xref: /linux/kernel/rcu/srcutree.c (revision 69050f8d6d075dc01af7a5f2f550a8067510366f)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Sleepable Read-Copy Update mechanism for mutual exclusion.
4  *
5  * Copyright (C) IBM Corporation, 2006
6  * Copyright (C) Fujitsu, 2012
7  *
8  * Authors: Paul McKenney <paulmck@linux.ibm.com>
9  *	   Lai Jiangshan <laijs@cn.fujitsu.com>
10  *
11  * For detailed explanation of Read-Copy Update mechanism see -
12  *		Documentation/RCU/ *.txt
13  *
14  */
15 
16 #define pr_fmt(fmt) "rcu: " fmt
17 
18 #include <linux/export.h>
19 #include <linux/mutex.h>
20 #include <linux/percpu.h>
21 #include <linux/preempt.h>
22 #include <linux/rcupdate_wait.h>
23 #include <linux/sched.h>
24 #include <linux/smp.h>
25 #include <linux/delay.h>
26 #include <linux/module.h>
27 #include <linux/slab.h>
28 #include <linux/srcu.h>
29 
30 #include "rcu.h"
31 #include "rcu_segcblist.h"
32 
33 /* Holdoff in nanoseconds for auto-expediting. */
34 #define DEFAULT_SRCU_EXP_HOLDOFF (25 * 1000)
35 static ulong exp_holdoff = DEFAULT_SRCU_EXP_HOLDOFF;
36 module_param(exp_holdoff, ulong, 0444);
37 
38 /* Overflow-check frequency.  N bits roughly says every 2**N grace periods. */
39 static ulong counter_wrap_check = (ULONG_MAX >> 2);
40 module_param(counter_wrap_check, ulong, 0444);
41 
42 /*
43  * Control conversion to SRCU_SIZE_BIG:
44  *    0: Don't convert at all.
45  *    1: Convert at init_srcu_struct() time.
46  *    2: Convert when rcutorture invokes srcu_torture_stats_print().
47  *    3: Decide at boot time based on system shape (default).
48  * 0x1x: Convert when excessive contention encountered.
49  */
50 #define SRCU_SIZING_NONE	0
51 #define SRCU_SIZING_INIT	1
52 #define SRCU_SIZING_TORTURE	2
53 #define SRCU_SIZING_AUTO	3
54 #define SRCU_SIZING_CONTEND	0x10
55 #define SRCU_SIZING_IS(x) ((convert_to_big & ~SRCU_SIZING_CONTEND) == x)
56 #define SRCU_SIZING_IS_NONE() (SRCU_SIZING_IS(SRCU_SIZING_NONE))
57 #define SRCU_SIZING_IS_INIT() (SRCU_SIZING_IS(SRCU_SIZING_INIT))
58 #define SRCU_SIZING_IS_TORTURE() (SRCU_SIZING_IS(SRCU_SIZING_TORTURE))
59 #define SRCU_SIZING_IS_CONTEND() (convert_to_big & SRCU_SIZING_CONTEND)
60 static int convert_to_big = SRCU_SIZING_AUTO;
61 module_param(convert_to_big, int, 0444);
62 
63 /* Number of CPUs to trigger init_srcu_struct()-time transition to big. */
64 static int big_cpu_lim __read_mostly = 128;
65 module_param(big_cpu_lim, int, 0444);
66 
67 /* Contention events per jiffy to initiate transition to big. */
68 static int small_contention_lim __read_mostly = 100;
69 module_param(small_contention_lim, int, 0444);
70 
71 /* Early-boot callback-management, so early that no lock is required! */
72 static LIST_HEAD(srcu_boot_list);
73 static bool __read_mostly srcu_init_done;
74 
75 static void srcu_invoke_callbacks(struct work_struct *work);
76 static void srcu_reschedule(struct srcu_struct *ssp, unsigned long delay);
77 static void process_srcu(struct work_struct *work);
78 static void srcu_delay_timer(struct timer_list *t);
79 
80 /* Wrappers for lock acquisition and release, see raw_spin_lock_rcu_node(). */
81 #define spin_lock_rcu_node(p)							\
82 do {										\
83 	spin_lock(&ACCESS_PRIVATE(p, lock));					\
84 	smp_mb__after_unlock_lock();						\
85 } while (0)
86 
87 #define spin_unlock_rcu_node(p) spin_unlock(&ACCESS_PRIVATE(p, lock))
88 
89 #define spin_lock_irq_rcu_node(p)						\
90 do {										\
91 	spin_lock_irq(&ACCESS_PRIVATE(p, lock));				\
92 	smp_mb__after_unlock_lock();						\
93 } while (0)
94 
95 #define spin_unlock_irq_rcu_node(p)						\
96 	spin_unlock_irq(&ACCESS_PRIVATE(p, lock))
97 
98 #define spin_lock_irqsave_rcu_node(p, flags)					\
99 do {										\
100 	spin_lock_irqsave(&ACCESS_PRIVATE(p, lock), flags);			\
101 	smp_mb__after_unlock_lock();						\
102 } while (0)
103 
104 #define spin_trylock_irqsave_rcu_node(p, flags)					\
105 ({										\
106 	bool ___locked = spin_trylock_irqsave(&ACCESS_PRIVATE(p, lock), flags); \
107 										\
108 	if (___locked)								\
109 		smp_mb__after_unlock_lock();					\
110 	___locked;								\
111 })
112 
113 #define spin_unlock_irqrestore_rcu_node(p, flags)				\
114 	spin_unlock_irqrestore(&ACCESS_PRIVATE(p, lock), flags)			\
115 
116 /*
117  * Initialize SRCU per-CPU data.  Note that statically allocated
118  * srcu_struct structures might already have srcu_read_lock() and
119  * srcu_read_unlock() running against them.  So if the is_static
120  * parameter is set, don't initialize ->srcu_ctrs[].srcu_locks and
121  * ->srcu_ctrs[].srcu_unlocks.
122  */
123 static void init_srcu_struct_data(struct srcu_struct *ssp)
124 {
125 	int cpu;
126 	struct srcu_data *sdp;
127 
128 	/*
129 	 * Initialize the per-CPU srcu_data array, which feeds into the
130 	 * leaves of the srcu_node tree.
131 	 */
132 	for_each_possible_cpu(cpu) {
133 		sdp = per_cpu_ptr(ssp->sda, cpu);
134 		spin_lock_init(&ACCESS_PRIVATE(sdp, lock));
135 		rcu_segcblist_init(&sdp->srcu_cblist);
136 		sdp->srcu_cblist_invoking = false;
137 		sdp->srcu_gp_seq_needed = ssp->srcu_sup->srcu_gp_seq;
138 		sdp->srcu_gp_seq_needed_exp = ssp->srcu_sup->srcu_gp_seq;
139 		sdp->srcu_barrier_head.next = &sdp->srcu_barrier_head;
140 		sdp->mynode = NULL;
141 		sdp->cpu = cpu;
142 		INIT_WORK(&sdp->work, srcu_invoke_callbacks);
143 		timer_setup(&sdp->delay_work, srcu_delay_timer, 0);
144 		sdp->ssp = ssp;
145 	}
146 }
147 
148 /* Invalid seq state, used during snp node initialization */
149 #define SRCU_SNP_INIT_SEQ		0x2
150 
151 /*
152  * Check whether sequence number corresponding to snp node,
153  * is invalid.
154  */
155 static inline bool srcu_invl_snp_seq(unsigned long s)
156 {
157 	return s == SRCU_SNP_INIT_SEQ;
158 }
159 
160 /*
161  * Allocated and initialize SRCU combining tree.  Returns @true if
162  * allocation succeeded and @false otherwise.
163  */
164 static bool init_srcu_struct_nodes(struct srcu_struct *ssp, gfp_t gfp_flags)
165 {
166 	int cpu;
167 	int i;
168 	int level = 0;
169 	int levelspread[RCU_NUM_LVLS];
170 	struct srcu_data *sdp;
171 	struct srcu_node *snp;
172 	struct srcu_node *snp_first;
173 
174 	/* Initialize geometry if it has not already been initialized. */
175 	rcu_init_geometry();
176 	ssp->srcu_sup->node = kzalloc_objs(*ssp->srcu_sup->node, rcu_num_nodes,
177 					   gfp_flags);
178 	if (!ssp->srcu_sup->node)
179 		return false;
180 
181 	/* Work out the overall tree geometry. */
182 	ssp->srcu_sup->level[0] = &ssp->srcu_sup->node[0];
183 	for (i = 1; i < rcu_num_lvls; i++)
184 		ssp->srcu_sup->level[i] = ssp->srcu_sup->level[i - 1] + num_rcu_lvl[i - 1];
185 	rcu_init_levelspread(levelspread, num_rcu_lvl);
186 
187 	/* Each pass through this loop initializes one srcu_node structure. */
188 	srcu_for_each_node_breadth_first(ssp, snp) {
189 		spin_lock_init(&ACCESS_PRIVATE(snp, lock));
190 		BUILD_BUG_ON(ARRAY_SIZE(snp->srcu_have_cbs) !=
191 			     ARRAY_SIZE(snp->srcu_data_have_cbs));
192 		for (i = 0; i < ARRAY_SIZE(snp->srcu_have_cbs); i++) {
193 			snp->srcu_have_cbs[i] = SRCU_SNP_INIT_SEQ;
194 			snp->srcu_data_have_cbs[i] = 0;
195 		}
196 		snp->srcu_gp_seq_needed_exp = SRCU_SNP_INIT_SEQ;
197 		snp->grplo = -1;
198 		snp->grphi = -1;
199 		if (snp == &ssp->srcu_sup->node[0]) {
200 			/* Root node, special case. */
201 			snp->srcu_parent = NULL;
202 			continue;
203 		}
204 
205 		/* Non-root node. */
206 		if (snp == ssp->srcu_sup->level[level + 1])
207 			level++;
208 		snp->srcu_parent = ssp->srcu_sup->level[level - 1] +
209 				   (snp - ssp->srcu_sup->level[level]) /
210 				   levelspread[level - 1];
211 	}
212 
213 	/*
214 	 * Initialize the per-CPU srcu_data array, which feeds into the
215 	 * leaves of the srcu_node tree.
216 	 */
217 	level = rcu_num_lvls - 1;
218 	snp_first = ssp->srcu_sup->level[level];
219 	for_each_possible_cpu(cpu) {
220 		sdp = per_cpu_ptr(ssp->sda, cpu);
221 		sdp->mynode = &snp_first[cpu / levelspread[level]];
222 		for (snp = sdp->mynode; snp != NULL; snp = snp->srcu_parent) {
223 			if (snp->grplo < 0)
224 				snp->grplo = cpu;
225 			snp->grphi = cpu;
226 		}
227 		sdp->grpmask = 1UL << (cpu - sdp->mynode->grplo);
228 	}
229 	smp_store_release(&ssp->srcu_sup->srcu_size_state, SRCU_SIZE_WAIT_BARRIER);
230 	return true;
231 }
232 
233 /*
234  * Initialize non-compile-time initialized fields, including the
235  * associated srcu_node and srcu_data structures.  The is_static parameter
236  * tells us that ->sda has already been wired up to srcu_data.
237  */
238 static int init_srcu_struct_fields(struct srcu_struct *ssp, bool is_static)
239 {
240 	if (!is_static)
241 		ssp->srcu_sup = kzalloc_obj(*ssp->srcu_sup, GFP_KERNEL);
242 	if (!ssp->srcu_sup)
243 		return -ENOMEM;
244 	if (!is_static)
245 		spin_lock_init(&ACCESS_PRIVATE(ssp->srcu_sup, lock));
246 	ssp->srcu_sup->srcu_size_state = SRCU_SIZE_SMALL;
247 	ssp->srcu_sup->node = NULL;
248 	mutex_init(&ssp->srcu_sup->srcu_cb_mutex);
249 	mutex_init(&ssp->srcu_sup->srcu_gp_mutex);
250 	ssp->srcu_sup->srcu_gp_seq = SRCU_GP_SEQ_INITIAL_VAL;
251 	ssp->srcu_sup->srcu_barrier_seq = 0;
252 	mutex_init(&ssp->srcu_sup->srcu_barrier_mutex);
253 	atomic_set(&ssp->srcu_sup->srcu_barrier_cpu_cnt, 0);
254 	INIT_DELAYED_WORK(&ssp->srcu_sup->work, process_srcu);
255 	ssp->srcu_sup->sda_is_static = is_static;
256 	if (!is_static) {
257 		ssp->sda = alloc_percpu(struct srcu_data);
258 		ssp->srcu_ctrp = &ssp->sda->srcu_ctrs[0];
259 	}
260 	if (!ssp->sda)
261 		goto err_free_sup;
262 	init_srcu_struct_data(ssp);
263 	ssp->srcu_sup->srcu_gp_seq_needed_exp = SRCU_GP_SEQ_INITIAL_VAL;
264 	ssp->srcu_sup->srcu_last_gp_end = ktime_get_mono_fast_ns();
265 	if (READ_ONCE(ssp->srcu_sup->srcu_size_state) == SRCU_SIZE_SMALL && SRCU_SIZING_IS_INIT()) {
266 		if (!init_srcu_struct_nodes(ssp, is_static ? GFP_ATOMIC : GFP_KERNEL))
267 			goto err_free_sda;
268 		WRITE_ONCE(ssp->srcu_sup->srcu_size_state, SRCU_SIZE_BIG);
269 	}
270 	ssp->srcu_sup->srcu_ssp = ssp;
271 	smp_store_release(&ssp->srcu_sup->srcu_gp_seq_needed,
272 			SRCU_GP_SEQ_INITIAL_VAL); /* Init done. */
273 	return 0;
274 
275 err_free_sda:
276 	if (!is_static) {
277 		free_percpu(ssp->sda);
278 		ssp->sda = NULL;
279 	}
280 err_free_sup:
281 	if (!is_static) {
282 		kfree(ssp->srcu_sup);
283 		ssp->srcu_sup = NULL;
284 	}
285 	return -ENOMEM;
286 }
287 
288 #ifdef CONFIG_DEBUG_LOCK_ALLOC
289 
290 static int
291 __init_srcu_struct_common(struct srcu_struct *ssp, const char *name, struct lock_class_key *key)
292 {
293 	/* Don't re-initialize a lock while it is held. */
294 	debug_check_no_locks_freed((void *)ssp, sizeof(*ssp));
295 	lockdep_init_map(&ssp->dep_map, name, key, 0);
296 	return init_srcu_struct_fields(ssp, false);
297 }
298 
299 int __init_srcu_struct(struct srcu_struct *ssp, const char *name, struct lock_class_key *key)
300 {
301 	ssp->srcu_reader_flavor = 0;
302 	return __init_srcu_struct_common(ssp, name, key);
303 }
304 EXPORT_SYMBOL_GPL(__init_srcu_struct);
305 
306 int __init_srcu_struct_fast(struct srcu_struct *ssp, const char *name, struct lock_class_key *key)
307 {
308 	ssp->srcu_reader_flavor = SRCU_READ_FLAVOR_FAST;
309 	return __init_srcu_struct_common(ssp, name, key);
310 }
311 EXPORT_SYMBOL_GPL(__init_srcu_struct_fast);
312 
313 int __init_srcu_struct_fast_updown(struct srcu_struct *ssp, const char *name,
314 				   struct lock_class_key *key)
315 {
316 	ssp->srcu_reader_flavor = SRCU_READ_FLAVOR_FAST_UPDOWN;
317 	return __init_srcu_struct_common(ssp, name, key);
318 }
319 EXPORT_SYMBOL_GPL(__init_srcu_struct_fast_updown);
320 
321 #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
322 
323 /**
324  * init_srcu_struct - initialize a sleep-RCU structure
325  * @ssp: structure to initialize.
326  *
327  * Use this in place of DEFINE_SRCU() and DEFINE_STATIC_SRCU()
328  * for non-static srcu_struct structures that are to be passed to
329  * srcu_read_lock(), srcu_read_lock_nmisafe(), and friends.  It is necessary
330  * to invoke this on a given srcu_struct before passing that srcu_struct
331  * to any other function.  Each srcu_struct represents a separate domain
332  * of SRCU protection.
333  */
334 int init_srcu_struct(struct srcu_struct *ssp)
335 {
336 	ssp->srcu_reader_flavor = 0;
337 	return init_srcu_struct_fields(ssp, false);
338 }
339 EXPORT_SYMBOL_GPL(init_srcu_struct);
340 
341 /**
342  * init_srcu_struct_fast - initialize a fast-reader sleep-RCU structure
343  * @ssp: structure to initialize.
344  *
345  * Use this in place of DEFINE_SRCU_FAST() and DEFINE_STATIC_SRCU_FAST()
346  * for non-static srcu_struct structures that are to be passed to
347  * srcu_read_lock_fast() and friends.  It is necessary to invoke this on a
348  * given srcu_struct before passing that srcu_struct to any other function.
349  * Each srcu_struct represents a separate domain of SRCU protection.
350  */
351 int init_srcu_struct_fast(struct srcu_struct *ssp)
352 {
353 	ssp->srcu_reader_flavor = SRCU_READ_FLAVOR_FAST;
354 	return init_srcu_struct_fields(ssp, false);
355 }
356 EXPORT_SYMBOL_GPL(init_srcu_struct_fast);
357 
358 /**
359  * init_srcu_struct_fast_updown - initialize a fast-reader up/down sleep-RCU structure
360  * @ssp: structure to initialize.
361  *
362  * Use this function in place of DEFINE_SRCU_FAST_UPDOWN() and
363  * DEFINE_STATIC_SRCU_FAST_UPDOWN() for non-static srcu_struct
364  * structures that are to be passed to srcu_read_lock_fast_updown(),
365  * srcu_down_read_fast(), and friends.  It is necessary to invoke this on a
366  * given srcu_struct before passing that srcu_struct to any other function.
367  * Each srcu_struct represents a separate domain of SRCU protection.
368  */
369 int init_srcu_struct_fast_updown(struct srcu_struct *ssp)
370 {
371 	ssp->srcu_reader_flavor = SRCU_READ_FLAVOR_FAST_UPDOWN;
372 	return init_srcu_struct_fields(ssp, false);
373 }
374 EXPORT_SYMBOL_GPL(init_srcu_struct_fast_updown);
375 
376 #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */
377 
378 /*
379  * Initiate a transition to SRCU_SIZE_BIG with lock held.
380  */
381 static void __srcu_transition_to_big(struct srcu_struct *ssp)
382 {
383 	lockdep_assert_held(&ACCESS_PRIVATE(ssp->srcu_sup, lock));
384 	smp_store_release(&ssp->srcu_sup->srcu_size_state, SRCU_SIZE_ALLOC);
385 }
386 
387 /*
388  * Initiate an idempotent transition to SRCU_SIZE_BIG.
389  */
390 static void srcu_transition_to_big(struct srcu_struct *ssp)
391 {
392 	unsigned long flags;
393 
394 	/* Double-checked locking on ->srcu_size-state. */
395 	if (smp_load_acquire(&ssp->srcu_sup->srcu_size_state) != SRCU_SIZE_SMALL)
396 		return;
397 	spin_lock_irqsave_rcu_node(ssp->srcu_sup, flags);
398 	if (smp_load_acquire(&ssp->srcu_sup->srcu_size_state) != SRCU_SIZE_SMALL) {
399 		spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, flags);
400 		return;
401 	}
402 	__srcu_transition_to_big(ssp);
403 	spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, flags);
404 }
405 
406 /*
407  * Check to see if the just-encountered contention event justifies
408  * a transition to SRCU_SIZE_BIG.
409  */
410 static void spin_lock_irqsave_check_contention(struct srcu_struct *ssp)
411 {
412 	unsigned long j;
413 
414 	if (!SRCU_SIZING_IS_CONTEND() || ssp->srcu_sup->srcu_size_state)
415 		return;
416 	j = jiffies;
417 	if (ssp->srcu_sup->srcu_size_jiffies != j) {
418 		ssp->srcu_sup->srcu_size_jiffies = j;
419 		ssp->srcu_sup->srcu_n_lock_retries = 0;
420 	}
421 	if (++ssp->srcu_sup->srcu_n_lock_retries <= small_contention_lim)
422 		return;
423 	__srcu_transition_to_big(ssp);
424 }
425 
426 /*
427  * Acquire the specified srcu_data structure's ->lock, but check for
428  * excessive contention, which results in initiation of a transition
429  * to SRCU_SIZE_BIG.  But only if the srcutree.convert_to_big module
430  * parameter permits this.
431  */
432 static void spin_lock_irqsave_sdp_contention(struct srcu_data *sdp, unsigned long *flags)
433 {
434 	struct srcu_struct *ssp = sdp->ssp;
435 
436 	if (spin_trylock_irqsave_rcu_node(sdp, *flags))
437 		return;
438 	spin_lock_irqsave_rcu_node(ssp->srcu_sup, *flags);
439 	spin_lock_irqsave_check_contention(ssp);
440 	spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, *flags);
441 	spin_lock_irqsave_rcu_node(sdp, *flags);
442 }
443 
444 /*
445  * Acquire the specified srcu_struct structure's ->lock, but check for
446  * excessive contention, which results in initiation of a transition
447  * to SRCU_SIZE_BIG.  But only if the srcutree.convert_to_big module
448  * parameter permits this.
449  */
450 static void spin_lock_irqsave_ssp_contention(struct srcu_struct *ssp, unsigned long *flags)
451 {
452 	if (spin_trylock_irqsave_rcu_node(ssp->srcu_sup, *flags))
453 		return;
454 	spin_lock_irqsave_rcu_node(ssp->srcu_sup, *flags);
455 	spin_lock_irqsave_check_contention(ssp);
456 }
457 
458 /*
459  * First-use initialization of statically allocated srcu_struct
460  * structure.  Wiring up the combining tree is more than can be
461  * done with compile-time initialization, so this check is added
462  * to each update-side SRCU primitive.  Use ssp->lock, which -is-
463  * compile-time initialized, to resolve races involving multiple
464  * CPUs trying to garner first-use privileges.
465  */
466 static void check_init_srcu_struct(struct srcu_struct *ssp)
467 {
468 	unsigned long flags;
469 
470 	/* The smp_load_acquire() pairs with the smp_store_release(). */
471 	if (!rcu_seq_state(smp_load_acquire(&ssp->srcu_sup->srcu_gp_seq_needed))) /*^^^*/
472 		return; /* Already initialized. */
473 	spin_lock_irqsave_rcu_node(ssp->srcu_sup, flags);
474 	if (!rcu_seq_state(ssp->srcu_sup->srcu_gp_seq_needed)) {
475 		spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, flags);
476 		return;
477 	}
478 	init_srcu_struct_fields(ssp, true);
479 	spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, flags);
480 }
481 
482 /*
483  * Is the current or any upcoming grace period to be expedited?
484  */
485 static bool srcu_gp_is_expedited(struct srcu_struct *ssp)
486 {
487 	struct srcu_usage *sup = ssp->srcu_sup;
488 
489 	return ULONG_CMP_LT(READ_ONCE(sup->srcu_gp_seq), READ_ONCE(sup->srcu_gp_seq_needed_exp));
490 }
491 
492 /*
493  * Computes approximate total of the readers' ->srcu_ctrs[].srcu_locks
494  * values for the rank of per-CPU counters specified by idx, and returns
495  * true if the caller did the proper barrier (gp), and if the count of
496  * the locks matches that of the unlocks passed in.
497  */
498 static bool srcu_readers_lock_idx(struct srcu_struct *ssp, int idx, bool gp, unsigned long unlocks)
499 {
500 	int cpu;
501 	unsigned long mask = 0;
502 	unsigned long sum = 0;
503 
504 	for_each_possible_cpu(cpu) {
505 		struct srcu_data *sdp = per_cpu_ptr(ssp->sda, cpu);
506 
507 		sum += atomic_long_read(&sdp->srcu_ctrs[idx].srcu_locks);
508 		if (IS_ENABLED(CONFIG_PROVE_RCU))
509 			mask = mask | READ_ONCE(sdp->srcu_reader_flavor);
510 	}
511 	WARN_ONCE(IS_ENABLED(CONFIG_PROVE_RCU) && (mask & (mask - 1)),
512 		  "Mixed reader flavors for srcu_struct at %ps.\n", ssp);
513 	if (mask & SRCU_READ_FLAVOR_SLOWGP && !gp)
514 		return false;
515 	return sum == unlocks;
516 }
517 
518 /*
519  * Returns approximate total of the readers' ->srcu_ctrs[].srcu_unlocks
520  * values for the rank of per-CPU counters specified by idx.
521  */
522 static unsigned long srcu_readers_unlock_idx(struct srcu_struct *ssp, int idx, unsigned long *rdm)
523 {
524 	int cpu;
525 	unsigned long mask = ssp->srcu_reader_flavor;
526 	unsigned long sum = 0;
527 
528 	for_each_possible_cpu(cpu) {
529 		struct srcu_data *sdp = per_cpu_ptr(ssp->sda, cpu);
530 
531 		sum += atomic_long_read(&sdp->srcu_ctrs[idx].srcu_unlocks);
532 		mask = mask | READ_ONCE(sdp->srcu_reader_flavor);
533 	}
534 	WARN_ONCE(IS_ENABLED(CONFIG_PROVE_RCU) && (mask & (mask - 1)),
535 		  "Mixed reader flavors for srcu_struct at %ps.\n", ssp);
536 	*rdm = mask;
537 	return sum;
538 }
539 
540 /*
541  * Return true if the number of pre-existing readers is determined to
542  * be zero.
543  */
544 static bool srcu_readers_active_idx_check(struct srcu_struct *ssp, int idx)
545 {
546 	bool did_gp;
547 	unsigned long rdm;
548 	unsigned long unlocks;
549 
550 	unlocks = srcu_readers_unlock_idx(ssp, idx, &rdm);
551 	did_gp = !!(rdm & SRCU_READ_FLAVOR_SLOWGP);
552 
553 	/*
554 	 * Make sure that a lock is always counted if the corresponding
555 	 * unlock is counted. Needs to be a smp_mb() as the read side may
556 	 * contain a read from a variable that is written to before the
557 	 * synchronize_srcu() in the write side. In this case smp_mb()s
558 	 * A and B (or X and Y) act like the store buffering pattern.
559 	 *
560 	 * This smp_mb() also pairs with smp_mb() C (or, in the case of X,
561 	 * Z) to prevent accesses after the synchronize_srcu() from being
562 	 * executed before the grace period ends.
563 	 */
564 	if (!did_gp)
565 		smp_mb(); /* A */
566 	else if (srcu_gp_is_expedited(ssp))
567 		synchronize_rcu_expedited(); /* X */
568 	else
569 		synchronize_rcu(); /* X */
570 
571 	/*
572 	 * If the locks are the same as the unlocks, then there must have
573 	 * been no readers on this index at some point in this function.
574 	 * But there might be more readers, as a task might have read
575 	 * the current ->srcu_ctrp but not yet have incremented its CPU's
576 	 * ->srcu_ctrs[idx].srcu_locks counter.  In fact, it is possible
577 	 * that most of the tasks have been preempted between fetching
578 	 * ->srcu_ctrp and incrementing ->srcu_ctrs[idx].srcu_locks.  And
579 	 * there could be almost (ULONG_MAX / sizeof(struct task_struct))
580 	 * tasks in a system whose address space was fully populated
581 	 * with memory.  Call this quantity Nt.
582 	 *
583 	 * So suppose that the updater is preempted at this
584 	 * point in the code for a long time.  That now-preempted
585 	 * updater has already flipped ->srcu_ctrp (possibly during
586 	 * the preceding grace period), done an smp_mb() (again,
587 	 * possibly during the preceding grace period), and summed up
588 	 * the ->srcu_ctrs[idx].srcu_unlocks counters.  How many times
589 	 * can a given one of the aforementioned Nt tasks increment the
590 	 * old ->srcu_ctrp value's ->srcu_ctrs[idx].srcu_locks counter,
591 	 * in the absence of nesting?
592 	 *
593 	 * It can clearly do so once, given that it has already fetched
594 	 * the old value of ->srcu_ctrp and is just about to use that
595 	 * value to index its increment of ->srcu_ctrs[idx].srcu_locks.
596 	 * But as soon as it leaves that SRCU read-side critical section,
597 	 * it will increment ->srcu_ctrs[idx].srcu_unlocks, which must
598 	 * follow the updater's above read from that same value.  Thus,
599 	   as soon the reading task does an smp_mb() and a later fetch from
600 	 * ->srcu_ctrp, that task will be guaranteed to get the new index.
601 	 * Except that the increment of ->srcu_ctrs[idx].srcu_unlocks
602 	 * in __srcu_read_unlock() is after the smp_mb(), and the fetch
603 	 * from ->srcu_ctrp in __srcu_read_lock() is before the smp_mb().
604 	 * Thus, that task might not see the new value of ->srcu_ctrp until
605 	 * the -second- __srcu_read_lock(), which in turn means that this
606 	 * task might well increment ->srcu_ctrs[idx].srcu_locks for the
607 	 * old value of ->srcu_ctrp twice, not just once.
608 	 *
609 	 * However, it is important to note that a given smp_mb() takes
610 	 * effect not just for the task executing it, but also for any
611 	 * later task running on that same CPU.
612 	 *
613 	 * That is, there can be almost Nt + Nc further increments
614 	 * of ->srcu_ctrs[idx].srcu_locks for the old index, where Nc
615 	 * is the number of CPUs.  But this is OK because the size of
616 	 * the task_struct structure limits the value of Nt and current
617 	 * systems limit Nc to a few thousand.
618 	 *
619 	 * OK, but what about nesting?  This does impose a limit on
620 	 * nesting of half of the size of the task_struct structure
621 	 * (measured in bytes), which should be sufficient.  A late 2022
622 	 * TREE01 rcutorture run reported this size to be no less than
623 	 * 9408 bytes, allowing up to 4704 levels of nesting, which is
624 	 * comfortably beyond excessive.  Especially on 64-bit systems,
625 	 * which are unlikely to be configured with an address space fully
626 	 * populated with memory, at least not anytime soon.
627 	 */
628 	return srcu_readers_lock_idx(ssp, idx, did_gp, unlocks);
629 }
630 
631 /**
632  * srcu_readers_active - returns true if there are readers. and false
633  *                       otherwise
634  * @ssp: which srcu_struct to count active readers (holding srcu_read_lock).
635  *
636  * Note that this is not an atomic primitive, and can therefore suffer
637  * severe errors when invoked on an active srcu_struct.  That said, it
638  * can be useful as an error check at cleanup time.
639  */
640 static bool srcu_readers_active(struct srcu_struct *ssp)
641 {
642 	int cpu;
643 	unsigned long sum = 0;
644 
645 	for_each_possible_cpu(cpu) {
646 		struct srcu_data *sdp = per_cpu_ptr(ssp->sda, cpu);
647 
648 		sum += atomic_long_read(&sdp->srcu_ctrs[0].srcu_locks);
649 		sum += atomic_long_read(&sdp->srcu_ctrs[1].srcu_locks);
650 		sum -= atomic_long_read(&sdp->srcu_ctrs[0].srcu_unlocks);
651 		sum -= atomic_long_read(&sdp->srcu_ctrs[1].srcu_unlocks);
652 	}
653 	return sum;
654 }
655 
656 /*
657  * We use an adaptive strategy for synchronize_srcu() and especially for
658  * synchronize_srcu_expedited().  We spin for a fixed time period
659  * (defined below, boot time configurable) to allow SRCU readers to exit
660  * their read-side critical sections.  If there are still some readers
661  * after one jiffy, we repeatedly block for one jiffy time periods.
662  * The blocking time is increased as the grace-period age increases,
663  * with max blocking time capped at 10 jiffies.
664  */
665 #define SRCU_DEFAULT_RETRY_CHECK_DELAY		5
666 
667 static ulong srcu_retry_check_delay = SRCU_DEFAULT_RETRY_CHECK_DELAY;
668 module_param(srcu_retry_check_delay, ulong, 0444);
669 
670 #define SRCU_INTERVAL		1		// Base delay if no expedited GPs pending.
671 #define SRCU_MAX_INTERVAL	10		// Maximum incremental delay from slow readers.
672 
673 #define SRCU_DEFAULT_MAX_NODELAY_PHASE_LO	3UL	// Lowmark on default per-GP-phase
674 							// no-delay instances.
675 #define SRCU_DEFAULT_MAX_NODELAY_PHASE_HI	1000UL	// Highmark on default per-GP-phase
676 							// no-delay instances.
677 
678 #define SRCU_UL_CLAMP_LO(val, low)	((val) > (low) ? (val) : (low))
679 #define SRCU_UL_CLAMP_HI(val, high)	((val) < (high) ? (val) : (high))
680 #define SRCU_UL_CLAMP(val, low, high)	SRCU_UL_CLAMP_HI(SRCU_UL_CLAMP_LO((val), (low)), (high))
681 // per-GP-phase no-delay instances adjusted to allow non-sleeping poll upto
682 // one jiffies time duration. Mult by 2 is done to factor in the srcu_get_delay()
683 // called from process_srcu().
684 #define SRCU_DEFAULT_MAX_NODELAY_PHASE_ADJUSTED	\
685 	(2UL * USEC_PER_SEC / HZ / SRCU_DEFAULT_RETRY_CHECK_DELAY)
686 
687 // Maximum per-GP-phase consecutive no-delay instances.
688 #define SRCU_DEFAULT_MAX_NODELAY_PHASE	\
689 	SRCU_UL_CLAMP(SRCU_DEFAULT_MAX_NODELAY_PHASE_ADJUSTED,	\
690 		      SRCU_DEFAULT_MAX_NODELAY_PHASE_LO,	\
691 		      SRCU_DEFAULT_MAX_NODELAY_PHASE_HI)
692 
693 static ulong srcu_max_nodelay_phase = SRCU_DEFAULT_MAX_NODELAY_PHASE;
694 module_param(srcu_max_nodelay_phase, ulong, 0444);
695 
696 // Maximum consecutive no-delay instances.
697 #define SRCU_DEFAULT_MAX_NODELAY	(SRCU_DEFAULT_MAX_NODELAY_PHASE > 100 ?	\
698 					 SRCU_DEFAULT_MAX_NODELAY_PHASE : 100)
699 
700 static ulong srcu_max_nodelay = SRCU_DEFAULT_MAX_NODELAY;
701 module_param(srcu_max_nodelay, ulong, 0444);
702 
703 /*
704  * Return grace-period delay, zero if there are expedited grace
705  * periods pending, SRCU_INTERVAL otherwise.
706  */
707 static unsigned long srcu_get_delay(struct srcu_struct *ssp)
708 {
709 	unsigned long gpstart;
710 	unsigned long j;
711 	unsigned long jbase = SRCU_INTERVAL;
712 	struct srcu_usage *sup = ssp->srcu_sup;
713 
714 	lockdep_assert_held(&ACCESS_PRIVATE(ssp->srcu_sup, lock));
715 	if (srcu_gp_is_expedited(ssp))
716 		jbase = 0;
717 	if (rcu_seq_state(READ_ONCE(sup->srcu_gp_seq))) {
718 		j = jiffies - 1;
719 		gpstart = READ_ONCE(sup->srcu_gp_start);
720 		if (time_after(j, gpstart))
721 			jbase += j - gpstart;
722 		if (!jbase) {
723 			ASSERT_EXCLUSIVE_WRITER(sup->srcu_n_exp_nodelay);
724 			WRITE_ONCE(sup->srcu_n_exp_nodelay, READ_ONCE(sup->srcu_n_exp_nodelay) + 1);
725 			if (READ_ONCE(sup->srcu_n_exp_nodelay) > srcu_max_nodelay_phase)
726 				jbase = 1;
727 		}
728 	}
729 	return jbase > SRCU_MAX_INTERVAL ? SRCU_MAX_INTERVAL : jbase;
730 }
731 
732 /**
733  * cleanup_srcu_struct - deconstruct a sleep-RCU structure
734  * @ssp: structure to clean up.
735  *
736  * Must invoke this after you are finished using a given srcu_struct that
737  * was initialized via init_srcu_struct(), else you leak memory.
738  */
739 void cleanup_srcu_struct(struct srcu_struct *ssp)
740 {
741 	int cpu;
742 	unsigned long delay;
743 	struct srcu_usage *sup = ssp->srcu_sup;
744 
745 	spin_lock_irq_rcu_node(ssp->srcu_sup);
746 	delay = srcu_get_delay(ssp);
747 	spin_unlock_irq_rcu_node(ssp->srcu_sup);
748 	if (WARN_ON(!delay))
749 		return; /* Just leak it! */
750 	if (WARN_ON(srcu_readers_active(ssp)))
751 		return; /* Just leak it! */
752 	flush_delayed_work(&sup->work);
753 	for_each_possible_cpu(cpu) {
754 		struct srcu_data *sdp = per_cpu_ptr(ssp->sda, cpu);
755 
756 		timer_delete_sync(&sdp->delay_work);
757 		flush_work(&sdp->work);
758 		if (WARN_ON(rcu_segcblist_n_cbs(&sdp->srcu_cblist)))
759 			return; /* Forgot srcu_barrier(), so just leak it! */
760 	}
761 	if (WARN_ON(rcu_seq_state(READ_ONCE(sup->srcu_gp_seq)) != SRCU_STATE_IDLE) ||
762 	    WARN_ON(rcu_seq_current(&sup->srcu_gp_seq) != sup->srcu_gp_seq_needed) ||
763 	    WARN_ON(srcu_readers_active(ssp))) {
764 		pr_info("%s: Active srcu_struct %p read state: %d gp state: %lu/%lu\n",
765 			__func__, ssp, rcu_seq_state(READ_ONCE(sup->srcu_gp_seq)),
766 			rcu_seq_current(&sup->srcu_gp_seq), sup->srcu_gp_seq_needed);
767 		return; // Caller forgot to stop doing call_srcu()?
768 			// Or caller invoked start_poll_synchronize_srcu()
769 			// and then cleanup_srcu_struct() before that grace
770 			// period ended?
771 	}
772 	kfree(sup->node);
773 	sup->node = NULL;
774 	sup->srcu_size_state = SRCU_SIZE_SMALL;
775 	if (!sup->sda_is_static) {
776 		free_percpu(ssp->sda);
777 		ssp->sda = NULL;
778 		kfree(sup);
779 		ssp->srcu_sup = NULL;
780 	}
781 }
782 EXPORT_SYMBOL_GPL(cleanup_srcu_struct);
783 
784 /*
785  * Check for consistent reader flavor.
786  */
787 void __srcu_check_read_flavor(struct srcu_struct *ssp, int read_flavor)
788 {
789 	int old_read_flavor;
790 	struct srcu_data *sdp;
791 
792 	/* NMI-unsafe use in NMI is a bad sign, as is multi-bit read_flavor values. */
793 	WARN_ON_ONCE(read_flavor != SRCU_READ_FLAVOR_NMI &&
794 		     read_flavor != SRCU_READ_FLAVOR_FAST && in_nmi());
795 	WARN_ON_ONCE(read_flavor & (read_flavor - 1));
796 
797 	sdp = raw_cpu_ptr(ssp->sda);
798 	old_read_flavor = READ_ONCE(sdp->srcu_reader_flavor);
799 	WARN_ON_ONCE(ssp->srcu_reader_flavor && read_flavor != ssp->srcu_reader_flavor);
800 	WARN_ON_ONCE(old_read_flavor && ssp->srcu_reader_flavor &&
801 		     old_read_flavor != ssp->srcu_reader_flavor);
802 	WARN_ON_ONCE(read_flavor == SRCU_READ_FLAVOR_FAST && !ssp->srcu_reader_flavor);
803 	if (!old_read_flavor) {
804 		old_read_flavor = cmpxchg(&sdp->srcu_reader_flavor, 0, read_flavor);
805 		if (!old_read_flavor)
806 			return;
807 	}
808 	WARN_ONCE(old_read_flavor != read_flavor, "CPU %d old state %d new state %d\n", sdp->cpu, old_read_flavor, read_flavor);
809 }
810 EXPORT_SYMBOL_GPL(__srcu_check_read_flavor);
811 
812 /*
813  * Counts the new reader in the appropriate per-CPU element of the
814  * srcu_struct.
815  * Returns a guaranteed non-negative index that must be passed to the
816  * matching __srcu_read_unlock().
817  */
818 int __srcu_read_lock(struct srcu_struct *ssp)
819 {
820 	struct srcu_ctr __percpu *scp = READ_ONCE(ssp->srcu_ctrp);
821 
822 	this_cpu_inc(scp->srcu_locks.counter);
823 	smp_mb(); /* B */  /* Avoid leaking the critical section. */
824 	return __srcu_ptr_to_ctr(ssp, scp);
825 }
826 EXPORT_SYMBOL_GPL(__srcu_read_lock);
827 
828 /*
829  * Removes the count for the old reader from the appropriate per-CPU
830  * element of the srcu_struct.  Note that this may well be a different
831  * CPU than that which was incremented by the corresponding srcu_read_lock().
832  */
833 void __srcu_read_unlock(struct srcu_struct *ssp, int idx)
834 {
835 	smp_mb(); /* C */  /* Avoid leaking the critical section. */
836 	this_cpu_inc(__srcu_ctr_to_ptr(ssp, idx)->srcu_unlocks.counter);
837 }
838 EXPORT_SYMBOL_GPL(__srcu_read_unlock);
839 
840 #ifdef CONFIG_NEED_SRCU_NMI_SAFE
841 
842 /*
843  * Counts the new reader in the appropriate per-CPU element of the
844  * srcu_struct, but in an NMI-safe manner using RMW atomics.
845  * Returns an index that must be passed to the matching srcu_read_unlock().
846  */
847 int __srcu_read_lock_nmisafe(struct srcu_struct *ssp)
848 {
849 	struct srcu_ctr __percpu *scpp = READ_ONCE(ssp->srcu_ctrp);
850 	struct srcu_ctr *scp = raw_cpu_ptr(scpp);
851 
852 	atomic_long_inc(&scp->srcu_locks);
853 	smp_mb__after_atomic(); /* B */  /* Avoid leaking the critical section. */
854 	return __srcu_ptr_to_ctr(ssp, scpp);
855 }
856 EXPORT_SYMBOL_GPL(__srcu_read_lock_nmisafe);
857 
858 /*
859  * Removes the count for the old reader from the appropriate per-CPU
860  * element of the srcu_struct.  Note that this may well be a different
861  * CPU than that which was incremented by the corresponding srcu_read_lock().
862  */
863 void __srcu_read_unlock_nmisafe(struct srcu_struct *ssp, int idx)
864 {
865 	smp_mb__before_atomic(); /* C */  /* Avoid leaking the critical section. */
866 	atomic_long_inc(&raw_cpu_ptr(__srcu_ctr_to_ptr(ssp, idx))->srcu_unlocks);
867 }
868 EXPORT_SYMBOL_GPL(__srcu_read_unlock_nmisafe);
869 
870 #endif // CONFIG_NEED_SRCU_NMI_SAFE
871 
872 /*
873  * Start an SRCU grace period.
874  */
875 static void srcu_gp_start(struct srcu_struct *ssp)
876 {
877 	int state;
878 
879 	lockdep_assert_held(&ACCESS_PRIVATE(ssp->srcu_sup, lock));
880 	WARN_ON_ONCE(ULONG_CMP_GE(ssp->srcu_sup->srcu_gp_seq, ssp->srcu_sup->srcu_gp_seq_needed));
881 	WRITE_ONCE(ssp->srcu_sup->srcu_gp_start, jiffies);
882 	WRITE_ONCE(ssp->srcu_sup->srcu_n_exp_nodelay, 0);
883 	smp_mb(); /* Order prior store to ->srcu_gp_seq_needed vs. GP start. */
884 	rcu_seq_start(&ssp->srcu_sup->srcu_gp_seq);
885 	state = rcu_seq_state(ssp->srcu_sup->srcu_gp_seq);
886 	WARN_ON_ONCE(state != SRCU_STATE_SCAN1);
887 }
888 
889 
890 static void srcu_delay_timer(struct timer_list *t)
891 {
892 	struct srcu_data *sdp = container_of(t, struct srcu_data, delay_work);
893 
894 	queue_work_on(sdp->cpu, rcu_gp_wq, &sdp->work);
895 }
896 
897 static void srcu_queue_delayed_work_on(struct srcu_data *sdp,
898 				       unsigned long delay)
899 {
900 	if (!delay) {
901 		queue_work_on(sdp->cpu, rcu_gp_wq, &sdp->work);
902 		return;
903 	}
904 
905 	timer_reduce(&sdp->delay_work, jiffies + delay);
906 }
907 
908 /*
909  * Schedule callback invocation for the specified srcu_data structure,
910  * if possible, on the corresponding CPU.
911  */
912 static void srcu_schedule_cbs_sdp(struct srcu_data *sdp, unsigned long delay)
913 {
914 	srcu_queue_delayed_work_on(sdp, delay);
915 }
916 
917 /*
918  * Schedule callback invocation for all srcu_data structures associated
919  * with the specified srcu_node structure that have callbacks for the
920  * just-completed grace period, the one corresponding to idx.  If possible,
921  * schedule this invocation on the corresponding CPUs.
922  */
923 static void srcu_schedule_cbs_snp(struct srcu_struct *ssp, struct srcu_node *snp,
924 				  unsigned long mask, unsigned long delay)
925 {
926 	int cpu;
927 
928 	for (cpu = snp->grplo; cpu <= snp->grphi; cpu++) {
929 		if (!(mask & (1UL << (cpu - snp->grplo))))
930 			continue;
931 		srcu_schedule_cbs_sdp(per_cpu_ptr(ssp->sda, cpu), delay);
932 	}
933 }
934 
935 /*
936  * Note the end of an SRCU grace period.  Initiates callback invocation
937  * and starts a new grace period if needed.
938  *
939  * The ->srcu_cb_mutex acquisition does not protect any data, but
940  * instead prevents more than one grace period from starting while we
941  * are initiating callback invocation.  This allows the ->srcu_have_cbs[]
942  * array to have a finite number of elements.
943  */
944 static void srcu_gp_end(struct srcu_struct *ssp)
945 {
946 	unsigned long cbdelay = 1;
947 	bool cbs;
948 	bool last_lvl;
949 	int cpu;
950 	unsigned long gpseq;
951 	int idx;
952 	unsigned long mask;
953 	struct srcu_data *sdp;
954 	unsigned long sgsne;
955 	struct srcu_node *snp;
956 	int ss_state;
957 	struct srcu_usage *sup = ssp->srcu_sup;
958 
959 	/* Prevent more than one additional grace period. */
960 	mutex_lock(&sup->srcu_cb_mutex);
961 
962 	/* End the current grace period. */
963 	spin_lock_irq_rcu_node(sup);
964 	idx = rcu_seq_state(sup->srcu_gp_seq);
965 	WARN_ON_ONCE(idx != SRCU_STATE_SCAN2);
966 	if (srcu_gp_is_expedited(ssp))
967 		cbdelay = 0;
968 
969 	WRITE_ONCE(sup->srcu_last_gp_end, ktime_get_mono_fast_ns());
970 	rcu_seq_end(&sup->srcu_gp_seq);
971 	gpseq = rcu_seq_current(&sup->srcu_gp_seq);
972 	if (ULONG_CMP_LT(sup->srcu_gp_seq_needed_exp, gpseq))
973 		WRITE_ONCE(sup->srcu_gp_seq_needed_exp, gpseq);
974 	spin_unlock_irq_rcu_node(sup);
975 	mutex_unlock(&sup->srcu_gp_mutex);
976 	/* A new grace period can start at this point.  But only one. */
977 
978 	/* Initiate callback invocation as needed. */
979 	ss_state = smp_load_acquire(&sup->srcu_size_state);
980 	if (ss_state < SRCU_SIZE_WAIT_BARRIER) {
981 		srcu_schedule_cbs_sdp(per_cpu_ptr(ssp->sda, get_boot_cpu_id()),
982 					cbdelay);
983 	} else {
984 		idx = rcu_seq_ctr(gpseq) % ARRAY_SIZE(snp->srcu_have_cbs);
985 		srcu_for_each_node_breadth_first(ssp, snp) {
986 			spin_lock_irq_rcu_node(snp);
987 			cbs = false;
988 			last_lvl = snp >= sup->level[rcu_num_lvls - 1];
989 			if (last_lvl)
990 				cbs = ss_state < SRCU_SIZE_BIG || snp->srcu_have_cbs[idx] == gpseq;
991 			snp->srcu_have_cbs[idx] = gpseq;
992 			rcu_seq_set_state(&snp->srcu_have_cbs[idx], 1);
993 			sgsne = snp->srcu_gp_seq_needed_exp;
994 			if (srcu_invl_snp_seq(sgsne) || ULONG_CMP_LT(sgsne, gpseq))
995 				WRITE_ONCE(snp->srcu_gp_seq_needed_exp, gpseq);
996 			if (ss_state < SRCU_SIZE_BIG)
997 				mask = ~0;
998 			else
999 				mask = snp->srcu_data_have_cbs[idx];
1000 			snp->srcu_data_have_cbs[idx] = 0;
1001 			spin_unlock_irq_rcu_node(snp);
1002 			if (cbs)
1003 				srcu_schedule_cbs_snp(ssp, snp, mask, cbdelay);
1004 		}
1005 	}
1006 
1007 	/* Occasionally prevent srcu_data counter wrap. */
1008 	if (!(gpseq & counter_wrap_check))
1009 		for_each_possible_cpu(cpu) {
1010 			sdp = per_cpu_ptr(ssp->sda, cpu);
1011 			spin_lock_irq_rcu_node(sdp);
1012 			if (ULONG_CMP_GE(gpseq, sdp->srcu_gp_seq_needed + 100))
1013 				sdp->srcu_gp_seq_needed = gpseq;
1014 			if (ULONG_CMP_GE(gpseq, sdp->srcu_gp_seq_needed_exp + 100))
1015 				sdp->srcu_gp_seq_needed_exp = gpseq;
1016 			spin_unlock_irq_rcu_node(sdp);
1017 		}
1018 
1019 	/* Callback initiation done, allow grace periods after next. */
1020 	mutex_unlock(&sup->srcu_cb_mutex);
1021 
1022 	/* Start a new grace period if needed. */
1023 	spin_lock_irq_rcu_node(sup);
1024 	gpseq = rcu_seq_current(&sup->srcu_gp_seq);
1025 	if (!rcu_seq_state(gpseq) &&
1026 	    ULONG_CMP_LT(gpseq, sup->srcu_gp_seq_needed)) {
1027 		srcu_gp_start(ssp);
1028 		spin_unlock_irq_rcu_node(sup);
1029 		srcu_reschedule(ssp, 0);
1030 	} else {
1031 		spin_unlock_irq_rcu_node(sup);
1032 	}
1033 
1034 	/* Transition to big if needed. */
1035 	if (ss_state != SRCU_SIZE_SMALL && ss_state != SRCU_SIZE_BIG) {
1036 		if (ss_state == SRCU_SIZE_ALLOC)
1037 			init_srcu_struct_nodes(ssp, GFP_KERNEL);
1038 		else
1039 			smp_store_release(&sup->srcu_size_state, ss_state + 1);
1040 	}
1041 }
1042 
1043 /*
1044  * Funnel-locking scheme to scalably mediate many concurrent expedited
1045  * grace-period requests.  This function is invoked for the first known
1046  * expedited request for a grace period that has already been requested,
1047  * but without expediting.  To start a completely new grace period,
1048  * whether expedited or not, use srcu_funnel_gp_start() instead.
1049  */
1050 static void srcu_funnel_exp_start(struct srcu_struct *ssp, struct srcu_node *snp,
1051 				  unsigned long s)
1052 {
1053 	unsigned long flags;
1054 	unsigned long sgsne;
1055 
1056 	if (snp)
1057 		for (; snp != NULL; snp = snp->srcu_parent) {
1058 			sgsne = READ_ONCE(snp->srcu_gp_seq_needed_exp);
1059 			if (WARN_ON_ONCE(rcu_seq_done(&ssp->srcu_sup->srcu_gp_seq, s)) ||
1060 			    (!srcu_invl_snp_seq(sgsne) && ULONG_CMP_GE(sgsne, s)))
1061 				return;
1062 			spin_lock_irqsave_rcu_node(snp, flags);
1063 			sgsne = snp->srcu_gp_seq_needed_exp;
1064 			if (!srcu_invl_snp_seq(sgsne) && ULONG_CMP_GE(sgsne, s)) {
1065 				spin_unlock_irqrestore_rcu_node(snp, flags);
1066 				return;
1067 			}
1068 			WRITE_ONCE(snp->srcu_gp_seq_needed_exp, s);
1069 			spin_unlock_irqrestore_rcu_node(snp, flags);
1070 		}
1071 	spin_lock_irqsave_ssp_contention(ssp, &flags);
1072 	if (ULONG_CMP_LT(ssp->srcu_sup->srcu_gp_seq_needed_exp, s))
1073 		WRITE_ONCE(ssp->srcu_sup->srcu_gp_seq_needed_exp, s);
1074 	spin_unlock_irqrestore_rcu_node(ssp->srcu_sup, flags);
1075 }
1076 
1077 /*
1078  * Funnel-locking scheme to scalably mediate many concurrent grace-period
1079  * requests.  The winner has to do the work of actually starting grace
1080  * period s.  Losers must either ensure that their desired grace-period
1081  * number is recorded on at least their leaf srcu_node structure, or they
1082  * must take steps to invoke their own callbacks.
1083  *
1084  * Note that this function also does the work of srcu_funnel_exp_start(),
1085  * in some cases by directly invoking it.
1086  *
1087  * The srcu read lock should be hold around this function. And s is a seq snap
1088  * after holding that lock.
1089  */
1090 static void srcu_funnel_gp_start(struct srcu_struct *ssp, struct srcu_data *sdp,
1091 				 unsigned long s, bool do_norm)
1092 {
1093 	unsigned long flags;
1094 	int idx = rcu_seq_ctr(s) % ARRAY_SIZE(sdp->mynode->srcu_have_cbs);
1095 	unsigned long sgsne;
1096 	struct srcu_node *snp;
1097 	struct srcu_node *snp_leaf;
1098 	unsigned long snp_seq;
1099 	struct srcu_usage *sup = ssp->srcu_sup;
1100 
1101 	/* Ensure that snp node tree is fully initialized before traversing it */
1102 	if (smp_load_acquire(&sup->srcu_size_state) < SRCU_SIZE_WAIT_BARRIER)
1103 		snp_leaf = NULL;
1104 	else
1105 		snp_leaf = sdp->mynode;
1106 
1107 	if (snp_leaf)
1108 		/* Each pass through the loop does one level of the srcu_node tree. */
1109 		for (snp = snp_leaf; snp != NULL; snp = snp->srcu_parent) {
1110 			if (WARN_ON_ONCE(rcu_seq_done(&sup->srcu_gp_seq, s)) && snp != snp_leaf)
1111 				return; /* GP already done and CBs recorded. */
1112 			spin_lock_irqsave_rcu_node(snp, flags);
1113 			snp_seq = snp->srcu_have_cbs[idx];
1114 			if (!srcu_invl_snp_seq(snp_seq) && ULONG_CMP_GE(snp_seq, s)) {
1115 				if (snp == snp_leaf && snp_seq == s)
1116 					snp->srcu_data_have_cbs[idx] |= sdp->grpmask;
1117 				spin_unlock_irqrestore_rcu_node(snp, flags);
1118 				if (snp == snp_leaf && snp_seq != s) {
1119 					srcu_schedule_cbs_sdp(sdp, do_norm ? SRCU_INTERVAL : 0);
1120 					return;
1121 				}
1122 				if (!do_norm)
1123 					srcu_funnel_exp_start(ssp, snp, s);
1124 				return;
1125 			}
1126 			snp->srcu_have_cbs[idx] = s;
1127 			if (snp == snp_leaf)
1128 				snp->srcu_data_have_cbs[idx] |= sdp->grpmask;
1129 			sgsne = snp->srcu_gp_seq_needed_exp;
1130 			if (!do_norm && (srcu_invl_snp_seq(sgsne) || ULONG_CMP_LT(sgsne, s)))
1131 				WRITE_ONCE(snp->srcu_gp_seq_needed_exp, s);
1132 			spin_unlock_irqrestore_rcu_node(snp, flags);
1133 		}
1134 
1135 	/* Top of tree, must ensure the grace period will be started. */
1136 	spin_lock_irqsave_ssp_contention(ssp, &flags);
1137 	if (ULONG_CMP_LT(sup->srcu_gp_seq_needed, s)) {
1138 		/*
1139 		 * Record need for grace period s.  Pair with load
1140 		 * acquire setting up for initialization.
1141 		 */
1142 		smp_store_release(&sup->srcu_gp_seq_needed, s); /*^^^*/
1143 	}
1144 	if (!do_norm && ULONG_CMP_LT(sup->srcu_gp_seq_needed_exp, s))
1145 		WRITE_ONCE(sup->srcu_gp_seq_needed_exp, s);
1146 
1147 	/* If grace period not already in progress, start it. */
1148 	if (!WARN_ON_ONCE(rcu_seq_done(&sup->srcu_gp_seq, s)) &&
1149 	    rcu_seq_state(sup->srcu_gp_seq) == SRCU_STATE_IDLE) {
1150 		srcu_gp_start(ssp);
1151 
1152 		// And how can that list_add() in the "else" clause
1153 		// possibly be safe for concurrent execution?  Well,
1154 		// it isn't.  And it does not have to be.  After all, it
1155 		// can only be executed during early boot when there is only
1156 		// the one boot CPU running with interrupts still disabled.
1157 		if (likely(srcu_init_done))
1158 			queue_delayed_work(rcu_gp_wq, &sup->work,
1159 					   !!srcu_get_delay(ssp));
1160 		else if (list_empty(&sup->work.work.entry))
1161 			list_add(&sup->work.work.entry, &srcu_boot_list);
1162 	}
1163 	spin_unlock_irqrestore_rcu_node(sup, flags);
1164 }
1165 
1166 /*
1167  * Wait until all readers counted by array index idx complete, but
1168  * loop an additional time if there is an expedited grace period pending.
1169  * The caller must ensure that ->srcu_ctrp is not changed while checking.
1170  */
1171 static bool try_check_zero(struct srcu_struct *ssp, int idx, int trycount)
1172 {
1173 	unsigned long curdelay;
1174 
1175 	spin_lock_irq_rcu_node(ssp->srcu_sup);
1176 	curdelay = !srcu_get_delay(ssp);
1177 	spin_unlock_irq_rcu_node(ssp->srcu_sup);
1178 
1179 	for (;;) {
1180 		if (srcu_readers_active_idx_check(ssp, idx))
1181 			return true;
1182 		if ((--trycount + curdelay) <= 0)
1183 			return false;
1184 		udelay(srcu_retry_check_delay);
1185 	}
1186 }
1187 
1188 /*
1189  * Increment the ->srcu_ctrp counter so that future SRCU readers will
1190  * use the other rank of the ->srcu_(un)lock_count[] arrays.  This allows
1191  * us to wait for pre-existing readers in a starvation-free manner.
1192  */
1193 static void srcu_flip(struct srcu_struct *ssp)
1194 {
1195 	/*
1196 	 * Because the flip of ->srcu_ctrp is executed only if the
1197 	 * preceding call to srcu_readers_active_idx_check() found that
1198 	 * the ->srcu_ctrs[].srcu_unlocks and ->srcu_ctrs[].srcu_locks sums
1199 	 * matched and because that summing uses atomic_long_read(),
1200 	 * there is ordering due to a control dependency between that
1201 	 * summing and the WRITE_ONCE() in this call to srcu_flip().
1202 	 * This ordering ensures that if this updater saw a given reader's
1203 	 * increment from __srcu_read_lock(), that reader was using a value
1204 	 * of ->srcu_ctrp from before the previous call to srcu_flip(),
1205 	 * which should be quite rare.  This ordering thus helps forward
1206 	 * progress because the grace period could otherwise be delayed
1207 	 * by additional calls to __srcu_read_lock() using that old (soon
1208 	 * to be new) value of ->srcu_ctrp.
1209 	 *
1210 	 * This sum-equality check and ordering also ensures that if
1211 	 * a given call to __srcu_read_lock() uses the new value of
1212 	 * ->srcu_ctrp, this updater's earlier scans cannot have seen
1213 	 * that reader's increments, which is all to the good, because
1214 	 * this grace period need not wait on that reader.  After all,
1215 	 * if those earlier scans had seen that reader, there would have
1216 	 * been a sum mismatch and this code would not be reached.
1217 	 *
1218 	 * This means that the following smp_mb() is redundant, but
1219 	 * it stays until either (1) Compilers learn about this sort of
1220 	 * control dependency or (2) Some production workload running on
1221 	 * a production system is unduly delayed by this slowpath smp_mb().
1222 	 * Except for _lite() readers, where it is inoperative, which
1223 	 * means that it is a good thing that it is redundant.
1224 	 */
1225 	smp_mb(); /* E */  /* Pairs with B and C. */
1226 
1227 	WRITE_ONCE(ssp->srcu_ctrp,
1228 		   &ssp->sda->srcu_ctrs[!(ssp->srcu_ctrp - &ssp->sda->srcu_ctrs[0])]);
1229 
1230 	/*
1231 	 * Ensure that if the updater misses an __srcu_read_unlock()
1232 	 * increment, that task's __srcu_read_lock() following its next
1233 	 * __srcu_read_lock() or __srcu_read_unlock() will see the above
1234 	 * counter update.  Note that both this memory barrier and the
1235 	 * one in srcu_readers_active_idx_check() provide the guarantee
1236 	 * for __srcu_read_lock().
1237 	 *
1238 	 * Note that this is a performance optimization, in which we spend
1239 	 * an otherwise unnecessary smp_mb() in order to reduce the number
1240 	 * of full per-CPU-variable scans in srcu_readers_lock_idx() and
1241 	 * srcu_readers_unlock_idx().  But this performance optimization
1242 	 * is not so optimal for SRCU-fast, where we would be spending
1243 	 * not smp_mb(), but rather synchronize_rcu().  At the same time,
1244 	 * the overhead of the smp_mb() is in the noise, so there is no
1245 	 * point in omitting it in the SRCU-fast case.  So the same code
1246 	 * is executed either way.
1247 	 */
1248 	smp_mb(); /* D */  /* Pairs with C. */
1249 }
1250 
1251 /*
1252  * If SRCU is likely idle, in other words, the next SRCU grace period
1253  * should be expedited, return true, otherwise return false.  Except that
1254  * in the presence of _lite() readers, always return false.
1255  *
1256  * Note that it is OK for several current from-idle requests for a new
1257  * grace period from idle to specify expediting because they will all end
1258  * up requesting the same grace period anyhow.  So no loss.
1259  *
1260  * Note also that if any CPU (including the current one) is still invoking
1261  * callbacks, this function will nevertheless say "idle".  This is not
1262  * ideal, but the overhead of checking all CPUs' callback lists is even
1263  * less ideal, especially on large systems.  Furthermore, the wakeup
1264  * can happen before the callback is fully removed, so we have no choice
1265  * but to accept this type of error.
1266  *
1267  * This function is also subject to counter-wrap errors, but let's face
1268  * it, if this function was preempted for enough time for the counters
1269  * to wrap, it really doesn't matter whether or not we expedite the grace
1270  * period.  The extra overhead of a needlessly expedited grace period is
1271  * negligible when amortized over that time period, and the extra latency
1272  * of a needlessly non-expedited grace period is similarly negligible.
1273  */
1274 static bool srcu_should_expedite(struct srcu_struct *ssp)
1275 {
1276 	unsigned long curseq;
1277 	unsigned long flags;
1278 	struct srcu_data *sdp;
1279 	unsigned long t;
1280 	unsigned long tlast;
1281 
1282 	check_init_srcu_struct(ssp);
1283 	/* If _lite() readers, don't do unsolicited expediting. */
1284 	if (this_cpu_read(ssp->sda->srcu_reader_flavor) & SRCU_READ_FLAVOR_SLOWGP)
1285 		return false;
1286 	/* If the local srcu_data structure has callbacks, not idle.  */
1287 	sdp = raw_cpu_ptr(ssp->sda);
1288 	spin_lock_irqsave_rcu_node(sdp, flags);
1289 	if (rcu_segcblist_pend_cbs(&sdp->srcu_cblist)) {
1290 		spin_unlock_irqrestore_rcu_node(sdp, flags);
1291 		return false; /* Callbacks already present, so not idle. */
1292 	}
1293 	spin_unlock_irqrestore_rcu_node(sdp, flags);
1294 
1295 	/*
1296 	 * No local callbacks, so probabilistically probe global state.
1297 	 * Exact information would require acquiring locks, which would
1298 	 * kill scalability, hence the probabilistic nature of the probe.
1299 	 */
1300 
1301 	/* First, see if enough time has passed since the last GP. */
1302 	t = ktime_get_mono_fast_ns();
1303 	tlast = READ_ONCE(ssp->srcu_sup->srcu_last_gp_end);
1304 	if (exp_holdoff == 0 ||
1305 	    time_in_range_open(t, tlast, tlast + exp_holdoff))
1306 		return false; /* Too soon after last GP. */
1307 
1308 	/* Next, check for probable idleness. */
1309 	curseq = rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq);
1310 	smp_mb(); /* Order ->srcu_gp_seq with ->srcu_gp_seq_needed. */
1311 	if (ULONG_CMP_LT(curseq, READ_ONCE(ssp->srcu_sup->srcu_gp_seq_needed)))
1312 		return false; /* Grace period in progress, so not idle. */
1313 	smp_mb(); /* Order ->srcu_gp_seq with prior access. */
1314 	if (curseq != rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq))
1315 		return false; /* GP # changed, so not idle. */
1316 	return true; /* With reasonable probability, idle! */
1317 }
1318 
1319 /*
1320  * SRCU callback function to leak a callback.
1321  */
1322 static void srcu_leak_callback(struct rcu_head *rhp)
1323 {
1324 }
1325 
1326 /*
1327  * Start an SRCU grace period, and also queue the callback if non-NULL.
1328  */
1329 static unsigned long srcu_gp_start_if_needed(struct srcu_struct *ssp,
1330 					     struct rcu_head *rhp, bool do_norm)
1331 {
1332 	unsigned long flags;
1333 	int idx;
1334 	bool needexp = false;
1335 	bool needgp = false;
1336 	unsigned long s;
1337 	struct srcu_data *sdp;
1338 	struct srcu_node *sdp_mynode;
1339 	int ss_state;
1340 
1341 	check_init_srcu_struct(ssp);
1342 	/*
1343 	 * While starting a new grace period, make sure we are in an
1344 	 * SRCU read-side critical section so that the grace-period
1345 	 * sequence number cannot wrap around in the meantime.
1346 	 */
1347 	idx = __srcu_read_lock_nmisafe(ssp);
1348 	ss_state = smp_load_acquire(&ssp->srcu_sup->srcu_size_state);
1349 	if (ss_state < SRCU_SIZE_WAIT_CALL)
1350 		sdp = per_cpu_ptr(ssp->sda, get_boot_cpu_id());
1351 	else
1352 		sdp = raw_cpu_ptr(ssp->sda);
1353 	spin_lock_irqsave_sdp_contention(sdp, &flags);
1354 	if (rhp)
1355 		rcu_segcblist_enqueue(&sdp->srcu_cblist, rhp);
1356 	/*
1357 	 * It's crucial to capture the snapshot 's' for acceleration before
1358 	 * reading the current gp_seq that is used for advancing. This is
1359 	 * essential because if the acceleration snapshot is taken after a
1360 	 * failed advancement attempt, there's a risk that a grace period may
1361 	 * conclude and a new one may start in the interim. If the snapshot is
1362 	 * captured after this sequence of events, the acceleration snapshot 's'
1363 	 * could be excessively advanced, leading to acceleration failure.
1364 	 * In such a scenario, an 'acceleration leak' can occur, where new
1365 	 * callbacks become indefinitely stuck in the RCU_NEXT_TAIL segment.
1366 	 * Also note that encountering advancing failures is a normal
1367 	 * occurrence when the grace period for RCU_WAIT_TAIL is in progress.
1368 	 *
1369 	 * To see this, consider the following events which occur if
1370 	 * rcu_seq_snap() were to be called after advance:
1371 	 *
1372 	 *  1) The RCU_WAIT_TAIL segment has callbacks (gp_num = X + 4) and the
1373 	 *     RCU_NEXT_READY_TAIL also has callbacks (gp_num = X + 8).
1374 	 *
1375 	 *  2) The grace period for RCU_WAIT_TAIL is seen as started but not
1376 	 *     completed so rcu_seq_current() returns X + SRCU_STATE_SCAN1.
1377 	 *
1378 	 *  3) This value is passed to rcu_segcblist_advance() which can't move
1379 	 *     any segment forward and fails.
1380 	 *
1381 	 *  4) srcu_gp_start_if_needed() still proceeds with callback acceleration.
1382 	 *     But then the call to rcu_seq_snap() observes the grace period for the
1383 	 *     RCU_WAIT_TAIL segment as completed and the subsequent one for the
1384 	 *     RCU_NEXT_READY_TAIL segment as started (ie: X + 4 + SRCU_STATE_SCAN1)
1385 	 *     so it returns a snapshot of the next grace period, which is X + 12.
1386 	 *
1387 	 *  5) The value of X + 12 is passed to rcu_segcblist_accelerate() but the
1388 	 *     freshly enqueued callback in RCU_NEXT_TAIL can't move to
1389 	 *     RCU_NEXT_READY_TAIL which already has callbacks for a previous grace
1390 	 *     period (gp_num = X + 8). So acceleration fails.
1391 	 */
1392 	s = rcu_seq_snap(&ssp->srcu_sup->srcu_gp_seq);
1393 	if (rhp) {
1394 		rcu_segcblist_advance(&sdp->srcu_cblist,
1395 				      rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq));
1396 		/*
1397 		 * Acceleration can never fail because the base current gp_seq
1398 		 * used for acceleration is <= the value of gp_seq used for
1399 		 * advancing. This means that RCU_NEXT_TAIL segment will
1400 		 * always be able to be emptied by the acceleration into the
1401 		 * RCU_NEXT_READY_TAIL or RCU_WAIT_TAIL segments.
1402 		 */
1403 		WARN_ON_ONCE(!rcu_segcblist_accelerate(&sdp->srcu_cblist, s));
1404 	}
1405 	if (ULONG_CMP_LT(sdp->srcu_gp_seq_needed, s)) {
1406 		sdp->srcu_gp_seq_needed = s;
1407 		needgp = true;
1408 	}
1409 	if (!do_norm && ULONG_CMP_LT(sdp->srcu_gp_seq_needed_exp, s)) {
1410 		sdp->srcu_gp_seq_needed_exp = s;
1411 		needexp = true;
1412 	}
1413 	spin_unlock_irqrestore_rcu_node(sdp, flags);
1414 
1415 	/* Ensure that snp node tree is fully initialized before traversing it */
1416 	if (ss_state < SRCU_SIZE_WAIT_BARRIER)
1417 		sdp_mynode = NULL;
1418 	else
1419 		sdp_mynode = sdp->mynode;
1420 
1421 	if (needgp)
1422 		srcu_funnel_gp_start(ssp, sdp, s, do_norm);
1423 	else if (needexp)
1424 		srcu_funnel_exp_start(ssp, sdp_mynode, s);
1425 	__srcu_read_unlock_nmisafe(ssp, idx);
1426 	return s;
1427 }
1428 
1429 /*
1430  * Enqueue an SRCU callback on the srcu_data structure associated with
1431  * the current CPU and the specified srcu_struct structure, initiating
1432  * grace-period processing if it is not already running.
1433  *
1434  * Note that all CPUs must agree that the grace period extended beyond
1435  * all pre-existing SRCU read-side critical section.  On systems with
1436  * more than one CPU, this means that when "func()" is invoked, each CPU
1437  * is guaranteed to have executed a full memory barrier since the end of
1438  * its last corresponding SRCU read-side critical section whose beginning
1439  * preceded the call to call_srcu().  It also means that each CPU executing
1440  * an SRCU read-side critical section that continues beyond the start of
1441  * "func()" must have executed a memory barrier after the call_srcu()
1442  * but before the beginning of that SRCU read-side critical section.
1443  * Note that these guarantees include CPUs that are offline, idle, or
1444  * executing in user mode, as well as CPUs that are executing in the kernel.
1445  *
1446  * Furthermore, if CPU A invoked call_srcu() and CPU B invoked the
1447  * resulting SRCU callback function "func()", then both CPU A and CPU
1448  * B are guaranteed to execute a full memory barrier during the time
1449  * interval between the call to call_srcu() and the invocation of "func()".
1450  * This guarantee applies even if CPU A and CPU B are the same CPU (but
1451  * again only if the system has more than one CPU).
1452  *
1453  * Of course, these guarantees apply only for invocations of call_srcu(),
1454  * srcu_read_lock(), and srcu_read_unlock() that are all passed the same
1455  * srcu_struct structure.
1456  */
1457 static void __call_srcu(struct srcu_struct *ssp, struct rcu_head *rhp,
1458 			rcu_callback_t func, bool do_norm)
1459 {
1460 	if (debug_rcu_head_queue(rhp)) {
1461 		/* Probable double call_srcu(), so leak the callback. */
1462 		WRITE_ONCE(rhp->func, srcu_leak_callback);
1463 		WARN_ONCE(1, "call_srcu(): Leaked duplicate callback\n");
1464 		return;
1465 	}
1466 	rhp->func = func;
1467 	(void)srcu_gp_start_if_needed(ssp, rhp, do_norm);
1468 }
1469 
1470 /**
1471  * call_srcu() - Queue a callback for invocation after an SRCU grace period
1472  * @ssp: srcu_struct in queue the callback
1473  * @rhp: structure to be used for queueing the SRCU callback.
1474  * @func: function to be invoked after the SRCU grace period
1475  *
1476  * The callback function will be invoked some time after a full SRCU
1477  * grace period elapses, in other words after all pre-existing SRCU
1478  * read-side critical sections have completed.  However, the callback
1479  * function might well execute concurrently with other SRCU read-side
1480  * critical sections that started after call_srcu() was invoked.  SRCU
1481  * read-side critical sections are delimited by srcu_read_lock() and
1482  * srcu_read_unlock(), and may be nested.
1483  *
1484  * The callback will be invoked from process context, but with bh
1485  * disabled.  The callback function must therefore be fast and must
1486  * not block.
1487  *
1488  * See the description of call_rcu() for more detailed information on
1489  * memory ordering guarantees.
1490  */
1491 void call_srcu(struct srcu_struct *ssp, struct rcu_head *rhp,
1492 	       rcu_callback_t func)
1493 {
1494 	__call_srcu(ssp, rhp, func, true);
1495 }
1496 EXPORT_SYMBOL_GPL(call_srcu);
1497 
1498 /*
1499  * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
1500  */
1501 static void __synchronize_srcu(struct srcu_struct *ssp, bool do_norm)
1502 {
1503 	struct rcu_synchronize rcu;
1504 
1505 	srcu_lock_sync(&ssp->dep_map);
1506 
1507 	RCU_LOCKDEP_WARN(lockdep_is_held(ssp) ||
1508 			 lock_is_held(&rcu_bh_lock_map) ||
1509 			 lock_is_held(&rcu_lock_map) ||
1510 			 lock_is_held(&rcu_sched_lock_map),
1511 			 "Illegal synchronize_srcu() in same-type SRCU (or in RCU) read-side critical section");
1512 
1513 	if (rcu_scheduler_active == RCU_SCHEDULER_INACTIVE)
1514 		return;
1515 	might_sleep();
1516 	check_init_srcu_struct(ssp);
1517 	init_completion(&rcu.completion);
1518 	init_rcu_head_on_stack(&rcu.head);
1519 	__call_srcu(ssp, &rcu.head, wakeme_after_rcu, do_norm);
1520 	wait_for_completion(&rcu.completion);
1521 	destroy_rcu_head_on_stack(&rcu.head);
1522 
1523 	/*
1524 	 * Make sure that later code is ordered after the SRCU grace
1525 	 * period.  This pairs with the spin_lock_irq_rcu_node()
1526 	 * in srcu_invoke_callbacks().  Unlike Tree RCU, this is needed
1527 	 * because the current CPU might have been totally uninvolved with
1528 	 * (and thus unordered against) that grace period.
1529 	 */
1530 	smp_mb();
1531 }
1532 
1533 /**
1534  * synchronize_srcu_expedited - Brute-force SRCU grace period
1535  * @ssp: srcu_struct with which to synchronize.
1536  *
1537  * Wait for an SRCU grace period to elapse, but be more aggressive about
1538  * spinning rather than blocking when waiting.
1539  *
1540  * Note that synchronize_srcu_expedited() has the same deadlock and
1541  * memory-ordering properties as does synchronize_srcu().
1542  */
1543 void synchronize_srcu_expedited(struct srcu_struct *ssp)
1544 {
1545 	__synchronize_srcu(ssp, rcu_gp_is_normal());
1546 }
1547 EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
1548 
1549 /**
1550  * synchronize_srcu - wait for prior SRCU read-side critical-section completion
1551  * @ssp: srcu_struct with which to synchronize.
1552  *
1553  * Wait for the count to drain to zero of both indexes. To avoid the
1554  * possible starvation of synchronize_srcu(), it waits for the count of
1555  * the index=!(ssp->srcu_ctrp - &ssp->sda->srcu_ctrs[0]) to drain to zero
1556  * at first, and then flip the ->srcu_ctrp and wait for the count of the
1557  * other index.
1558  *
1559  * Can block; must be called from process context.
1560  *
1561  * Note that it is illegal to call synchronize_srcu() from the corresponding
1562  * SRCU read-side critical section; doing so will result in deadlock.
1563  * However, it is perfectly legal to call synchronize_srcu() on one
1564  * srcu_struct from some other srcu_struct's read-side critical section,
1565  * as long as the resulting graph of srcu_structs is acyclic.
1566  *
1567  * There are memory-ordering constraints implied by synchronize_srcu().
1568  * On systems with more than one CPU, when synchronize_srcu() returns,
1569  * each CPU is guaranteed to have executed a full memory barrier since
1570  * the end of its last corresponding SRCU read-side critical section
1571  * whose beginning preceded the call to synchronize_srcu().  In addition,
1572  * each CPU having an SRCU read-side critical section that extends beyond
1573  * the return from synchronize_srcu() is guaranteed to have executed a
1574  * full memory barrier after the beginning of synchronize_srcu() and before
1575  * the beginning of that SRCU read-side critical section.  Note that these
1576  * guarantees include CPUs that are offline, idle, or executing in user mode,
1577  * as well as CPUs that are executing in the kernel.
1578  *
1579  * Furthermore, if CPU A invoked synchronize_srcu(), which returned
1580  * to its caller on CPU B, then both CPU A and CPU B are guaranteed
1581  * to have executed a full memory barrier during the execution of
1582  * synchronize_srcu().  This guarantee applies even if CPU A and CPU B
1583  * are the same CPU, but again only if the system has more than one CPU.
1584  *
1585  * Of course, these memory-ordering guarantees apply only when
1586  * synchronize_srcu(), srcu_read_lock(), and srcu_read_unlock() are
1587  * passed the same srcu_struct structure.
1588  *
1589  * Implementation of these memory-ordering guarantees is similar to
1590  * that of synchronize_rcu().
1591  *
1592  * If SRCU is likely idle as determined by srcu_should_expedite(),
1593  * expedite the first request.  This semantic was provided by Classic SRCU,
1594  * and is relied upon by its users, so TREE SRCU must also provide it.
1595  * Note that detecting idleness is heuristic and subject to both false
1596  * positives and negatives.
1597  */
1598 void synchronize_srcu(struct srcu_struct *ssp)
1599 {
1600 	if (srcu_should_expedite(ssp) || rcu_gp_is_expedited())
1601 		synchronize_srcu_expedited(ssp);
1602 	else
1603 		__synchronize_srcu(ssp, true);
1604 }
1605 EXPORT_SYMBOL_GPL(synchronize_srcu);
1606 
1607 /**
1608  * get_state_synchronize_srcu - Provide an end-of-grace-period cookie
1609  * @ssp: srcu_struct to provide cookie for.
1610  *
1611  * This function returns a cookie that can be passed to
1612  * poll_state_synchronize_srcu(), which will return true if a full grace
1613  * period has elapsed in the meantime.  It is the caller's responsibility
1614  * to make sure that grace period happens, for example, by invoking
1615  * call_srcu() after return from get_state_synchronize_srcu().
1616  */
1617 unsigned long get_state_synchronize_srcu(struct srcu_struct *ssp)
1618 {
1619 	// Any prior manipulation of SRCU-protected data must happen
1620 	// before the load from ->srcu_gp_seq.
1621 	smp_mb();
1622 	return rcu_seq_snap(&ssp->srcu_sup->srcu_gp_seq);
1623 }
1624 EXPORT_SYMBOL_GPL(get_state_synchronize_srcu);
1625 
1626 /**
1627  * start_poll_synchronize_srcu - Provide cookie and start grace period
1628  * @ssp: srcu_struct to provide cookie for.
1629  *
1630  * This function returns a cookie that can be passed to
1631  * poll_state_synchronize_srcu(), which will return true if a full grace
1632  * period has elapsed in the meantime.  Unlike get_state_synchronize_srcu(),
1633  * this function also ensures that any needed SRCU grace period will be
1634  * started.  This convenience does come at a cost in terms of CPU overhead.
1635  */
1636 unsigned long start_poll_synchronize_srcu(struct srcu_struct *ssp)
1637 {
1638 	return srcu_gp_start_if_needed(ssp, NULL, true);
1639 }
1640 EXPORT_SYMBOL_GPL(start_poll_synchronize_srcu);
1641 
1642 /**
1643  * poll_state_synchronize_srcu - Has cookie's grace period ended?
1644  * @ssp: srcu_struct to provide cookie for.
1645  * @cookie: Return value from get_state_synchronize_srcu() or start_poll_synchronize_srcu().
1646  *
1647  * This function takes the cookie that was returned from either
1648  * get_state_synchronize_srcu() or start_poll_synchronize_srcu(), and
1649  * returns @true if an SRCU grace period elapsed since the time that the
1650  * cookie was created.
1651  *
1652  * Because cookies are finite in size, wrapping/overflow is possible.
1653  * This is more pronounced on 32-bit systems where cookies are 32 bits,
1654  * where in theory wrapping could happen in about 14 hours assuming
1655  * 25-microsecond expedited SRCU grace periods.  However, a more likely
1656  * overflow lower bound is on the order of 24 days in the case of
1657  * one-millisecond SRCU grace periods.  Of course, wrapping in a 64-bit
1658  * system requires geologic timespans, as in more than seven million years
1659  * even for expedited SRCU grace periods.
1660  *
1661  * Wrapping/overflow is much more of an issue for CONFIG_SMP=n systems
1662  * that also have CONFIG_PREEMPTION=n, which selects Tiny SRCU.  This uses
1663  * a 16-bit cookie, which rcutorture routinely wraps in a matter of a
1664  * few minutes.  If this proves to be a problem, this counter will be
1665  * expanded to the same size as for Tree SRCU.
1666  */
1667 bool poll_state_synchronize_srcu(struct srcu_struct *ssp, unsigned long cookie)
1668 {
1669 	if (cookie != SRCU_GET_STATE_COMPLETED &&
1670 	    !rcu_seq_done_exact(&ssp->srcu_sup->srcu_gp_seq, cookie))
1671 		return false;
1672 	// Ensure that the end of the SRCU grace period happens before
1673 	// any subsequent code that the caller might execute.
1674 	smp_mb(); // ^^^
1675 	return true;
1676 }
1677 EXPORT_SYMBOL_GPL(poll_state_synchronize_srcu);
1678 
1679 /*
1680  * Callback function for srcu_barrier() use.
1681  */
1682 static void srcu_barrier_cb(struct rcu_head *rhp)
1683 {
1684 	struct srcu_data *sdp;
1685 	struct srcu_struct *ssp;
1686 
1687 	rhp->next = rhp; // Mark the callback as having been invoked.
1688 	sdp = container_of(rhp, struct srcu_data, srcu_barrier_head);
1689 	ssp = sdp->ssp;
1690 	if (atomic_dec_and_test(&ssp->srcu_sup->srcu_barrier_cpu_cnt))
1691 		complete(&ssp->srcu_sup->srcu_barrier_completion);
1692 }
1693 
1694 /*
1695  * Enqueue an srcu_barrier() callback on the specified srcu_data
1696  * structure's ->cblist.  but only if that ->cblist already has at least one
1697  * callback enqueued.  Note that if a CPU already has callbacks enqueue,
1698  * it must have already registered the need for a future grace period,
1699  * so all we need do is enqueue a callback that will use the same grace
1700  * period as the last callback already in the queue.
1701  */
1702 static void srcu_barrier_one_cpu(struct srcu_struct *ssp, struct srcu_data *sdp)
1703 {
1704 	spin_lock_irq_rcu_node(sdp);
1705 	atomic_inc(&ssp->srcu_sup->srcu_barrier_cpu_cnt);
1706 	sdp->srcu_barrier_head.func = srcu_barrier_cb;
1707 	debug_rcu_head_queue(&sdp->srcu_barrier_head);
1708 	if (!rcu_segcblist_entrain(&sdp->srcu_cblist,
1709 				   &sdp->srcu_barrier_head)) {
1710 		debug_rcu_head_unqueue(&sdp->srcu_barrier_head);
1711 		atomic_dec(&ssp->srcu_sup->srcu_barrier_cpu_cnt);
1712 	}
1713 	spin_unlock_irq_rcu_node(sdp);
1714 }
1715 
1716 /**
1717  * srcu_barrier - Wait until all in-flight call_srcu() callbacks complete.
1718  * @ssp: srcu_struct on which to wait for in-flight callbacks.
1719  */
1720 void srcu_barrier(struct srcu_struct *ssp)
1721 {
1722 	int cpu;
1723 	int idx;
1724 	unsigned long s = rcu_seq_snap(&ssp->srcu_sup->srcu_barrier_seq);
1725 
1726 	check_init_srcu_struct(ssp);
1727 	mutex_lock(&ssp->srcu_sup->srcu_barrier_mutex);
1728 	if (rcu_seq_done(&ssp->srcu_sup->srcu_barrier_seq, s)) {
1729 		smp_mb(); /* Force ordering following return. */
1730 		mutex_unlock(&ssp->srcu_sup->srcu_barrier_mutex);
1731 		return; /* Someone else did our work for us. */
1732 	}
1733 	rcu_seq_start(&ssp->srcu_sup->srcu_barrier_seq);
1734 	init_completion(&ssp->srcu_sup->srcu_barrier_completion);
1735 
1736 	/* Initial count prevents reaching zero until all CBs are posted. */
1737 	atomic_set(&ssp->srcu_sup->srcu_barrier_cpu_cnt, 1);
1738 
1739 	idx = __srcu_read_lock_nmisafe(ssp);
1740 	if (smp_load_acquire(&ssp->srcu_sup->srcu_size_state) < SRCU_SIZE_WAIT_BARRIER)
1741 		srcu_barrier_one_cpu(ssp, per_cpu_ptr(ssp->sda,	get_boot_cpu_id()));
1742 	else
1743 		for_each_possible_cpu(cpu)
1744 			srcu_barrier_one_cpu(ssp, per_cpu_ptr(ssp->sda, cpu));
1745 	__srcu_read_unlock_nmisafe(ssp, idx);
1746 
1747 	/* Remove the initial count, at which point reaching zero can happen. */
1748 	if (atomic_dec_and_test(&ssp->srcu_sup->srcu_barrier_cpu_cnt))
1749 		complete(&ssp->srcu_sup->srcu_barrier_completion);
1750 	wait_for_completion(&ssp->srcu_sup->srcu_barrier_completion);
1751 
1752 	rcu_seq_end(&ssp->srcu_sup->srcu_barrier_seq);
1753 	mutex_unlock(&ssp->srcu_sup->srcu_barrier_mutex);
1754 }
1755 EXPORT_SYMBOL_GPL(srcu_barrier);
1756 
1757 /* Callback for srcu_expedite_current() usage. */
1758 static void srcu_expedite_current_cb(struct rcu_head *rhp)
1759 {
1760 	unsigned long flags;
1761 	bool needcb = false;
1762 	struct srcu_data *sdp = container_of(rhp, struct srcu_data, srcu_ec_head);
1763 
1764 	spin_lock_irqsave_sdp_contention(sdp, &flags);
1765 	if (sdp->srcu_ec_state == SRCU_EC_IDLE) {
1766 		WARN_ON_ONCE(1);
1767 	} else if (sdp->srcu_ec_state == SRCU_EC_PENDING) {
1768 		sdp->srcu_ec_state = SRCU_EC_IDLE;
1769 	} else {
1770 		WARN_ON_ONCE(sdp->srcu_ec_state != SRCU_EC_REPOST);
1771 		sdp->srcu_ec_state = SRCU_EC_PENDING;
1772 		needcb = true;
1773 	}
1774 	spin_unlock_irqrestore_rcu_node(sdp, flags);
1775 	// If needed, requeue ourselves as an expedited SRCU callback.
1776 	if (needcb)
1777 		__call_srcu(sdp->ssp, &sdp->srcu_ec_head, srcu_expedite_current_cb, false);
1778 }
1779 
1780 /**
1781  * srcu_expedite_current - Expedite the current SRCU grace period
1782  * @ssp: srcu_struct to expedite.
1783  *
1784  * Cause the current SRCU grace period to become expedited.  The grace
1785  * period following the current one might also be expedited.  If there is
1786  * no current grace period, one might be created.  If the current grace
1787  * period is currently sleeping, that sleep will complete before expediting
1788  * will take effect.
1789  */
1790 void srcu_expedite_current(struct srcu_struct *ssp)
1791 {
1792 	unsigned long flags;
1793 	bool needcb = false;
1794 	struct srcu_data *sdp;
1795 
1796 	migrate_disable();
1797 	sdp = this_cpu_ptr(ssp->sda);
1798 	spin_lock_irqsave_sdp_contention(sdp, &flags);
1799 	if (sdp->srcu_ec_state == SRCU_EC_IDLE) {
1800 		sdp->srcu_ec_state = SRCU_EC_PENDING;
1801 		needcb = true;
1802 	} else if (sdp->srcu_ec_state == SRCU_EC_PENDING) {
1803 		sdp->srcu_ec_state = SRCU_EC_REPOST;
1804 	} else {
1805 		WARN_ON_ONCE(sdp->srcu_ec_state != SRCU_EC_REPOST);
1806 	}
1807 	spin_unlock_irqrestore_rcu_node(sdp, flags);
1808 	// If needed, queue an expedited SRCU callback.
1809 	if (needcb)
1810 		__call_srcu(ssp, &sdp->srcu_ec_head, srcu_expedite_current_cb, false);
1811 	migrate_enable();
1812 }
1813 EXPORT_SYMBOL_GPL(srcu_expedite_current);
1814 
1815 /**
1816  * srcu_batches_completed - return batches completed.
1817  * @ssp: srcu_struct on which to report batch completion.
1818  *
1819  * Report the number of batches, correlated with, but not necessarily
1820  * precisely the same as, the number of grace periods that have elapsed.
1821  */
1822 unsigned long srcu_batches_completed(struct srcu_struct *ssp)
1823 {
1824 	return READ_ONCE(ssp->srcu_sup->srcu_gp_seq);
1825 }
1826 EXPORT_SYMBOL_GPL(srcu_batches_completed);
1827 
1828 /*
1829  * Core SRCU state machine.  Push state bits of ->srcu_gp_seq
1830  * to SRCU_STATE_SCAN2, and invoke srcu_gp_end() when scan has
1831  * completed in that state.
1832  */
1833 static void srcu_advance_state(struct srcu_struct *ssp)
1834 {
1835 	int idx;
1836 
1837 	mutex_lock(&ssp->srcu_sup->srcu_gp_mutex);
1838 
1839 	/*
1840 	 * Because readers might be delayed for an extended period after
1841 	 * fetching ->srcu_ctrp for their index, at any point in time there
1842 	 * might well be readers using both idx=0 and idx=1.  We therefore
1843 	 * need to wait for readers to clear from both index values before
1844 	 * invoking a callback.
1845 	 *
1846 	 * The load-acquire ensures that we see the accesses performed
1847 	 * by the prior grace period.
1848 	 */
1849 	idx = rcu_seq_state(smp_load_acquire(&ssp->srcu_sup->srcu_gp_seq)); /* ^^^ */
1850 	if (idx == SRCU_STATE_IDLE) {
1851 		spin_lock_irq_rcu_node(ssp->srcu_sup);
1852 		if (ULONG_CMP_GE(ssp->srcu_sup->srcu_gp_seq, ssp->srcu_sup->srcu_gp_seq_needed)) {
1853 			WARN_ON_ONCE(rcu_seq_state(ssp->srcu_sup->srcu_gp_seq));
1854 			spin_unlock_irq_rcu_node(ssp->srcu_sup);
1855 			mutex_unlock(&ssp->srcu_sup->srcu_gp_mutex);
1856 			return;
1857 		}
1858 		idx = rcu_seq_state(READ_ONCE(ssp->srcu_sup->srcu_gp_seq));
1859 		if (idx == SRCU_STATE_IDLE)
1860 			srcu_gp_start(ssp);
1861 		spin_unlock_irq_rcu_node(ssp->srcu_sup);
1862 		if (idx != SRCU_STATE_IDLE) {
1863 			mutex_unlock(&ssp->srcu_sup->srcu_gp_mutex);
1864 			return; /* Someone else started the grace period. */
1865 		}
1866 	}
1867 
1868 	if (rcu_seq_state(READ_ONCE(ssp->srcu_sup->srcu_gp_seq)) == SRCU_STATE_SCAN1) {
1869 		idx = !(ssp->srcu_ctrp - &ssp->sda->srcu_ctrs[0]);
1870 		if (!try_check_zero(ssp, idx, 1)) {
1871 			mutex_unlock(&ssp->srcu_sup->srcu_gp_mutex);
1872 			return; /* readers present, retry later. */
1873 		}
1874 		srcu_flip(ssp);
1875 		spin_lock_irq_rcu_node(ssp->srcu_sup);
1876 		rcu_seq_set_state(&ssp->srcu_sup->srcu_gp_seq, SRCU_STATE_SCAN2);
1877 		ssp->srcu_sup->srcu_n_exp_nodelay = 0;
1878 		spin_unlock_irq_rcu_node(ssp->srcu_sup);
1879 	}
1880 
1881 	if (rcu_seq_state(READ_ONCE(ssp->srcu_sup->srcu_gp_seq)) == SRCU_STATE_SCAN2) {
1882 
1883 		/*
1884 		 * SRCU read-side critical sections are normally short,
1885 		 * so check at least twice in quick succession after a flip.
1886 		 */
1887 		idx = !(ssp->srcu_ctrp - &ssp->sda->srcu_ctrs[0]);
1888 		if (!try_check_zero(ssp, idx, 2)) {
1889 			mutex_unlock(&ssp->srcu_sup->srcu_gp_mutex);
1890 			return; /* readers present, retry later. */
1891 		}
1892 		ssp->srcu_sup->srcu_n_exp_nodelay = 0;
1893 		srcu_gp_end(ssp);  /* Releases ->srcu_gp_mutex. */
1894 	}
1895 }
1896 
1897 /*
1898  * Invoke a limited number of SRCU callbacks that have passed through
1899  * their grace period.  If there are more to do, SRCU will reschedule
1900  * the workqueue.  Note that needed memory barriers have been executed
1901  * in this task's context by srcu_readers_active_idx_check().
1902  */
1903 static void srcu_invoke_callbacks(struct work_struct *work)
1904 {
1905 	long len;
1906 	bool more;
1907 	struct rcu_cblist ready_cbs;
1908 	struct rcu_head *rhp;
1909 	struct srcu_data *sdp;
1910 	struct srcu_struct *ssp;
1911 
1912 	sdp = container_of(work, struct srcu_data, work);
1913 
1914 	ssp = sdp->ssp;
1915 	rcu_cblist_init(&ready_cbs);
1916 	spin_lock_irq_rcu_node(sdp);
1917 	WARN_ON_ONCE(!rcu_segcblist_segempty(&sdp->srcu_cblist, RCU_NEXT_TAIL));
1918 	rcu_segcblist_advance(&sdp->srcu_cblist,
1919 			      rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq));
1920 	/*
1921 	 * Although this function is theoretically re-entrant, concurrent
1922 	 * callbacks invocation is disallowed to avoid executing an SRCU barrier
1923 	 * too early.
1924 	 */
1925 	if (sdp->srcu_cblist_invoking ||
1926 	    !rcu_segcblist_ready_cbs(&sdp->srcu_cblist)) {
1927 		spin_unlock_irq_rcu_node(sdp);
1928 		return;  /* Someone else on the job or nothing to do. */
1929 	}
1930 
1931 	/* We are on the job!  Extract and invoke ready callbacks. */
1932 	sdp->srcu_cblist_invoking = true;
1933 	rcu_segcblist_extract_done_cbs(&sdp->srcu_cblist, &ready_cbs);
1934 	len = ready_cbs.len;
1935 	spin_unlock_irq_rcu_node(sdp);
1936 	rhp = rcu_cblist_dequeue(&ready_cbs);
1937 	for (; rhp != NULL; rhp = rcu_cblist_dequeue(&ready_cbs)) {
1938 		debug_rcu_head_unqueue(rhp);
1939 		debug_rcu_head_callback(rhp);
1940 		local_bh_disable();
1941 		rhp->func(rhp);
1942 		local_bh_enable();
1943 	}
1944 	WARN_ON_ONCE(ready_cbs.len);
1945 
1946 	/*
1947 	 * Update counts, accelerate new callbacks, and if needed,
1948 	 * schedule another round of callback invocation.
1949 	 */
1950 	spin_lock_irq_rcu_node(sdp);
1951 	rcu_segcblist_add_len(&sdp->srcu_cblist, -len);
1952 	sdp->srcu_cblist_invoking = false;
1953 	more = rcu_segcblist_ready_cbs(&sdp->srcu_cblist);
1954 	spin_unlock_irq_rcu_node(sdp);
1955 	/* An SRCU barrier or callbacks from previous nesting work pending */
1956 	if (more)
1957 		srcu_schedule_cbs_sdp(sdp, 0);
1958 }
1959 
1960 /*
1961  * Finished one round of SRCU grace period.  Start another if there are
1962  * more SRCU callbacks queued, otherwise put SRCU into not-running state.
1963  */
1964 static void srcu_reschedule(struct srcu_struct *ssp, unsigned long delay)
1965 {
1966 	bool pushgp = true;
1967 
1968 	spin_lock_irq_rcu_node(ssp->srcu_sup);
1969 	if (ULONG_CMP_GE(ssp->srcu_sup->srcu_gp_seq, ssp->srcu_sup->srcu_gp_seq_needed)) {
1970 		if (!WARN_ON_ONCE(rcu_seq_state(ssp->srcu_sup->srcu_gp_seq))) {
1971 			/* All requests fulfilled, time to go idle. */
1972 			pushgp = false;
1973 		}
1974 	} else if (!rcu_seq_state(ssp->srcu_sup->srcu_gp_seq)) {
1975 		/* Outstanding request and no GP.  Start one. */
1976 		srcu_gp_start(ssp);
1977 	}
1978 	spin_unlock_irq_rcu_node(ssp->srcu_sup);
1979 
1980 	if (pushgp)
1981 		queue_delayed_work(rcu_gp_wq, &ssp->srcu_sup->work, delay);
1982 }
1983 
1984 /*
1985  * This is the work-queue function that handles SRCU grace periods.
1986  */
1987 static void process_srcu(struct work_struct *work)
1988 {
1989 	unsigned long curdelay;
1990 	unsigned long j;
1991 	struct srcu_struct *ssp;
1992 	struct srcu_usage *sup;
1993 
1994 	sup = container_of(work, struct srcu_usage, work.work);
1995 	ssp = sup->srcu_ssp;
1996 
1997 	srcu_advance_state(ssp);
1998 	spin_lock_irq_rcu_node(ssp->srcu_sup);
1999 	curdelay = srcu_get_delay(ssp);
2000 	spin_unlock_irq_rcu_node(ssp->srcu_sup);
2001 	if (curdelay) {
2002 		WRITE_ONCE(sup->reschedule_count, 0);
2003 	} else {
2004 		j = jiffies;
2005 		if (READ_ONCE(sup->reschedule_jiffies) == j) {
2006 			ASSERT_EXCLUSIVE_WRITER(sup->reschedule_count);
2007 			WRITE_ONCE(sup->reschedule_count, READ_ONCE(sup->reschedule_count) + 1);
2008 			if (READ_ONCE(sup->reschedule_count) > srcu_max_nodelay)
2009 				curdelay = 1;
2010 		} else {
2011 			WRITE_ONCE(sup->reschedule_count, 1);
2012 			WRITE_ONCE(sup->reschedule_jiffies, j);
2013 		}
2014 	}
2015 	srcu_reschedule(ssp, curdelay);
2016 }
2017 
2018 void srcutorture_get_gp_data(struct srcu_struct *ssp, int *flags,
2019 			     unsigned long *gp_seq)
2020 {
2021 	*flags = 0;
2022 	*gp_seq = rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq);
2023 }
2024 EXPORT_SYMBOL_GPL(srcutorture_get_gp_data);
2025 
2026 static const char * const srcu_size_state_name[] = {
2027 	"SRCU_SIZE_SMALL",
2028 	"SRCU_SIZE_ALLOC",
2029 	"SRCU_SIZE_WAIT_BARRIER",
2030 	"SRCU_SIZE_WAIT_CALL",
2031 	"SRCU_SIZE_WAIT_CBS1",
2032 	"SRCU_SIZE_WAIT_CBS2",
2033 	"SRCU_SIZE_WAIT_CBS3",
2034 	"SRCU_SIZE_WAIT_CBS4",
2035 	"SRCU_SIZE_BIG",
2036 	"SRCU_SIZE_???",
2037 };
2038 
2039 void srcu_torture_stats_print(struct srcu_struct *ssp, char *tt, char *tf)
2040 {
2041 	int cpu;
2042 	int idx;
2043 	unsigned long s0 = 0, s1 = 0;
2044 	int ss_state = READ_ONCE(ssp->srcu_sup->srcu_size_state);
2045 	int ss_state_idx = ss_state;
2046 
2047 	idx = ssp->srcu_ctrp - &ssp->sda->srcu_ctrs[0];
2048 	if (ss_state < 0 || ss_state >= ARRAY_SIZE(srcu_size_state_name))
2049 		ss_state_idx = ARRAY_SIZE(srcu_size_state_name) - 1;
2050 	pr_alert("%s%s Tree SRCU g%ld state %d (%s)",
2051 		 tt, tf, rcu_seq_current(&ssp->srcu_sup->srcu_gp_seq), ss_state,
2052 		 srcu_size_state_name[ss_state_idx]);
2053 	if (!ssp->sda) {
2054 		// Called after cleanup_srcu_struct(), perhaps.
2055 		pr_cont(" No per-CPU srcu_data structures (->sda == NULL).\n");
2056 	} else {
2057 		pr_cont(" per-CPU(idx=%d):", idx);
2058 		for_each_possible_cpu(cpu) {
2059 			unsigned long l0, l1;
2060 			unsigned long u0, u1;
2061 			long c0, c1;
2062 			struct srcu_data *sdp;
2063 
2064 			sdp = per_cpu_ptr(ssp->sda, cpu);
2065 			u0 = data_race(atomic_long_read(&sdp->srcu_ctrs[!idx].srcu_unlocks));
2066 			u1 = data_race(atomic_long_read(&sdp->srcu_ctrs[idx].srcu_unlocks));
2067 
2068 			/*
2069 			 * Make sure that a lock is always counted if the corresponding
2070 			 * unlock is counted.
2071 			 */
2072 			smp_rmb();
2073 
2074 			l0 = data_race(atomic_long_read(&sdp->srcu_ctrs[!idx].srcu_locks));
2075 			l1 = data_race(atomic_long_read(&sdp->srcu_ctrs[idx].srcu_locks));
2076 
2077 			c0 = l0 - u0;
2078 			c1 = l1 - u1;
2079 			pr_cont(" %d(%ld,%ld %c)",
2080 				cpu, c0, c1,
2081 				"C."[rcu_segcblist_empty(&sdp->srcu_cblist)]);
2082 			s0 += c0;
2083 			s1 += c1;
2084 		}
2085 		pr_cont(" T(%ld,%ld)\n", s0, s1);
2086 	}
2087 	if (SRCU_SIZING_IS_TORTURE())
2088 		srcu_transition_to_big(ssp);
2089 }
2090 EXPORT_SYMBOL_GPL(srcu_torture_stats_print);
2091 
2092 static int __init srcu_bootup_announce(void)
2093 {
2094 	pr_info("Hierarchical SRCU implementation.\n");
2095 	if (exp_holdoff != DEFAULT_SRCU_EXP_HOLDOFF)
2096 		pr_info("\tNon-default auto-expedite holdoff of %lu ns.\n", exp_holdoff);
2097 	if (srcu_retry_check_delay != SRCU_DEFAULT_RETRY_CHECK_DELAY)
2098 		pr_info("\tNon-default retry check delay of %lu us.\n", srcu_retry_check_delay);
2099 	if (srcu_max_nodelay != SRCU_DEFAULT_MAX_NODELAY)
2100 		pr_info("\tNon-default max no-delay of %lu.\n", srcu_max_nodelay);
2101 	pr_info("\tMax phase no-delay instances is %lu.\n", srcu_max_nodelay_phase);
2102 	return 0;
2103 }
2104 early_initcall(srcu_bootup_announce);
2105 
2106 void __init srcu_init(void)
2107 {
2108 	struct srcu_usage *sup;
2109 
2110 	/* Decide on srcu_struct-size strategy. */
2111 	if (SRCU_SIZING_IS(SRCU_SIZING_AUTO)) {
2112 		if (nr_cpu_ids >= big_cpu_lim) {
2113 			convert_to_big = SRCU_SIZING_INIT; // Don't bother waiting for contention.
2114 			pr_info("%s: Setting srcu_struct sizes to big.\n", __func__);
2115 		} else {
2116 			convert_to_big = SRCU_SIZING_NONE | SRCU_SIZING_CONTEND;
2117 			pr_info("%s: Setting srcu_struct sizes based on contention.\n", __func__);
2118 		}
2119 	}
2120 
2121 	/*
2122 	 * Once that is set, call_srcu() can follow the normal path and
2123 	 * queue delayed work. This must follow RCU workqueues creation
2124 	 * and timers initialization.
2125 	 */
2126 	srcu_init_done = true;
2127 	while (!list_empty(&srcu_boot_list)) {
2128 		sup = list_first_entry(&srcu_boot_list, struct srcu_usage,
2129 				      work.work.entry);
2130 		list_del_init(&sup->work.work.entry);
2131 		if (SRCU_SIZING_IS(SRCU_SIZING_INIT) &&
2132 		    sup->srcu_size_state == SRCU_SIZE_SMALL)
2133 			sup->srcu_size_state = SRCU_SIZE_ALLOC;
2134 		queue_work(rcu_gp_wq, &sup->work.work);
2135 	}
2136 }
2137 
2138 #ifdef CONFIG_MODULES
2139 
2140 /* Initialize any global-scope srcu_struct structures used by this module. */
2141 static int srcu_module_coming(struct module *mod)
2142 {
2143 	int i;
2144 	struct srcu_struct *ssp;
2145 	struct srcu_struct **sspp = mod->srcu_struct_ptrs;
2146 
2147 	for (i = 0; i < mod->num_srcu_structs; i++) {
2148 		ssp = *(sspp++);
2149 		ssp->sda = alloc_percpu(struct srcu_data);
2150 		if (WARN_ON_ONCE(!ssp->sda))
2151 			return -ENOMEM;
2152 		ssp->srcu_ctrp = &ssp->sda->srcu_ctrs[0];
2153 	}
2154 	return 0;
2155 }
2156 
2157 /* Clean up any global-scope srcu_struct structures used by this module. */
2158 static void srcu_module_going(struct module *mod)
2159 {
2160 	int i;
2161 	struct srcu_struct *ssp;
2162 	struct srcu_struct **sspp = mod->srcu_struct_ptrs;
2163 
2164 	for (i = 0; i < mod->num_srcu_structs; i++) {
2165 		ssp = *(sspp++);
2166 		if (!rcu_seq_state(smp_load_acquire(&ssp->srcu_sup->srcu_gp_seq_needed)) &&
2167 		    !WARN_ON_ONCE(!ssp->srcu_sup->sda_is_static))
2168 			cleanup_srcu_struct(ssp);
2169 		if (!WARN_ON(srcu_readers_active(ssp)))
2170 			free_percpu(ssp->sda);
2171 	}
2172 }
2173 
2174 /* Handle one module, either coming or going. */
2175 static int srcu_module_notify(struct notifier_block *self,
2176 			      unsigned long val, void *data)
2177 {
2178 	struct module *mod = data;
2179 	int ret = 0;
2180 
2181 	switch (val) {
2182 	case MODULE_STATE_COMING:
2183 		ret = srcu_module_coming(mod);
2184 		break;
2185 	case MODULE_STATE_GOING:
2186 		srcu_module_going(mod);
2187 		break;
2188 	default:
2189 		break;
2190 	}
2191 	return ret;
2192 }
2193 
2194 static struct notifier_block srcu_module_nb = {
2195 	.notifier_call = srcu_module_notify,
2196 	.priority = 0,
2197 };
2198 
2199 static __init int init_srcu_module_notifier(void)
2200 {
2201 	int ret;
2202 
2203 	ret = register_module_notifier(&srcu_module_nb);
2204 	if (ret)
2205 		pr_warn("Failed to register srcu module notifier\n");
2206 	return ret;
2207 }
2208 late_initcall(init_srcu_module_notifier);
2209 
2210 #endif /* #ifdef CONFIG_MODULES */
2211