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