xref: /linux-6.15/kernel/rcu/srcutree.c (revision b1e1f21f)
1 /*
2  * Sleepable Read-Copy Update mechanism for mutual exclusion.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, you can access it online at
16  * http://www.gnu.org/licenses/gpl-2.0.html.
17  *
18  * Copyright (C) IBM Corporation, 2006
19  * Copyright (C) Fujitsu, 2012
20  *
21  * Author: Paul McKenney <[email protected]>
22  *	   Lai Jiangshan <[email protected]>
23  *
24  * For detailed explanation of Read-Copy Update mechanism see -
25  *		Documentation/RCU/ *.txt
26  *
27  */
28 
29 #include <linux/export.h>
30 #include <linux/mutex.h>
31 #include <linux/percpu.h>
32 #include <linux/preempt.h>
33 #include <linux/rcupdate_wait.h>
34 #include <linux/sched.h>
35 #include <linux/smp.h>
36 #include <linux/delay.h>
37 #include <linux/module.h>
38 #include <linux/srcu.h>
39 
40 #include "rcu.h"
41 #include "rcu_segcblist.h"
42 
43 /* Holdoff in nanoseconds for auto-expediting. */
44 #define DEFAULT_SRCU_EXP_HOLDOFF (25 * 1000)
45 static ulong exp_holdoff = DEFAULT_SRCU_EXP_HOLDOFF;
46 module_param(exp_holdoff, ulong, 0444);
47 
48 /* Overflow-check frequency.  N bits roughly says every 2**N grace periods. */
49 static ulong counter_wrap_check = (ULONG_MAX >> 2);
50 module_param(counter_wrap_check, ulong, 0444);
51 
52 static void srcu_invoke_callbacks(struct work_struct *work);
53 static void srcu_reschedule(struct srcu_struct *sp, unsigned long delay);
54 static void process_srcu(struct work_struct *work);
55 
56 /* Wrappers for lock acquisition and release, see raw_spin_lock_rcu_node(). */
57 #define spin_lock_rcu_node(p)					\
58 do {									\
59 	spin_lock(&ACCESS_PRIVATE(p, lock));			\
60 	smp_mb__after_unlock_lock();					\
61 } while (0)
62 
63 #define spin_unlock_rcu_node(p) spin_unlock(&ACCESS_PRIVATE(p, lock))
64 
65 #define spin_lock_irq_rcu_node(p)					\
66 do {									\
67 	spin_lock_irq(&ACCESS_PRIVATE(p, lock));			\
68 	smp_mb__after_unlock_lock();					\
69 } while (0)
70 
71 #define spin_unlock_irq_rcu_node(p)					\
72 	spin_unlock_irq(&ACCESS_PRIVATE(p, lock))
73 
74 #define spin_lock_irqsave_rcu_node(p, flags)			\
75 do {									\
76 	spin_lock_irqsave(&ACCESS_PRIVATE(p, lock), flags);	\
77 	smp_mb__after_unlock_lock();					\
78 } while (0)
79 
80 #define spin_unlock_irqrestore_rcu_node(p, flags)			\
81 	spin_unlock_irqrestore(&ACCESS_PRIVATE(p, lock), flags)	\
82 
83 /*
84  * Initialize SRCU combining tree.  Note that statically allocated
85  * srcu_struct structures might already have srcu_read_lock() and
86  * srcu_read_unlock() running against them.  So if the is_static parameter
87  * is set, don't initialize ->srcu_lock_count[] and ->srcu_unlock_count[].
88  */
89 static void init_srcu_struct_nodes(struct srcu_struct *sp, bool is_static)
90 {
91 	int cpu;
92 	int i;
93 	int level = 0;
94 	int levelspread[RCU_NUM_LVLS];
95 	struct srcu_data *sdp;
96 	struct srcu_node *snp;
97 	struct srcu_node *snp_first;
98 
99 	/* Work out the overall tree geometry. */
100 	sp->level[0] = &sp->node[0];
101 	for (i = 1; i < rcu_num_lvls; i++)
102 		sp->level[i] = sp->level[i - 1] + num_rcu_lvl[i - 1];
103 	rcu_init_levelspread(levelspread, num_rcu_lvl);
104 
105 	/* Each pass through this loop initializes one srcu_node structure. */
106 	rcu_for_each_node_breadth_first(sp, snp) {
107 		spin_lock_init(&ACCESS_PRIVATE(snp, lock));
108 		WARN_ON_ONCE(ARRAY_SIZE(snp->srcu_have_cbs) !=
109 			     ARRAY_SIZE(snp->srcu_data_have_cbs));
110 		for (i = 0; i < ARRAY_SIZE(snp->srcu_have_cbs); i++) {
111 			snp->srcu_have_cbs[i] = 0;
112 			snp->srcu_data_have_cbs[i] = 0;
113 		}
114 		snp->srcu_gp_seq_needed_exp = 0;
115 		snp->grplo = -1;
116 		snp->grphi = -1;
117 		if (snp == &sp->node[0]) {
118 			/* Root node, special case. */
119 			snp->srcu_parent = NULL;
120 			continue;
121 		}
122 
123 		/* Non-root node. */
124 		if (snp == sp->level[level + 1])
125 			level++;
126 		snp->srcu_parent = sp->level[level - 1] +
127 				   (snp - sp->level[level]) /
128 				   levelspread[level - 1];
129 	}
130 
131 	/*
132 	 * Initialize the per-CPU srcu_data array, which feeds into the
133 	 * leaves of the srcu_node tree.
134 	 */
135 	WARN_ON_ONCE(ARRAY_SIZE(sdp->srcu_lock_count) !=
136 		     ARRAY_SIZE(sdp->srcu_unlock_count));
137 	level = rcu_num_lvls - 1;
138 	snp_first = sp->level[level];
139 	for_each_possible_cpu(cpu) {
140 		sdp = per_cpu_ptr(sp->sda, cpu);
141 		spin_lock_init(&ACCESS_PRIVATE(sdp, lock));
142 		rcu_segcblist_init(&sdp->srcu_cblist);
143 		sdp->srcu_cblist_invoking = false;
144 		sdp->srcu_gp_seq_needed = sp->srcu_gp_seq;
145 		sdp->srcu_gp_seq_needed_exp = sp->srcu_gp_seq;
146 		sdp->mynode = &snp_first[cpu / levelspread[level]];
147 		for (snp = sdp->mynode; snp != NULL; snp = snp->srcu_parent) {
148 			if (snp->grplo < 0)
149 				snp->grplo = cpu;
150 			snp->grphi = cpu;
151 		}
152 		sdp->cpu = cpu;
153 		INIT_DELAYED_WORK(&sdp->work, srcu_invoke_callbacks);
154 		sdp->sp = sp;
155 		sdp->grpmask = 1 << (cpu - sdp->mynode->grplo);
156 		if (is_static)
157 			continue;
158 
159 		/* Dynamically allocated, better be no srcu_read_locks()! */
160 		for (i = 0; i < ARRAY_SIZE(sdp->srcu_lock_count); i++) {
161 			sdp->srcu_lock_count[i] = 0;
162 			sdp->srcu_unlock_count[i] = 0;
163 		}
164 	}
165 }
166 
167 /*
168  * Initialize non-compile-time initialized fields, including the
169  * associated srcu_node and srcu_data structures.  The is_static
170  * parameter is passed through to init_srcu_struct_nodes(), and
171  * also tells us that ->sda has already been wired up to srcu_data.
172  */
173 static int init_srcu_struct_fields(struct srcu_struct *sp, bool is_static)
174 {
175 	mutex_init(&sp->srcu_cb_mutex);
176 	mutex_init(&sp->srcu_gp_mutex);
177 	sp->srcu_idx = 0;
178 	sp->srcu_gp_seq = 0;
179 	sp->srcu_barrier_seq = 0;
180 	mutex_init(&sp->srcu_barrier_mutex);
181 	atomic_set(&sp->srcu_barrier_cpu_cnt, 0);
182 	INIT_DELAYED_WORK(&sp->work, process_srcu);
183 	if (!is_static)
184 		sp->sda = alloc_percpu(struct srcu_data);
185 	init_srcu_struct_nodes(sp, is_static);
186 	sp->srcu_gp_seq_needed_exp = 0;
187 	sp->srcu_last_gp_end = ktime_get_mono_fast_ns();
188 	smp_store_release(&sp->srcu_gp_seq_needed, 0); /* Init done. */
189 	return sp->sda ? 0 : -ENOMEM;
190 }
191 
192 #ifdef CONFIG_DEBUG_LOCK_ALLOC
193 
194 int __init_srcu_struct(struct srcu_struct *sp, const char *name,
195 		       struct lock_class_key *key)
196 {
197 	/* Don't re-initialize a lock while it is held. */
198 	debug_check_no_locks_freed((void *)sp, sizeof(*sp));
199 	lockdep_init_map(&sp->dep_map, name, key, 0);
200 	spin_lock_init(&ACCESS_PRIVATE(sp, lock));
201 	return init_srcu_struct_fields(sp, false);
202 }
203 EXPORT_SYMBOL_GPL(__init_srcu_struct);
204 
205 #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
206 
207 /**
208  * init_srcu_struct - initialize a sleep-RCU structure
209  * @sp: structure to initialize.
210  *
211  * Must invoke this on a given srcu_struct before passing that srcu_struct
212  * to any other function.  Each srcu_struct represents a separate domain
213  * of SRCU protection.
214  */
215 int init_srcu_struct(struct srcu_struct *sp)
216 {
217 	spin_lock_init(&ACCESS_PRIVATE(sp, lock));
218 	return init_srcu_struct_fields(sp, false);
219 }
220 EXPORT_SYMBOL_GPL(init_srcu_struct);
221 
222 #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */
223 
224 /*
225  * First-use initialization of statically allocated srcu_struct
226  * structure.  Wiring up the combining tree is more than can be
227  * done with compile-time initialization, so this check is added
228  * to each update-side SRCU primitive.  Use sp->lock, which -is-
229  * compile-time initialized, to resolve races involving multiple
230  * CPUs trying to garner first-use privileges.
231  */
232 static void check_init_srcu_struct(struct srcu_struct *sp)
233 {
234 	unsigned long flags;
235 
236 	WARN_ON_ONCE(rcu_scheduler_active == RCU_SCHEDULER_INIT);
237 	/* The smp_load_acquire() pairs with the smp_store_release(). */
238 	if (!rcu_seq_state(smp_load_acquire(&sp->srcu_gp_seq_needed))) /*^^^*/
239 		return; /* Already initialized. */
240 	spin_lock_irqsave_rcu_node(sp, flags);
241 	if (!rcu_seq_state(sp->srcu_gp_seq_needed)) {
242 		spin_unlock_irqrestore_rcu_node(sp, flags);
243 		return;
244 	}
245 	init_srcu_struct_fields(sp, true);
246 	spin_unlock_irqrestore_rcu_node(sp, flags);
247 }
248 
249 /*
250  * Returns approximate total of the readers' ->srcu_lock_count[] values
251  * for the rank of per-CPU counters specified by idx.
252  */
253 static unsigned long srcu_readers_lock_idx(struct srcu_struct *sp, int idx)
254 {
255 	int cpu;
256 	unsigned long sum = 0;
257 
258 	for_each_possible_cpu(cpu) {
259 		struct srcu_data *cpuc = per_cpu_ptr(sp->sda, cpu);
260 
261 		sum += READ_ONCE(cpuc->srcu_lock_count[idx]);
262 	}
263 	return sum;
264 }
265 
266 /*
267  * Returns approximate total of the readers' ->srcu_unlock_count[] values
268  * for the rank of per-CPU counters specified by idx.
269  */
270 static unsigned long srcu_readers_unlock_idx(struct srcu_struct *sp, int idx)
271 {
272 	int cpu;
273 	unsigned long sum = 0;
274 
275 	for_each_possible_cpu(cpu) {
276 		struct srcu_data *cpuc = per_cpu_ptr(sp->sda, cpu);
277 
278 		sum += READ_ONCE(cpuc->srcu_unlock_count[idx]);
279 	}
280 	return sum;
281 }
282 
283 /*
284  * Return true if the number of pre-existing readers is determined to
285  * be zero.
286  */
287 static bool srcu_readers_active_idx_check(struct srcu_struct *sp, int idx)
288 {
289 	unsigned long unlocks;
290 
291 	unlocks = srcu_readers_unlock_idx(sp, idx);
292 
293 	/*
294 	 * Make sure that a lock is always counted if the corresponding
295 	 * unlock is counted. Needs to be a smp_mb() as the read side may
296 	 * contain a read from a variable that is written to before the
297 	 * synchronize_srcu() in the write side. In this case smp_mb()s
298 	 * A and B act like the store buffering pattern.
299 	 *
300 	 * This smp_mb() also pairs with smp_mb() C to prevent accesses
301 	 * after the synchronize_srcu() from being executed before the
302 	 * grace period ends.
303 	 */
304 	smp_mb(); /* A */
305 
306 	/*
307 	 * If the locks are the same as the unlocks, then there must have
308 	 * been no readers on this index at some time in between. This does
309 	 * not mean that there are no more readers, as one could have read
310 	 * the current index but not have incremented the lock counter yet.
311 	 *
312 	 * So suppose that the updater is preempted here for so long
313 	 * that more than ULONG_MAX non-nested readers come and go in
314 	 * the meantime.  It turns out that this cannot result in overflow
315 	 * because if a reader modifies its unlock count after we read it
316 	 * above, then that reader's next load of ->srcu_idx is guaranteed
317 	 * to get the new value, which will cause it to operate on the
318 	 * other bank of counters, where it cannot contribute to the
319 	 * overflow of these counters.  This means that there is a maximum
320 	 * of 2*NR_CPUS increments, which cannot overflow given current
321 	 * systems, especially not on 64-bit systems.
322 	 *
323 	 * OK, how about nesting?  This does impose a limit on nesting
324 	 * of floor(ULONG_MAX/NR_CPUS/2), which should be sufficient,
325 	 * especially on 64-bit systems.
326 	 */
327 	return srcu_readers_lock_idx(sp, idx) == unlocks;
328 }
329 
330 /**
331  * srcu_readers_active - returns true if there are readers. and false
332  *                       otherwise
333  * @sp: which srcu_struct to count active readers (holding srcu_read_lock).
334  *
335  * Note that this is not an atomic primitive, and can therefore suffer
336  * severe errors when invoked on an active srcu_struct.  That said, it
337  * can be useful as an error check at cleanup time.
338  */
339 static bool srcu_readers_active(struct srcu_struct *sp)
340 {
341 	int cpu;
342 	unsigned long sum = 0;
343 
344 	for_each_possible_cpu(cpu) {
345 		struct srcu_data *cpuc = per_cpu_ptr(sp->sda, cpu);
346 
347 		sum += READ_ONCE(cpuc->srcu_lock_count[0]);
348 		sum += READ_ONCE(cpuc->srcu_lock_count[1]);
349 		sum -= READ_ONCE(cpuc->srcu_unlock_count[0]);
350 		sum -= READ_ONCE(cpuc->srcu_unlock_count[1]);
351 	}
352 	return sum;
353 }
354 
355 #define SRCU_INTERVAL		1
356 
357 /*
358  * Return grace-period delay, zero if there are expedited grace
359  * periods pending, SRCU_INTERVAL otherwise.
360  */
361 static unsigned long srcu_get_delay(struct srcu_struct *sp)
362 {
363 	if (ULONG_CMP_LT(READ_ONCE(sp->srcu_gp_seq),
364 			 READ_ONCE(sp->srcu_gp_seq_needed_exp)))
365 		return 0;
366 	return SRCU_INTERVAL;
367 }
368 
369 /* Helper for cleanup_srcu_struct() and cleanup_srcu_struct_quiesced(). */
370 void _cleanup_srcu_struct(struct srcu_struct *sp, bool quiesced)
371 {
372 	int cpu;
373 
374 	if (WARN_ON(!srcu_get_delay(sp)))
375 		return; /* Just leak it! */
376 	if (WARN_ON(srcu_readers_active(sp)))
377 		return; /* Just leak it! */
378 	if (quiesced) {
379 		if (WARN_ON(delayed_work_pending(&sp->work)))
380 			return; /* Just leak it! */
381 	} else {
382 		flush_delayed_work(&sp->work);
383 	}
384 	for_each_possible_cpu(cpu)
385 		if (quiesced) {
386 			if (WARN_ON(delayed_work_pending(&per_cpu_ptr(sp->sda, cpu)->work)))
387 				return; /* Just leak it! */
388 		} else {
389 			flush_delayed_work(&per_cpu_ptr(sp->sda, cpu)->work);
390 		}
391 	if (WARN_ON(rcu_seq_state(READ_ONCE(sp->srcu_gp_seq)) != SRCU_STATE_IDLE) ||
392 	    WARN_ON(srcu_readers_active(sp))) {
393 		pr_info("%s: Active srcu_struct %p state: %d\n", __func__, sp, rcu_seq_state(READ_ONCE(sp->srcu_gp_seq)));
394 		return; /* Caller forgot to stop doing call_srcu()? */
395 	}
396 	free_percpu(sp->sda);
397 	sp->sda = NULL;
398 }
399 EXPORT_SYMBOL_GPL(_cleanup_srcu_struct);
400 
401 /*
402  * Counts the new reader in the appropriate per-CPU element of the
403  * srcu_struct.
404  * Returns an index that must be passed to the matching srcu_read_unlock().
405  */
406 int __srcu_read_lock(struct srcu_struct *sp)
407 {
408 	int idx;
409 
410 	idx = READ_ONCE(sp->srcu_idx) & 0x1;
411 	this_cpu_inc(sp->sda->srcu_lock_count[idx]);
412 	smp_mb(); /* B */  /* Avoid leaking the critical section. */
413 	return idx;
414 }
415 EXPORT_SYMBOL_GPL(__srcu_read_lock);
416 
417 /*
418  * Removes the count for the old reader from the appropriate per-CPU
419  * element of the srcu_struct.  Note that this may well be a different
420  * CPU than that which was incremented by the corresponding srcu_read_lock().
421  */
422 void __srcu_read_unlock(struct srcu_struct *sp, int idx)
423 {
424 	smp_mb(); /* C */  /* Avoid leaking the critical section. */
425 	this_cpu_inc(sp->sda->srcu_unlock_count[idx]);
426 }
427 EXPORT_SYMBOL_GPL(__srcu_read_unlock);
428 
429 /*
430  * We use an adaptive strategy for synchronize_srcu() and especially for
431  * synchronize_srcu_expedited().  We spin for a fixed time period
432  * (defined below) to allow SRCU readers to exit their read-side critical
433  * sections.  If there are still some readers after a few microseconds,
434  * we repeatedly block for 1-millisecond time periods.
435  */
436 #define SRCU_RETRY_CHECK_DELAY		5
437 
438 /*
439  * Start an SRCU grace period.
440  */
441 static void srcu_gp_start(struct srcu_struct *sp)
442 {
443 	struct srcu_data *sdp = this_cpu_ptr(sp->sda);
444 	int state;
445 
446 	lockdep_assert_held(&ACCESS_PRIVATE(sp, lock));
447 	WARN_ON_ONCE(ULONG_CMP_GE(sp->srcu_gp_seq, sp->srcu_gp_seq_needed));
448 	rcu_segcblist_advance(&sdp->srcu_cblist,
449 			      rcu_seq_current(&sp->srcu_gp_seq));
450 	(void)rcu_segcblist_accelerate(&sdp->srcu_cblist,
451 				       rcu_seq_snap(&sp->srcu_gp_seq));
452 	smp_mb(); /* Order prior store to ->srcu_gp_seq_needed vs. GP start. */
453 	rcu_seq_start(&sp->srcu_gp_seq);
454 	state = rcu_seq_state(READ_ONCE(sp->srcu_gp_seq));
455 	WARN_ON_ONCE(state != SRCU_STATE_SCAN1);
456 }
457 
458 /*
459  * Track online CPUs to guide callback workqueue placement.
460  */
461 DEFINE_PER_CPU(bool, srcu_online);
462 
463 void srcu_online_cpu(unsigned int cpu)
464 {
465 	WRITE_ONCE(per_cpu(srcu_online, cpu), true);
466 }
467 
468 void srcu_offline_cpu(unsigned int cpu)
469 {
470 	WRITE_ONCE(per_cpu(srcu_online, cpu), false);
471 }
472 
473 /*
474  * Place the workqueue handler on the specified CPU if online, otherwise
475  * just run it whereever.  This is useful for placing workqueue handlers
476  * that are to invoke the specified CPU's callbacks.
477  */
478 static bool srcu_queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
479 				       struct delayed_work *dwork,
480 				       unsigned long delay)
481 {
482 	bool ret;
483 
484 	preempt_disable();
485 	if (READ_ONCE(per_cpu(srcu_online, cpu)))
486 		ret = queue_delayed_work_on(cpu, wq, dwork, delay);
487 	else
488 		ret = queue_delayed_work(wq, dwork, delay);
489 	preempt_enable();
490 	return ret;
491 }
492 
493 /*
494  * Schedule callback invocation for the specified srcu_data structure,
495  * if possible, on the corresponding CPU.
496  */
497 static void srcu_schedule_cbs_sdp(struct srcu_data *sdp, unsigned long delay)
498 {
499 	srcu_queue_delayed_work_on(sdp->cpu, rcu_gp_wq, &sdp->work, delay);
500 }
501 
502 /*
503  * Schedule callback invocation for all srcu_data structures associated
504  * with the specified srcu_node structure that have callbacks for the
505  * just-completed grace period, the one corresponding to idx.  If possible,
506  * schedule this invocation on the corresponding CPUs.
507  */
508 static void srcu_schedule_cbs_snp(struct srcu_struct *sp, struct srcu_node *snp,
509 				  unsigned long mask, unsigned long delay)
510 {
511 	int cpu;
512 
513 	for (cpu = snp->grplo; cpu <= snp->grphi; cpu++) {
514 		if (!(mask & (1 << (cpu - snp->grplo))))
515 			continue;
516 		srcu_schedule_cbs_sdp(per_cpu_ptr(sp->sda, cpu), delay);
517 	}
518 }
519 
520 /*
521  * Note the end of an SRCU grace period.  Initiates callback invocation
522  * and starts a new grace period if needed.
523  *
524  * The ->srcu_cb_mutex acquisition does not protect any data, but
525  * instead prevents more than one grace period from starting while we
526  * are initiating callback invocation.  This allows the ->srcu_have_cbs[]
527  * array to have a finite number of elements.
528  */
529 static void srcu_gp_end(struct srcu_struct *sp)
530 {
531 	unsigned long cbdelay;
532 	bool cbs;
533 	bool last_lvl;
534 	int cpu;
535 	unsigned long flags;
536 	unsigned long gpseq;
537 	int idx;
538 	unsigned long mask;
539 	struct srcu_data *sdp;
540 	struct srcu_node *snp;
541 
542 	/* Prevent more than one additional grace period. */
543 	mutex_lock(&sp->srcu_cb_mutex);
544 
545 	/* End the current grace period. */
546 	spin_lock_irq_rcu_node(sp);
547 	idx = rcu_seq_state(sp->srcu_gp_seq);
548 	WARN_ON_ONCE(idx != SRCU_STATE_SCAN2);
549 	cbdelay = srcu_get_delay(sp);
550 	sp->srcu_last_gp_end = ktime_get_mono_fast_ns();
551 	rcu_seq_end(&sp->srcu_gp_seq);
552 	gpseq = rcu_seq_current(&sp->srcu_gp_seq);
553 	if (ULONG_CMP_LT(sp->srcu_gp_seq_needed_exp, gpseq))
554 		sp->srcu_gp_seq_needed_exp = gpseq;
555 	spin_unlock_irq_rcu_node(sp);
556 	mutex_unlock(&sp->srcu_gp_mutex);
557 	/* A new grace period can start at this point.  But only one. */
558 
559 	/* Initiate callback invocation as needed. */
560 	idx = rcu_seq_ctr(gpseq) % ARRAY_SIZE(snp->srcu_have_cbs);
561 	rcu_for_each_node_breadth_first(sp, snp) {
562 		spin_lock_irq_rcu_node(snp);
563 		cbs = false;
564 		last_lvl = snp >= sp->level[rcu_num_lvls - 1];
565 		if (last_lvl)
566 			cbs = snp->srcu_have_cbs[idx] == gpseq;
567 		snp->srcu_have_cbs[idx] = gpseq;
568 		rcu_seq_set_state(&snp->srcu_have_cbs[idx], 1);
569 		if (ULONG_CMP_LT(snp->srcu_gp_seq_needed_exp, gpseq))
570 			snp->srcu_gp_seq_needed_exp = gpseq;
571 		mask = snp->srcu_data_have_cbs[idx];
572 		snp->srcu_data_have_cbs[idx] = 0;
573 		spin_unlock_irq_rcu_node(snp);
574 		if (cbs)
575 			srcu_schedule_cbs_snp(sp, snp, mask, cbdelay);
576 
577 		/* Occasionally prevent srcu_data counter wrap. */
578 		if (!(gpseq & counter_wrap_check) && last_lvl)
579 			for (cpu = snp->grplo; cpu <= snp->grphi; cpu++) {
580 				sdp = per_cpu_ptr(sp->sda, cpu);
581 				spin_lock_irqsave_rcu_node(sdp, flags);
582 				if (ULONG_CMP_GE(gpseq,
583 						 sdp->srcu_gp_seq_needed + 100))
584 					sdp->srcu_gp_seq_needed = gpseq;
585 				if (ULONG_CMP_GE(gpseq,
586 						 sdp->srcu_gp_seq_needed_exp + 100))
587 					sdp->srcu_gp_seq_needed_exp = gpseq;
588 				spin_unlock_irqrestore_rcu_node(sdp, flags);
589 			}
590 	}
591 
592 	/* Callback initiation done, allow grace periods after next. */
593 	mutex_unlock(&sp->srcu_cb_mutex);
594 
595 	/* Start a new grace period if needed. */
596 	spin_lock_irq_rcu_node(sp);
597 	gpseq = rcu_seq_current(&sp->srcu_gp_seq);
598 	if (!rcu_seq_state(gpseq) &&
599 	    ULONG_CMP_LT(gpseq, sp->srcu_gp_seq_needed)) {
600 		srcu_gp_start(sp);
601 		spin_unlock_irq_rcu_node(sp);
602 		srcu_reschedule(sp, 0);
603 	} else {
604 		spin_unlock_irq_rcu_node(sp);
605 	}
606 }
607 
608 /*
609  * Funnel-locking scheme to scalably mediate many concurrent expedited
610  * grace-period requests.  This function is invoked for the first known
611  * expedited request for a grace period that has already been requested,
612  * but without expediting.  To start a completely new grace period,
613  * whether expedited or not, use srcu_funnel_gp_start() instead.
614  */
615 static void srcu_funnel_exp_start(struct srcu_struct *sp, struct srcu_node *snp,
616 				  unsigned long s)
617 {
618 	unsigned long flags;
619 
620 	for (; snp != NULL; snp = snp->srcu_parent) {
621 		if (rcu_seq_done(&sp->srcu_gp_seq, s) ||
622 		    ULONG_CMP_GE(READ_ONCE(snp->srcu_gp_seq_needed_exp), s))
623 			return;
624 		spin_lock_irqsave_rcu_node(snp, flags);
625 		if (ULONG_CMP_GE(snp->srcu_gp_seq_needed_exp, s)) {
626 			spin_unlock_irqrestore_rcu_node(snp, flags);
627 			return;
628 		}
629 		WRITE_ONCE(snp->srcu_gp_seq_needed_exp, s);
630 		spin_unlock_irqrestore_rcu_node(snp, flags);
631 	}
632 	spin_lock_irqsave_rcu_node(sp, flags);
633 	if (ULONG_CMP_LT(sp->srcu_gp_seq_needed_exp, s))
634 		sp->srcu_gp_seq_needed_exp = s;
635 	spin_unlock_irqrestore_rcu_node(sp, flags);
636 }
637 
638 /*
639  * Funnel-locking scheme to scalably mediate many concurrent grace-period
640  * requests.  The winner has to do the work of actually starting grace
641  * period s.  Losers must either ensure that their desired grace-period
642  * number is recorded on at least their leaf srcu_node structure, or they
643  * must take steps to invoke their own callbacks.
644  *
645  * Note that this function also does the work of srcu_funnel_exp_start(),
646  * in some cases by directly invoking it.
647  */
648 static void srcu_funnel_gp_start(struct srcu_struct *sp, struct srcu_data *sdp,
649 				 unsigned long s, bool do_norm)
650 {
651 	unsigned long flags;
652 	int idx = rcu_seq_ctr(s) % ARRAY_SIZE(sdp->mynode->srcu_have_cbs);
653 	struct srcu_node *snp = sdp->mynode;
654 	unsigned long snp_seq;
655 
656 	/* Each pass through the loop does one level of the srcu_node tree. */
657 	for (; snp != NULL; snp = snp->srcu_parent) {
658 		if (rcu_seq_done(&sp->srcu_gp_seq, s) && snp != sdp->mynode)
659 			return; /* GP already done and CBs recorded. */
660 		spin_lock_irqsave_rcu_node(snp, flags);
661 		if (ULONG_CMP_GE(snp->srcu_have_cbs[idx], s)) {
662 			snp_seq = snp->srcu_have_cbs[idx];
663 			if (snp == sdp->mynode && snp_seq == s)
664 				snp->srcu_data_have_cbs[idx] |= sdp->grpmask;
665 			spin_unlock_irqrestore_rcu_node(snp, flags);
666 			if (snp == sdp->mynode && snp_seq != s) {
667 				srcu_schedule_cbs_sdp(sdp, do_norm
668 							   ? SRCU_INTERVAL
669 							   : 0);
670 				return;
671 			}
672 			if (!do_norm)
673 				srcu_funnel_exp_start(sp, snp, s);
674 			return;
675 		}
676 		snp->srcu_have_cbs[idx] = s;
677 		if (snp == sdp->mynode)
678 			snp->srcu_data_have_cbs[idx] |= sdp->grpmask;
679 		if (!do_norm && ULONG_CMP_LT(snp->srcu_gp_seq_needed_exp, s))
680 			snp->srcu_gp_seq_needed_exp = s;
681 		spin_unlock_irqrestore_rcu_node(snp, flags);
682 	}
683 
684 	/* Top of tree, must ensure the grace period will be started. */
685 	spin_lock_irqsave_rcu_node(sp, flags);
686 	if (ULONG_CMP_LT(sp->srcu_gp_seq_needed, s)) {
687 		/*
688 		 * Record need for grace period s.  Pair with load
689 		 * acquire setting up for initialization.
690 		 */
691 		smp_store_release(&sp->srcu_gp_seq_needed, s); /*^^^*/
692 	}
693 	if (!do_norm && ULONG_CMP_LT(sp->srcu_gp_seq_needed_exp, s))
694 		sp->srcu_gp_seq_needed_exp = s;
695 
696 	/* If grace period not already done and none in progress, start it. */
697 	if (!rcu_seq_done(&sp->srcu_gp_seq, s) &&
698 	    rcu_seq_state(sp->srcu_gp_seq) == SRCU_STATE_IDLE) {
699 		WARN_ON_ONCE(ULONG_CMP_GE(sp->srcu_gp_seq, sp->srcu_gp_seq_needed));
700 		srcu_gp_start(sp);
701 		queue_delayed_work(rcu_gp_wq, &sp->work, srcu_get_delay(sp));
702 	}
703 	spin_unlock_irqrestore_rcu_node(sp, flags);
704 }
705 
706 /*
707  * Wait until all readers counted by array index idx complete, but
708  * loop an additional time if there is an expedited grace period pending.
709  * The caller must ensure that ->srcu_idx is not changed while checking.
710  */
711 static bool try_check_zero(struct srcu_struct *sp, int idx, int trycount)
712 {
713 	for (;;) {
714 		if (srcu_readers_active_idx_check(sp, idx))
715 			return true;
716 		if (--trycount + !srcu_get_delay(sp) <= 0)
717 			return false;
718 		udelay(SRCU_RETRY_CHECK_DELAY);
719 	}
720 }
721 
722 /*
723  * Increment the ->srcu_idx counter so that future SRCU readers will
724  * use the other rank of the ->srcu_(un)lock_count[] arrays.  This allows
725  * us to wait for pre-existing readers in a starvation-free manner.
726  */
727 static void srcu_flip(struct srcu_struct *sp)
728 {
729 	/*
730 	 * Ensure that if this updater saw a given reader's increment
731 	 * from __srcu_read_lock(), that reader was using an old value
732 	 * of ->srcu_idx.  Also ensure that if a given reader sees the
733 	 * new value of ->srcu_idx, this updater's earlier scans cannot
734 	 * have seen that reader's increments (which is OK, because this
735 	 * grace period need not wait on that reader).
736 	 */
737 	smp_mb(); /* E */  /* Pairs with B and C. */
738 
739 	WRITE_ONCE(sp->srcu_idx, sp->srcu_idx + 1);
740 
741 	/*
742 	 * Ensure that if the updater misses an __srcu_read_unlock()
743 	 * increment, that task's next __srcu_read_lock() will see the
744 	 * above counter update.  Note that both this memory barrier
745 	 * and the one in srcu_readers_active_idx_check() provide the
746 	 * guarantee for __srcu_read_lock().
747 	 */
748 	smp_mb(); /* D */  /* Pairs with C. */
749 }
750 
751 /*
752  * If SRCU is likely idle, return true, otherwise return false.
753  *
754  * Note that it is OK for several current from-idle requests for a new
755  * grace period from idle to specify expediting because they will all end
756  * up requesting the same grace period anyhow.  So no loss.
757  *
758  * Note also that if any CPU (including the current one) is still invoking
759  * callbacks, this function will nevertheless say "idle".  This is not
760  * ideal, but the overhead of checking all CPUs' callback lists is even
761  * less ideal, especially on large systems.  Furthermore, the wakeup
762  * can happen before the callback is fully removed, so we have no choice
763  * but to accept this type of error.
764  *
765  * This function is also subject to counter-wrap errors, but let's face
766  * it, if this function was preempted for enough time for the counters
767  * to wrap, it really doesn't matter whether or not we expedite the grace
768  * period.  The extra overhead of a needlessly expedited grace period is
769  * negligible when amoritized over that time period, and the extra latency
770  * of a needlessly non-expedited grace period is similarly negligible.
771  */
772 static bool srcu_might_be_idle(struct srcu_struct *sp)
773 {
774 	unsigned long curseq;
775 	unsigned long flags;
776 	struct srcu_data *sdp;
777 	unsigned long t;
778 
779 	/* If the local srcu_data structure has callbacks, not idle.  */
780 	local_irq_save(flags);
781 	sdp = this_cpu_ptr(sp->sda);
782 	if (rcu_segcblist_pend_cbs(&sdp->srcu_cblist)) {
783 		local_irq_restore(flags);
784 		return false; /* Callbacks already present, so not idle. */
785 	}
786 	local_irq_restore(flags);
787 
788 	/*
789 	 * No local callbacks, so probabalistically probe global state.
790 	 * Exact information would require acquiring locks, which would
791 	 * kill scalability, hence the probabalistic nature of the probe.
792 	 */
793 
794 	/* First, see if enough time has passed since the last GP. */
795 	t = ktime_get_mono_fast_ns();
796 	if (exp_holdoff == 0 ||
797 	    time_in_range_open(t, sp->srcu_last_gp_end,
798 			       sp->srcu_last_gp_end + exp_holdoff))
799 		return false; /* Too soon after last GP. */
800 
801 	/* Next, check for probable idleness. */
802 	curseq = rcu_seq_current(&sp->srcu_gp_seq);
803 	smp_mb(); /* Order ->srcu_gp_seq with ->srcu_gp_seq_needed. */
804 	if (ULONG_CMP_LT(curseq, READ_ONCE(sp->srcu_gp_seq_needed)))
805 		return false; /* Grace period in progress, so not idle. */
806 	smp_mb(); /* Order ->srcu_gp_seq with prior access. */
807 	if (curseq != rcu_seq_current(&sp->srcu_gp_seq))
808 		return false; /* GP # changed, so not idle. */
809 	return true; /* With reasonable probability, idle! */
810 }
811 
812 /*
813  * SRCU callback function to leak a callback.
814  */
815 static void srcu_leak_callback(struct rcu_head *rhp)
816 {
817 }
818 
819 /*
820  * Enqueue an SRCU callback on the srcu_data structure associated with
821  * the current CPU and the specified srcu_struct structure, initiating
822  * grace-period processing if it is not already running.
823  *
824  * Note that all CPUs must agree that the grace period extended beyond
825  * all pre-existing SRCU read-side critical section.  On systems with
826  * more than one CPU, this means that when "func()" is invoked, each CPU
827  * is guaranteed to have executed a full memory barrier since the end of
828  * its last corresponding SRCU read-side critical section whose beginning
829  * preceded the call to call_srcu().  It also means that each CPU executing
830  * an SRCU read-side critical section that continues beyond the start of
831  * "func()" must have executed a memory barrier after the call_srcu()
832  * but before the beginning of that SRCU read-side critical section.
833  * Note that these guarantees include CPUs that are offline, idle, or
834  * executing in user mode, as well as CPUs that are executing in the kernel.
835  *
836  * Furthermore, if CPU A invoked call_srcu() and CPU B invoked the
837  * resulting SRCU callback function "func()", then both CPU A and CPU
838  * B are guaranteed to execute a full memory barrier during the time
839  * interval between the call to call_srcu() and the invocation of "func()".
840  * This guarantee applies even if CPU A and CPU B are the same CPU (but
841  * again only if the system has more than one CPU).
842  *
843  * Of course, these guarantees apply only for invocations of call_srcu(),
844  * srcu_read_lock(), and srcu_read_unlock() that are all passed the same
845  * srcu_struct structure.
846  */
847 void __call_srcu(struct srcu_struct *sp, struct rcu_head *rhp,
848 		 rcu_callback_t func, bool do_norm)
849 {
850 	unsigned long flags;
851 	bool needexp = false;
852 	bool needgp = false;
853 	unsigned long s;
854 	struct srcu_data *sdp;
855 
856 	check_init_srcu_struct(sp);
857 	if (debug_rcu_head_queue(rhp)) {
858 		/* Probable double call_srcu(), so leak the callback. */
859 		WRITE_ONCE(rhp->func, srcu_leak_callback);
860 		WARN_ONCE(1, "call_srcu(): Leaked duplicate callback\n");
861 		return;
862 	}
863 	rhp->func = func;
864 	local_irq_save(flags);
865 	sdp = this_cpu_ptr(sp->sda);
866 	spin_lock_rcu_node(sdp);
867 	rcu_segcblist_enqueue(&sdp->srcu_cblist, rhp, false);
868 	rcu_segcblist_advance(&sdp->srcu_cblist,
869 			      rcu_seq_current(&sp->srcu_gp_seq));
870 	s = rcu_seq_snap(&sp->srcu_gp_seq);
871 	(void)rcu_segcblist_accelerate(&sdp->srcu_cblist, s);
872 	if (ULONG_CMP_LT(sdp->srcu_gp_seq_needed, s)) {
873 		sdp->srcu_gp_seq_needed = s;
874 		needgp = true;
875 	}
876 	if (!do_norm && ULONG_CMP_LT(sdp->srcu_gp_seq_needed_exp, s)) {
877 		sdp->srcu_gp_seq_needed_exp = s;
878 		needexp = true;
879 	}
880 	spin_unlock_irqrestore_rcu_node(sdp, flags);
881 	if (needgp)
882 		srcu_funnel_gp_start(sp, sdp, s, do_norm);
883 	else if (needexp)
884 		srcu_funnel_exp_start(sp, sdp->mynode, s);
885 }
886 
887 /**
888  * call_srcu() - Queue a callback for invocation after an SRCU grace period
889  * @sp: srcu_struct in queue the callback
890  * @rhp: structure to be used for queueing the SRCU callback.
891  * @func: function to be invoked after the SRCU grace period
892  *
893  * The callback function will be invoked some time after a full SRCU
894  * grace period elapses, in other words after all pre-existing SRCU
895  * read-side critical sections have completed.  However, the callback
896  * function might well execute concurrently with other SRCU read-side
897  * critical sections that started after call_srcu() was invoked.  SRCU
898  * read-side critical sections are delimited by srcu_read_lock() and
899  * srcu_read_unlock(), and may be nested.
900  *
901  * The callback will be invoked from process context, but must nevertheless
902  * be fast and must not block.
903  */
904 void call_srcu(struct srcu_struct *sp, struct rcu_head *rhp,
905 	       rcu_callback_t func)
906 {
907 	__call_srcu(sp, rhp, func, true);
908 }
909 EXPORT_SYMBOL_GPL(call_srcu);
910 
911 /*
912  * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
913  */
914 static void __synchronize_srcu(struct srcu_struct *sp, bool do_norm)
915 {
916 	struct rcu_synchronize rcu;
917 
918 	RCU_LOCKDEP_WARN(lock_is_held(&sp->dep_map) ||
919 			 lock_is_held(&rcu_bh_lock_map) ||
920 			 lock_is_held(&rcu_lock_map) ||
921 			 lock_is_held(&rcu_sched_lock_map),
922 			 "Illegal synchronize_srcu() in same-type SRCU (or in RCU) read-side critical section");
923 
924 	if (rcu_scheduler_active == RCU_SCHEDULER_INACTIVE)
925 		return;
926 	might_sleep();
927 	check_init_srcu_struct(sp);
928 	init_completion(&rcu.completion);
929 	init_rcu_head_on_stack(&rcu.head);
930 	__call_srcu(sp, &rcu.head, wakeme_after_rcu, do_norm);
931 	wait_for_completion(&rcu.completion);
932 	destroy_rcu_head_on_stack(&rcu.head);
933 
934 	/*
935 	 * Make sure that later code is ordered after the SRCU grace
936 	 * period.  This pairs with the spin_lock_irq_rcu_node()
937 	 * in srcu_invoke_callbacks().  Unlike Tree RCU, this is needed
938 	 * because the current CPU might have been totally uninvolved with
939 	 * (and thus unordered against) that grace period.
940 	 */
941 	smp_mb();
942 }
943 
944 /**
945  * synchronize_srcu_expedited - Brute-force SRCU grace period
946  * @sp: srcu_struct with which to synchronize.
947  *
948  * Wait for an SRCU grace period to elapse, but be more aggressive about
949  * spinning rather than blocking when waiting.
950  *
951  * Note that synchronize_srcu_expedited() has the same deadlock and
952  * memory-ordering properties as does synchronize_srcu().
953  */
954 void synchronize_srcu_expedited(struct srcu_struct *sp)
955 {
956 	__synchronize_srcu(sp, rcu_gp_is_normal());
957 }
958 EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
959 
960 /**
961  * synchronize_srcu - wait for prior SRCU read-side critical-section completion
962  * @sp: srcu_struct with which to synchronize.
963  *
964  * Wait for the count to drain to zero of both indexes. To avoid the
965  * possible starvation of synchronize_srcu(), it waits for the count of
966  * the index=((->srcu_idx & 1) ^ 1) to drain to zero at first,
967  * and then flip the srcu_idx and wait for the count of the other index.
968  *
969  * Can block; must be called from process context.
970  *
971  * Note that it is illegal to call synchronize_srcu() from the corresponding
972  * SRCU read-side critical section; doing so will result in deadlock.
973  * However, it is perfectly legal to call synchronize_srcu() on one
974  * srcu_struct from some other srcu_struct's read-side critical section,
975  * as long as the resulting graph of srcu_structs is acyclic.
976  *
977  * There are memory-ordering constraints implied by synchronize_srcu().
978  * On systems with more than one CPU, when synchronize_srcu() returns,
979  * each CPU is guaranteed to have executed a full memory barrier since
980  * the end of its last corresponding SRCU-sched read-side critical section
981  * whose beginning preceded the call to synchronize_srcu().  In addition,
982  * each CPU having an SRCU read-side critical section that extends beyond
983  * the return from synchronize_srcu() is guaranteed to have executed a
984  * full memory barrier after the beginning of synchronize_srcu() and before
985  * the beginning of that SRCU read-side critical section.  Note that these
986  * guarantees include CPUs that are offline, idle, or executing in user mode,
987  * as well as CPUs that are executing in the kernel.
988  *
989  * Furthermore, if CPU A invoked synchronize_srcu(), which returned
990  * to its caller on CPU B, then both CPU A and CPU B are guaranteed
991  * to have executed a full memory barrier during the execution of
992  * synchronize_srcu().  This guarantee applies even if CPU A and CPU B
993  * are the same CPU, but again only if the system has more than one CPU.
994  *
995  * Of course, these memory-ordering guarantees apply only when
996  * synchronize_srcu(), srcu_read_lock(), and srcu_read_unlock() are
997  * passed the same srcu_struct structure.
998  *
999  * If SRCU is likely idle, expedite the first request.  This semantic
1000  * was provided by Classic SRCU, and is relied upon by its users, so TREE
1001  * SRCU must also provide it.  Note that detecting idleness is heuristic
1002  * and subject to both false positives and negatives.
1003  */
1004 void synchronize_srcu(struct srcu_struct *sp)
1005 {
1006 	if (srcu_might_be_idle(sp) || rcu_gp_is_expedited())
1007 		synchronize_srcu_expedited(sp);
1008 	else
1009 		__synchronize_srcu(sp, true);
1010 }
1011 EXPORT_SYMBOL_GPL(synchronize_srcu);
1012 
1013 /*
1014  * Callback function for srcu_barrier() use.
1015  */
1016 static void srcu_barrier_cb(struct rcu_head *rhp)
1017 {
1018 	struct srcu_data *sdp;
1019 	struct srcu_struct *sp;
1020 
1021 	sdp = container_of(rhp, struct srcu_data, srcu_barrier_head);
1022 	sp = sdp->sp;
1023 	if (atomic_dec_and_test(&sp->srcu_barrier_cpu_cnt))
1024 		complete(&sp->srcu_barrier_completion);
1025 }
1026 
1027 /**
1028  * srcu_barrier - Wait until all in-flight call_srcu() callbacks complete.
1029  * @sp: srcu_struct on which to wait for in-flight callbacks.
1030  */
1031 void srcu_barrier(struct srcu_struct *sp)
1032 {
1033 	int cpu;
1034 	struct srcu_data *sdp;
1035 	unsigned long s = rcu_seq_snap(&sp->srcu_barrier_seq);
1036 
1037 	check_init_srcu_struct(sp);
1038 	mutex_lock(&sp->srcu_barrier_mutex);
1039 	if (rcu_seq_done(&sp->srcu_barrier_seq, s)) {
1040 		smp_mb(); /* Force ordering following return. */
1041 		mutex_unlock(&sp->srcu_barrier_mutex);
1042 		return; /* Someone else did our work for us. */
1043 	}
1044 	rcu_seq_start(&sp->srcu_barrier_seq);
1045 	init_completion(&sp->srcu_barrier_completion);
1046 
1047 	/* Initial count prevents reaching zero until all CBs are posted. */
1048 	atomic_set(&sp->srcu_barrier_cpu_cnt, 1);
1049 
1050 	/*
1051 	 * Each pass through this loop enqueues a callback, but only
1052 	 * on CPUs already having callbacks enqueued.  Note that if
1053 	 * a CPU already has callbacks enqueue, it must have already
1054 	 * registered the need for a future grace period, so all we
1055 	 * need do is enqueue a callback that will use the same
1056 	 * grace period as the last callback already in the queue.
1057 	 */
1058 	for_each_possible_cpu(cpu) {
1059 		sdp = per_cpu_ptr(sp->sda, cpu);
1060 		spin_lock_irq_rcu_node(sdp);
1061 		atomic_inc(&sp->srcu_barrier_cpu_cnt);
1062 		sdp->srcu_barrier_head.func = srcu_barrier_cb;
1063 		debug_rcu_head_queue(&sdp->srcu_barrier_head);
1064 		if (!rcu_segcblist_entrain(&sdp->srcu_cblist,
1065 					   &sdp->srcu_barrier_head, 0)) {
1066 			debug_rcu_head_unqueue(&sdp->srcu_barrier_head);
1067 			atomic_dec(&sp->srcu_barrier_cpu_cnt);
1068 		}
1069 		spin_unlock_irq_rcu_node(sdp);
1070 	}
1071 
1072 	/* Remove the initial count, at which point reaching zero can happen. */
1073 	if (atomic_dec_and_test(&sp->srcu_barrier_cpu_cnt))
1074 		complete(&sp->srcu_barrier_completion);
1075 	wait_for_completion(&sp->srcu_barrier_completion);
1076 
1077 	rcu_seq_end(&sp->srcu_barrier_seq);
1078 	mutex_unlock(&sp->srcu_barrier_mutex);
1079 }
1080 EXPORT_SYMBOL_GPL(srcu_barrier);
1081 
1082 /**
1083  * srcu_batches_completed - return batches completed.
1084  * @sp: srcu_struct on which to report batch completion.
1085  *
1086  * Report the number of batches, correlated with, but not necessarily
1087  * precisely the same as, the number of grace periods that have elapsed.
1088  */
1089 unsigned long srcu_batches_completed(struct srcu_struct *sp)
1090 {
1091 	return sp->srcu_idx;
1092 }
1093 EXPORT_SYMBOL_GPL(srcu_batches_completed);
1094 
1095 /*
1096  * Core SRCU state machine.  Push state bits of ->srcu_gp_seq
1097  * to SRCU_STATE_SCAN2, and invoke srcu_gp_end() when scan has
1098  * completed in that state.
1099  */
1100 static void srcu_advance_state(struct srcu_struct *sp)
1101 {
1102 	int idx;
1103 
1104 	mutex_lock(&sp->srcu_gp_mutex);
1105 
1106 	/*
1107 	 * Because readers might be delayed for an extended period after
1108 	 * fetching ->srcu_idx for their index, at any point in time there
1109 	 * might well be readers using both idx=0 and idx=1.  We therefore
1110 	 * need to wait for readers to clear from both index values before
1111 	 * invoking a callback.
1112 	 *
1113 	 * The load-acquire ensures that we see the accesses performed
1114 	 * by the prior grace period.
1115 	 */
1116 	idx = rcu_seq_state(smp_load_acquire(&sp->srcu_gp_seq)); /* ^^^ */
1117 	if (idx == SRCU_STATE_IDLE) {
1118 		spin_lock_irq_rcu_node(sp);
1119 		if (ULONG_CMP_GE(sp->srcu_gp_seq, sp->srcu_gp_seq_needed)) {
1120 			WARN_ON_ONCE(rcu_seq_state(sp->srcu_gp_seq));
1121 			spin_unlock_irq_rcu_node(sp);
1122 			mutex_unlock(&sp->srcu_gp_mutex);
1123 			return;
1124 		}
1125 		idx = rcu_seq_state(READ_ONCE(sp->srcu_gp_seq));
1126 		if (idx == SRCU_STATE_IDLE)
1127 			srcu_gp_start(sp);
1128 		spin_unlock_irq_rcu_node(sp);
1129 		if (idx != SRCU_STATE_IDLE) {
1130 			mutex_unlock(&sp->srcu_gp_mutex);
1131 			return; /* Someone else started the grace period. */
1132 		}
1133 	}
1134 
1135 	if (rcu_seq_state(READ_ONCE(sp->srcu_gp_seq)) == SRCU_STATE_SCAN1) {
1136 		idx = 1 ^ (sp->srcu_idx & 1);
1137 		if (!try_check_zero(sp, idx, 1)) {
1138 			mutex_unlock(&sp->srcu_gp_mutex);
1139 			return; /* readers present, retry later. */
1140 		}
1141 		srcu_flip(sp);
1142 		rcu_seq_set_state(&sp->srcu_gp_seq, SRCU_STATE_SCAN2);
1143 	}
1144 
1145 	if (rcu_seq_state(READ_ONCE(sp->srcu_gp_seq)) == SRCU_STATE_SCAN2) {
1146 
1147 		/*
1148 		 * SRCU read-side critical sections are normally short,
1149 		 * so check at least twice in quick succession after a flip.
1150 		 */
1151 		idx = 1 ^ (sp->srcu_idx & 1);
1152 		if (!try_check_zero(sp, idx, 2)) {
1153 			mutex_unlock(&sp->srcu_gp_mutex);
1154 			return; /* readers present, retry later. */
1155 		}
1156 		srcu_gp_end(sp);  /* Releases ->srcu_gp_mutex. */
1157 	}
1158 }
1159 
1160 /*
1161  * Invoke a limited number of SRCU callbacks that have passed through
1162  * their grace period.  If there are more to do, SRCU will reschedule
1163  * the workqueue.  Note that needed memory barriers have been executed
1164  * in this task's context by srcu_readers_active_idx_check().
1165  */
1166 static void srcu_invoke_callbacks(struct work_struct *work)
1167 {
1168 	bool more;
1169 	struct rcu_cblist ready_cbs;
1170 	struct rcu_head *rhp;
1171 	struct srcu_data *sdp;
1172 	struct srcu_struct *sp;
1173 
1174 	sdp = container_of(work, struct srcu_data, work.work);
1175 	sp = sdp->sp;
1176 	rcu_cblist_init(&ready_cbs);
1177 	spin_lock_irq_rcu_node(sdp);
1178 	rcu_segcblist_advance(&sdp->srcu_cblist,
1179 			      rcu_seq_current(&sp->srcu_gp_seq));
1180 	if (sdp->srcu_cblist_invoking ||
1181 	    !rcu_segcblist_ready_cbs(&sdp->srcu_cblist)) {
1182 		spin_unlock_irq_rcu_node(sdp);
1183 		return;  /* Someone else on the job or nothing to do. */
1184 	}
1185 
1186 	/* We are on the job!  Extract and invoke ready callbacks. */
1187 	sdp->srcu_cblist_invoking = true;
1188 	rcu_segcblist_extract_done_cbs(&sdp->srcu_cblist, &ready_cbs);
1189 	spin_unlock_irq_rcu_node(sdp);
1190 	rhp = rcu_cblist_dequeue(&ready_cbs);
1191 	for (; rhp != NULL; rhp = rcu_cblist_dequeue(&ready_cbs)) {
1192 		debug_rcu_head_unqueue(rhp);
1193 		local_bh_disable();
1194 		rhp->func(rhp);
1195 		local_bh_enable();
1196 	}
1197 
1198 	/*
1199 	 * Update counts, accelerate new callbacks, and if needed,
1200 	 * schedule another round of callback invocation.
1201 	 */
1202 	spin_lock_irq_rcu_node(sdp);
1203 	rcu_segcblist_insert_count(&sdp->srcu_cblist, &ready_cbs);
1204 	(void)rcu_segcblist_accelerate(&sdp->srcu_cblist,
1205 				       rcu_seq_snap(&sp->srcu_gp_seq));
1206 	sdp->srcu_cblist_invoking = false;
1207 	more = rcu_segcblist_ready_cbs(&sdp->srcu_cblist);
1208 	spin_unlock_irq_rcu_node(sdp);
1209 	if (more)
1210 		srcu_schedule_cbs_sdp(sdp, 0);
1211 }
1212 
1213 /*
1214  * Finished one round of SRCU grace period.  Start another if there are
1215  * more SRCU callbacks queued, otherwise put SRCU into not-running state.
1216  */
1217 static void srcu_reschedule(struct srcu_struct *sp, unsigned long delay)
1218 {
1219 	bool pushgp = true;
1220 
1221 	spin_lock_irq_rcu_node(sp);
1222 	if (ULONG_CMP_GE(sp->srcu_gp_seq, sp->srcu_gp_seq_needed)) {
1223 		if (!WARN_ON_ONCE(rcu_seq_state(sp->srcu_gp_seq))) {
1224 			/* All requests fulfilled, time to go idle. */
1225 			pushgp = false;
1226 		}
1227 	} else if (!rcu_seq_state(sp->srcu_gp_seq)) {
1228 		/* Outstanding request and no GP.  Start one. */
1229 		srcu_gp_start(sp);
1230 	}
1231 	spin_unlock_irq_rcu_node(sp);
1232 
1233 	if (pushgp)
1234 		queue_delayed_work(rcu_gp_wq, &sp->work, delay);
1235 }
1236 
1237 /*
1238  * This is the work-queue function that handles SRCU grace periods.
1239  */
1240 static void process_srcu(struct work_struct *work)
1241 {
1242 	struct srcu_struct *sp;
1243 
1244 	sp = container_of(work, struct srcu_struct, work.work);
1245 
1246 	srcu_advance_state(sp);
1247 	srcu_reschedule(sp, srcu_get_delay(sp));
1248 }
1249 
1250 void srcutorture_get_gp_data(enum rcutorture_type test_type,
1251 			     struct srcu_struct *sp, int *flags,
1252 			     unsigned long *gp_seq)
1253 {
1254 	if (test_type != SRCU_FLAVOR)
1255 		return;
1256 	*flags = 0;
1257 	*gp_seq = rcu_seq_current(&sp->srcu_gp_seq);
1258 }
1259 EXPORT_SYMBOL_GPL(srcutorture_get_gp_data);
1260 
1261 void srcu_torture_stats_print(struct srcu_struct *sp, char *tt, char *tf)
1262 {
1263 	int cpu;
1264 	int idx;
1265 	unsigned long s0 = 0, s1 = 0;
1266 
1267 	idx = sp->srcu_idx & 0x1;
1268 	pr_alert("%s%s Tree SRCU per-CPU(idx=%d):", tt, tf, idx);
1269 	for_each_possible_cpu(cpu) {
1270 		unsigned long l0, l1;
1271 		unsigned long u0, u1;
1272 		long c0, c1;
1273 		struct srcu_data *sdp;
1274 
1275 		sdp = per_cpu_ptr(sp->sda, cpu);
1276 		u0 = sdp->srcu_unlock_count[!idx];
1277 		u1 = sdp->srcu_unlock_count[idx];
1278 
1279 		/*
1280 		 * Make sure that a lock is always counted if the corresponding
1281 		 * unlock is counted.
1282 		 */
1283 		smp_rmb();
1284 
1285 		l0 = sdp->srcu_lock_count[!idx];
1286 		l1 = sdp->srcu_lock_count[idx];
1287 
1288 		c0 = l0 - u0;
1289 		c1 = l1 - u1;
1290 		pr_cont(" %d(%ld,%ld %1p)",
1291 			cpu, c0, c1, rcu_segcblist_head(&sdp->srcu_cblist));
1292 		s0 += c0;
1293 		s1 += c1;
1294 	}
1295 	pr_cont(" T(%ld,%ld)\n", s0, s1);
1296 }
1297 EXPORT_SYMBOL_GPL(srcu_torture_stats_print);
1298 
1299 static int __init srcu_bootup_announce(void)
1300 {
1301 	pr_info("Hierarchical SRCU implementation.\n");
1302 	if (exp_holdoff != DEFAULT_SRCU_EXP_HOLDOFF)
1303 		pr_info("\tNon-default auto-expedite holdoff of %lu ns.\n", exp_holdoff);
1304 	return 0;
1305 }
1306 early_initcall(srcu_bootup_announce);
1307