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