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