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