]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - kernel/rcu/srcutree.c
srcu: Expedite srcu_schedule_cbs_snp() callback invocation
[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/srcu.h>
38
39 #include "rcu.h"
40
41 static void srcu_invoke_callbacks(struct work_struct *work);
42 static void srcu_reschedule(struct srcu_struct *sp, unsigned long delay);
43
44 /*
45 * Initialize SRCU combining tree. Note that statically allocated
46 * srcu_struct structures might already have srcu_read_lock() and
47 * srcu_read_unlock() running against them. So if the is_static parameter
48 * is set, don't initialize ->srcu_lock_count[] and ->srcu_unlock_count[].
49 */
50 static void init_srcu_struct_nodes(struct srcu_struct *sp, bool is_static)
51 {
52 int cpu;
53 int i;
54 int level = 0;
55 int levelspread[RCU_NUM_LVLS];
56 struct srcu_data *sdp;
57 struct srcu_node *snp;
58 struct srcu_node *snp_first;
59
60 /* Work out the overall tree geometry. */
61 sp->level[0] = &sp->node[0];
62 for (i = 1; i < rcu_num_lvls; i++)
63 sp->level[i] = sp->level[i - 1] + num_rcu_lvl[i - 1];
64 rcu_init_levelspread(levelspread, num_rcu_lvl);
65
66 /* Each pass through this loop initializes one srcu_node structure. */
67 rcu_for_each_node_breadth_first(sp, snp) {
68 spin_lock_init(&snp->lock);
69 for (i = 0; i < ARRAY_SIZE(snp->srcu_have_cbs); i++)
70 snp->srcu_have_cbs[i] = 0;
71 snp->grplo = -1;
72 snp->grphi = -1;
73 if (snp == &sp->node[0]) {
74 /* Root node, special case. */
75 snp->srcu_parent = NULL;
76 continue;
77 }
78
79 /* Non-root node. */
80 if (snp == sp->level[level + 1])
81 level++;
82 snp->srcu_parent = sp->level[level - 1] +
83 (snp - sp->level[level]) /
84 levelspread[level - 1];
85 }
86
87 /*
88 * Initialize the per-CPU srcu_data array, which feeds into the
89 * leaves of the srcu_node tree.
90 */
91 WARN_ON_ONCE(ARRAY_SIZE(sdp->srcu_lock_count) !=
92 ARRAY_SIZE(sdp->srcu_unlock_count));
93 level = rcu_num_lvls - 1;
94 snp_first = sp->level[level];
95 for_each_possible_cpu(cpu) {
96 sdp = per_cpu_ptr(sp->sda, cpu);
97 spin_lock_init(&sdp->lock);
98 rcu_segcblist_init(&sdp->srcu_cblist);
99 sdp->srcu_cblist_invoking = false;
100 sdp->srcu_gp_seq_needed = sp->srcu_gp_seq;
101 sdp->mynode = &snp_first[cpu / levelspread[level]];
102 for (snp = sdp->mynode; snp != NULL; snp = snp->srcu_parent) {
103 if (snp->grplo < 0)
104 snp->grplo = cpu;
105 snp->grphi = cpu;
106 }
107 sdp->cpu = cpu;
108 INIT_DELAYED_WORK(&sdp->work, srcu_invoke_callbacks);
109 sdp->sp = sp;
110 if (is_static)
111 continue;
112
113 /* Dynamically allocated, better be no srcu_read_locks()! */
114 for (i = 0; i < ARRAY_SIZE(sdp->srcu_lock_count); i++) {
115 sdp->srcu_lock_count[i] = 0;
116 sdp->srcu_unlock_count[i] = 0;
117 }
118 }
119 }
120
121 /*
122 * Initialize non-compile-time initialized fields, including the
123 * associated srcu_node and srcu_data structures. The is_static
124 * parameter is passed through to init_srcu_struct_nodes(), and
125 * also tells us that ->sda has already been wired up to srcu_data.
126 */
127 static int init_srcu_struct_fields(struct srcu_struct *sp, bool is_static)
128 {
129 mutex_init(&sp->srcu_cb_mutex);
130 mutex_init(&sp->srcu_gp_mutex);
131 sp->srcu_idx = 0;
132 sp->srcu_gp_seq = 0;
133 atomic_set(&sp->srcu_exp_cnt, 0);
134 sp->srcu_barrier_seq = 0;
135 mutex_init(&sp->srcu_barrier_mutex);
136 atomic_set(&sp->srcu_barrier_cpu_cnt, 0);
137 INIT_DELAYED_WORK(&sp->work, process_srcu);
138 if (!is_static)
139 sp->sda = alloc_percpu(struct srcu_data);
140 init_srcu_struct_nodes(sp, is_static);
141 smp_store_release(&sp->srcu_gp_seq_needed, 0); /* Init done. */
142 return sp->sda ? 0 : -ENOMEM;
143 }
144
145 #ifdef CONFIG_DEBUG_LOCK_ALLOC
146
147 int __init_srcu_struct(struct srcu_struct *sp, const char *name,
148 struct lock_class_key *key)
149 {
150 /* Don't re-initialize a lock while it is held. */
151 debug_check_no_locks_freed((void *)sp, sizeof(*sp));
152 lockdep_init_map(&sp->dep_map, name, key, 0);
153 spin_lock_init(&sp->gp_lock);
154 return init_srcu_struct_fields(sp, false);
155 }
156 EXPORT_SYMBOL_GPL(__init_srcu_struct);
157
158 #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
159
160 /**
161 * init_srcu_struct - initialize a sleep-RCU structure
162 * @sp: structure to initialize.
163 *
164 * Must invoke this on a given srcu_struct before passing that srcu_struct
165 * to any other function. Each srcu_struct represents a separate domain
166 * of SRCU protection.
167 */
168 int init_srcu_struct(struct srcu_struct *sp)
169 {
170 spin_lock_init(&sp->gp_lock);
171 return init_srcu_struct_fields(sp, false);
172 }
173 EXPORT_SYMBOL_GPL(init_srcu_struct);
174
175 #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */
176
177 /*
178 * First-use initialization of statically allocated srcu_struct
179 * structure. Wiring up the combining tree is more than can be
180 * done with compile-time initialization, so this check is added
181 * to each update-side SRCU primitive. Use ->gp_lock, which -is-
182 * compile-time initialized, to resolve races involving multiple
183 * CPUs trying to garner first-use privileges.
184 */
185 static void check_init_srcu_struct(struct srcu_struct *sp)
186 {
187 unsigned long flags;
188
189 WARN_ON_ONCE(rcu_scheduler_active == RCU_SCHEDULER_INIT);
190 /* The smp_load_acquire() pairs with the smp_store_release(). */
191 if (!rcu_seq_state(smp_load_acquire(&sp->srcu_gp_seq_needed))) /*^^^*/
192 return; /* Already initialized. */
193 spin_lock_irqsave(&sp->gp_lock, flags);
194 if (!rcu_seq_state(sp->srcu_gp_seq_needed)) {
195 spin_unlock_irqrestore(&sp->gp_lock, flags);
196 return;
197 }
198 init_srcu_struct_fields(sp, true);
199 spin_unlock_irqrestore(&sp->gp_lock, flags);
200 }
201
202 /*
203 * Returns approximate total of the readers' ->srcu_lock_count[] values
204 * for the rank of per-CPU counters specified by idx.
205 */
206 static unsigned long srcu_readers_lock_idx(struct srcu_struct *sp, int idx)
207 {
208 int cpu;
209 unsigned long sum = 0;
210
211 for_each_possible_cpu(cpu) {
212 struct srcu_data *cpuc = per_cpu_ptr(sp->sda, cpu);
213
214 sum += READ_ONCE(cpuc->srcu_lock_count[idx]);
215 }
216 return sum;
217 }
218
219 /*
220 * Returns approximate total of the readers' ->srcu_unlock_count[] values
221 * for the rank of per-CPU counters specified by idx.
222 */
223 static unsigned long srcu_readers_unlock_idx(struct srcu_struct *sp, int idx)
224 {
225 int cpu;
226 unsigned long sum = 0;
227
228 for_each_possible_cpu(cpu) {
229 struct srcu_data *cpuc = per_cpu_ptr(sp->sda, cpu);
230
231 sum += READ_ONCE(cpuc->srcu_unlock_count[idx]);
232 }
233 return sum;
234 }
235
236 /*
237 * Return true if the number of pre-existing readers is determined to
238 * be zero.
239 */
240 static bool srcu_readers_active_idx_check(struct srcu_struct *sp, int idx)
241 {
242 unsigned long unlocks;
243
244 unlocks = srcu_readers_unlock_idx(sp, idx);
245
246 /*
247 * Make sure that a lock is always counted if the corresponding
248 * unlock is counted. Needs to be a smp_mb() as the read side may
249 * contain a read from a variable that is written to before the
250 * synchronize_srcu() in the write side. In this case smp_mb()s
251 * A and B act like the store buffering pattern.
252 *
253 * This smp_mb() also pairs with smp_mb() C to prevent accesses
254 * after the synchronize_srcu() from being executed before the
255 * grace period ends.
256 */
257 smp_mb(); /* A */
258
259 /*
260 * If the locks are the same as the unlocks, then there must have
261 * been no readers on this index at some time in between. This does
262 * not mean that there are no more readers, as one could have read
263 * the current index but not have incremented the lock counter yet.
264 *
265 * Possible bug: There is no guarantee that there haven't been
266 * ULONG_MAX increments of ->srcu_lock_count[] since the unlocks were
267 * counted, meaning that this could return true even if there are
268 * still active readers. Since there are no memory barriers around
269 * srcu_flip(), the CPU is not required to increment ->srcu_idx
270 * before running srcu_readers_unlock_idx(), which means that there
271 * could be an arbitrarily large number of critical sections that
272 * execute after srcu_readers_unlock_idx() but use the old value
273 * of ->srcu_idx.
274 */
275 return srcu_readers_lock_idx(sp, idx) == unlocks;
276 }
277
278 /**
279 * srcu_readers_active - returns true if there are readers. and false
280 * otherwise
281 * @sp: which srcu_struct to count active readers (holding srcu_read_lock).
282 *
283 * Note that this is not an atomic primitive, and can therefore suffer
284 * severe errors when invoked on an active srcu_struct. That said, it
285 * can be useful as an error check at cleanup time.
286 */
287 static bool srcu_readers_active(struct srcu_struct *sp)
288 {
289 int cpu;
290 unsigned long sum = 0;
291
292 for_each_possible_cpu(cpu) {
293 struct srcu_data *cpuc = per_cpu_ptr(sp->sda, cpu);
294
295 sum += READ_ONCE(cpuc->srcu_lock_count[0]);
296 sum += READ_ONCE(cpuc->srcu_lock_count[1]);
297 sum -= READ_ONCE(cpuc->srcu_unlock_count[0]);
298 sum -= READ_ONCE(cpuc->srcu_unlock_count[1]);
299 }
300 return sum;
301 }
302
303 #define SRCU_INTERVAL 1
304
305 /**
306 * cleanup_srcu_struct - deconstruct a sleep-RCU structure
307 * @sp: structure to clean up.
308 *
309 * Must invoke this after you are finished using a given srcu_struct that
310 * was initialized via init_srcu_struct(), else you leak memory.
311 */
312 void cleanup_srcu_struct(struct srcu_struct *sp)
313 {
314 int cpu;
315
316 WARN_ON_ONCE(atomic_read(&sp->srcu_exp_cnt));
317 if (WARN_ON(srcu_readers_active(sp)))
318 return; /* Leakage unless caller handles error. */
319 flush_delayed_work(&sp->work);
320 for_each_possible_cpu(cpu)
321 flush_delayed_work(&per_cpu_ptr(sp->sda, cpu)->work);
322 if (WARN_ON(rcu_seq_state(READ_ONCE(sp->srcu_gp_seq)) != SRCU_STATE_IDLE) ||
323 WARN_ON(srcu_readers_active(sp))) {
324 pr_info("cleanup_srcu_struct: Active srcu_struct %p state: %d\n", sp, rcu_seq_state(READ_ONCE(sp->srcu_gp_seq)));
325 return; /* Caller forgot to stop doing call_srcu()? */
326 }
327 free_percpu(sp->sda);
328 sp->sda = NULL;
329 }
330 EXPORT_SYMBOL_GPL(cleanup_srcu_struct);
331
332 /*
333 * Counts the new reader in the appropriate per-CPU element of the
334 * srcu_struct. Must be called from process context.
335 * Returns an index that must be passed to the matching srcu_read_unlock().
336 */
337 int __srcu_read_lock(struct srcu_struct *sp)
338 {
339 int idx;
340
341 idx = READ_ONCE(sp->srcu_idx) & 0x1;
342 __this_cpu_inc(sp->sda->srcu_lock_count[idx]);
343 smp_mb(); /* B */ /* Avoid leaking the critical section. */
344 return idx;
345 }
346 EXPORT_SYMBOL_GPL(__srcu_read_lock);
347
348 /*
349 * Removes the count for the old reader from the appropriate per-CPU
350 * element of the srcu_struct. Note that this may well be a different
351 * CPU than that which was incremented by the corresponding srcu_read_lock().
352 * Must be called from process context.
353 */
354 void __srcu_read_unlock(struct srcu_struct *sp, int idx)
355 {
356 smp_mb(); /* C */ /* Avoid leaking the critical section. */
357 this_cpu_inc(sp->sda->srcu_unlock_count[idx]);
358 }
359 EXPORT_SYMBOL_GPL(__srcu_read_unlock);
360
361 /*
362 * We use an adaptive strategy for synchronize_srcu() and especially for
363 * synchronize_srcu_expedited(). We spin for a fixed time period
364 * (defined below) to allow SRCU readers to exit their read-side critical
365 * sections. If there are still some readers after a few microseconds,
366 * we repeatedly block for 1-millisecond time periods.
367 */
368 #define SRCU_RETRY_CHECK_DELAY 5
369
370 /*
371 * Start an SRCU grace period.
372 */
373 static void srcu_gp_start(struct srcu_struct *sp)
374 {
375 struct srcu_data *sdp = this_cpu_ptr(sp->sda);
376 int state;
377
378 RCU_LOCKDEP_WARN(!lockdep_is_held(&sp->gp_lock),
379 "Invoked srcu_gp_start() without ->gp_lock!");
380 WARN_ON_ONCE(ULONG_CMP_GE(sp->srcu_gp_seq, sp->srcu_gp_seq_needed));
381 rcu_segcblist_advance(&sdp->srcu_cblist,
382 rcu_seq_current(&sp->srcu_gp_seq));
383 (void)rcu_segcblist_accelerate(&sdp->srcu_cblist,
384 rcu_seq_snap(&sp->srcu_gp_seq));
385 rcu_seq_start(&sp->srcu_gp_seq);
386 state = rcu_seq_state(READ_ONCE(sp->srcu_gp_seq));
387 WARN_ON_ONCE(state != SRCU_STATE_SCAN1);
388 }
389
390 /*
391 * Track online CPUs to guide callback workqueue placement.
392 */
393 DEFINE_PER_CPU(bool, srcu_online);
394
395 void srcu_online_cpu(unsigned int cpu)
396 {
397 WRITE_ONCE(per_cpu(srcu_online, cpu), true);
398 }
399
400 void srcu_offline_cpu(unsigned int cpu)
401 {
402 WRITE_ONCE(per_cpu(srcu_online, cpu), false);
403 }
404
405 /*
406 * Place the workqueue handler on the specified CPU if online, otherwise
407 * just run it whereever. This is useful for placing workqueue handlers
408 * that are to invoke the specified CPU's callbacks.
409 */
410 static bool srcu_queue_delayed_work_on(int cpu, struct workqueue_struct *wq,
411 struct delayed_work *dwork,
412 unsigned long delay)
413 {
414 bool ret;
415
416 preempt_disable();
417 if (READ_ONCE(per_cpu(srcu_online, cpu)))
418 ret = queue_delayed_work_on(cpu, wq, dwork, delay);
419 else
420 ret = queue_delayed_work(wq, dwork, delay);
421 preempt_enable();
422 return ret;
423 }
424
425 /*
426 * Schedule callback invocation for the specified srcu_data structure,
427 * if possible, on the corresponding CPU.
428 */
429 static void srcu_schedule_cbs_sdp(struct srcu_data *sdp, unsigned long delay)
430 {
431 srcu_queue_delayed_work_on(sdp->cpu, system_power_efficient_wq,
432 &sdp->work, delay);
433 }
434
435 /*
436 * Schedule callback invocation for all srcu_data structures associated
437 * with the specified srcu_node structure, if possible, on the corresponding
438 * CPUs.
439 */
440 static void srcu_schedule_cbs_snp(struct srcu_struct *sp, struct srcu_node *snp)
441 {
442 int cpu;
443
444 for (cpu = snp->grplo; cpu <= snp->grphi; cpu++)
445 srcu_schedule_cbs_sdp(per_cpu_ptr(sp->sda, cpu),
446 atomic_read(&sp->srcu_exp_cnt) ? 0 : SRCU_INTERVAL);
447 }
448
449 /*
450 * Note the end of an SRCU grace period. Initiates callback invocation
451 * and starts a new grace period if needed.
452 *
453 * The ->srcu_cb_mutex acquisition does not protect any data, but
454 * instead prevents more than one grace period from starting while we
455 * are initiating callback invocation. This allows the ->srcu_have_cbs[]
456 * array to have a finite number of elements.
457 */
458 static void srcu_gp_end(struct srcu_struct *sp)
459 {
460 bool cbs;
461 unsigned long gpseq;
462 int idx;
463 int idxnext;
464 struct srcu_node *snp;
465
466 /* Prevent more than one additional grace period. */
467 mutex_lock(&sp->srcu_cb_mutex);
468
469 /* End the current grace period. */
470 spin_lock_irq(&sp->gp_lock);
471 idx = rcu_seq_state(sp->srcu_gp_seq);
472 WARN_ON_ONCE(idx != SRCU_STATE_SCAN2);
473 rcu_seq_end(&sp->srcu_gp_seq);
474 gpseq = rcu_seq_current(&sp->srcu_gp_seq);
475 spin_unlock_irq(&sp->gp_lock);
476 mutex_unlock(&sp->srcu_gp_mutex);
477 /* A new grace period can start at this point. But only one. */
478
479 /* Initiate callback invocation as needed. */
480 idx = rcu_seq_ctr(gpseq) % ARRAY_SIZE(snp->srcu_have_cbs);
481 idxnext = (idx + 1) % ARRAY_SIZE(snp->srcu_have_cbs);
482 rcu_for_each_node_breadth_first(sp, snp) {
483 spin_lock_irq(&snp->lock);
484 cbs = false;
485 if (snp >= sp->level[rcu_num_lvls - 1])
486 cbs = snp->srcu_have_cbs[idx] == gpseq;
487 snp->srcu_have_cbs[idx] = gpseq;
488 rcu_seq_set_state(&snp->srcu_have_cbs[idx], 1);
489 spin_unlock_irq(&snp->lock);
490 if (cbs) {
491 smp_mb(); /* GP end before CB invocation. */
492 srcu_schedule_cbs_snp(sp, snp);
493 }
494 }
495
496 /* Callback initiation done, allow grace periods after next. */
497 mutex_unlock(&sp->srcu_cb_mutex);
498
499 /* Start a new grace period if needed. */
500 spin_lock_irq(&sp->gp_lock);
501 gpseq = rcu_seq_current(&sp->srcu_gp_seq);
502 if (!rcu_seq_state(gpseq) &&
503 ULONG_CMP_LT(gpseq, sp->srcu_gp_seq_needed)) {
504 srcu_gp_start(sp);
505 spin_unlock_irq(&sp->gp_lock);
506 /* Throttle expedited grace periods: Should be rare! */
507 srcu_reschedule(sp, atomic_read(&sp->srcu_exp_cnt) &&
508 rcu_seq_ctr(gpseq) & 0xf
509 ? 0
510 : SRCU_INTERVAL);
511 } else {
512 spin_unlock_irq(&sp->gp_lock);
513 }
514 }
515
516 /*
517 * Funnel-locking scheme to scalably mediate many concurrent grace-period
518 * requests. The winner has to do the work of actually starting grace
519 * period s. Losers must either ensure that their desired grace-period
520 * number is recorded on at least their leaf srcu_node structure, or they
521 * must take steps to invoke their own callbacks.
522 */
523 static void srcu_funnel_gp_start(struct srcu_struct *sp,
524 struct srcu_data *sdp,
525 unsigned long s)
526 {
527 unsigned long flags;
528 int idx = rcu_seq_ctr(s) % ARRAY_SIZE(sdp->mynode->srcu_have_cbs);
529 struct srcu_node *snp = sdp->mynode;
530 unsigned long snp_seq;
531
532 /* Each pass through the loop does one level of the srcu_node tree. */
533 for (; snp != NULL; snp = snp->srcu_parent) {
534 if (rcu_seq_done(&sp->srcu_gp_seq, s) && snp != sdp->mynode)
535 return; /* GP already done and CBs recorded. */
536 spin_lock_irqsave(&snp->lock, flags);
537 if (ULONG_CMP_GE(snp->srcu_have_cbs[idx], s)) {
538 snp_seq = snp->srcu_have_cbs[idx];
539 spin_unlock_irqrestore(&snp->lock, flags);
540 if (snp == sdp->mynode && snp_seq != s) {
541 smp_mb(); /* CBs after GP! */
542 srcu_schedule_cbs_sdp(sdp, 0);
543 }
544 return;
545 }
546 snp->srcu_have_cbs[idx] = s;
547 spin_unlock_irqrestore(&snp->lock, flags);
548 }
549
550 /* Top of tree, must ensure the grace period will be started. */
551 spin_lock_irqsave(&sp->gp_lock, flags);
552 if (ULONG_CMP_LT(sp->srcu_gp_seq_needed, s)) {
553 /*
554 * Record need for grace period s. Pair with load
555 * acquire setting up for initialization.
556 */
557 smp_store_release(&sp->srcu_gp_seq_needed, s); /*^^^*/
558 }
559
560 /* If grace period not already done and none in progress, start it. */
561 if (!rcu_seq_done(&sp->srcu_gp_seq, s) &&
562 rcu_seq_state(sp->srcu_gp_seq) == SRCU_STATE_IDLE) {
563 WARN_ON_ONCE(ULONG_CMP_GE(sp->srcu_gp_seq, sp->srcu_gp_seq_needed));
564 srcu_gp_start(sp);
565 queue_delayed_work(system_power_efficient_wq, &sp->work,
566 atomic_read(&sp->srcu_exp_cnt)
567 ? 0
568 : SRCU_INTERVAL);
569 }
570 spin_unlock_irqrestore(&sp->gp_lock, flags);
571 }
572
573 /*
574 * Wait until all readers counted by array index idx complete, but
575 * loop an additional time if there is an expedited grace period pending.
576 * The caller must ensure that ->srcu_idx is not changed while checking.
577 */
578 static bool try_check_zero(struct srcu_struct *sp, int idx, int trycount)
579 {
580 for (;;) {
581 if (srcu_readers_active_idx_check(sp, idx))
582 return true;
583 if (--trycount + !!atomic_read(&sp->srcu_exp_cnt) <= 0)
584 return false;
585 udelay(SRCU_RETRY_CHECK_DELAY);
586 }
587 }
588
589 /*
590 * Increment the ->srcu_idx counter so that future SRCU readers will
591 * use the other rank of the ->srcu_(un)lock_count[] arrays. This allows
592 * us to wait for pre-existing readers in a starvation-free manner.
593 */
594 static void srcu_flip(struct srcu_struct *sp)
595 {
596 WRITE_ONCE(sp->srcu_idx, sp->srcu_idx + 1);
597
598 /*
599 * Ensure that if the updater misses an __srcu_read_unlock()
600 * increment, that task's next __srcu_read_lock() will see the
601 * above counter update. Note that both this memory barrier
602 * and the one in srcu_readers_active_idx_check() provide the
603 * guarantee for __srcu_read_lock().
604 */
605 smp_mb(); /* D */ /* Pairs with C. */
606 }
607
608 /*
609 * Enqueue an SRCU callback on the srcu_data structure associated with
610 * the current CPU and the specified srcu_struct structure, initiating
611 * grace-period processing if it is not already running.
612 *
613 * Note that all CPUs must agree that the grace period extended beyond
614 * all pre-existing SRCU read-side critical section. On systems with
615 * more than one CPU, this means that when "func()" is invoked, each CPU
616 * is guaranteed to have executed a full memory barrier since the end of
617 * its last corresponding SRCU read-side critical section whose beginning
618 * preceded the call to call_rcu(). It also means that each CPU executing
619 * an SRCU read-side critical section that continues beyond the start of
620 * "func()" must have executed a memory barrier after the call_rcu()
621 * but before the beginning of that SRCU read-side critical section.
622 * Note that these guarantees include CPUs that are offline, idle, or
623 * executing in user mode, as well as CPUs that are executing in the kernel.
624 *
625 * Furthermore, if CPU A invoked call_rcu() and CPU B invoked the
626 * resulting SRCU callback function "func()", then both CPU A and CPU
627 * B are guaranteed to execute a full memory barrier during the time
628 * interval between the call to call_rcu() and the invocation of "func()".
629 * This guarantee applies even if CPU A and CPU B are the same CPU (but
630 * again only if the system has more than one CPU).
631 *
632 * Of course, these guarantees apply only for invocations of call_srcu(),
633 * srcu_read_lock(), and srcu_read_unlock() that are all passed the same
634 * srcu_struct structure.
635 */
636 void call_srcu(struct srcu_struct *sp, struct rcu_head *rhp,
637 rcu_callback_t func)
638 {
639 unsigned long flags;
640 bool needgp = false;
641 unsigned long s;
642 struct srcu_data *sdp;
643
644 check_init_srcu_struct(sp);
645 rhp->func = func;
646 local_irq_save(flags);
647 sdp = this_cpu_ptr(sp->sda);
648 spin_lock(&sdp->lock);
649 rcu_segcblist_enqueue(&sdp->srcu_cblist, rhp, false);
650 rcu_segcblist_advance(&sdp->srcu_cblist,
651 rcu_seq_current(&sp->srcu_gp_seq));
652 s = rcu_seq_snap(&sp->srcu_gp_seq);
653 (void)rcu_segcblist_accelerate(&sdp->srcu_cblist, s);
654 if (ULONG_CMP_LT(sdp->srcu_gp_seq_needed, s)) {
655 sdp->srcu_gp_seq_needed = s;
656 needgp = true;
657 }
658 spin_unlock_irqrestore(&sdp->lock, flags);
659 if (needgp)
660 srcu_funnel_gp_start(sp, sdp, s);
661 }
662 EXPORT_SYMBOL_GPL(call_srcu);
663
664 /*
665 * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
666 */
667 static void __synchronize_srcu(struct srcu_struct *sp)
668 {
669 struct rcu_synchronize rcu;
670
671 RCU_LOCKDEP_WARN(lock_is_held(&sp->dep_map) ||
672 lock_is_held(&rcu_bh_lock_map) ||
673 lock_is_held(&rcu_lock_map) ||
674 lock_is_held(&rcu_sched_lock_map),
675 "Illegal synchronize_srcu() in same-type SRCU (or in RCU) read-side critical section");
676
677 if (rcu_scheduler_active == RCU_SCHEDULER_INACTIVE)
678 return;
679 might_sleep();
680 check_init_srcu_struct(sp);
681 init_completion(&rcu.completion);
682 init_rcu_head_on_stack(&rcu.head);
683 call_srcu(sp, &rcu.head, wakeme_after_rcu);
684 wait_for_completion(&rcu.completion);
685 destroy_rcu_head_on_stack(&rcu.head);
686 }
687
688 /**
689 * synchronize_srcu_expedited - Brute-force SRCU grace period
690 * @sp: srcu_struct with which to synchronize.
691 *
692 * Wait for an SRCU grace period to elapse, but be more aggressive about
693 * spinning rather than blocking when waiting.
694 *
695 * Note that synchronize_srcu_expedited() has the same deadlock and
696 * memory-ordering properties as does synchronize_srcu().
697 */
698 void synchronize_srcu_expedited(struct srcu_struct *sp)
699 {
700 bool do_norm = rcu_gp_is_normal();
701
702 check_init_srcu_struct(sp);
703 if (!do_norm) {
704 atomic_inc(&sp->srcu_exp_cnt);
705 smp_mb__after_atomic(); /* increment before GP. */
706 }
707 __synchronize_srcu(sp);
708 if (!do_norm) {
709 smp_mb__before_atomic(); /* GP before decrement. */
710 WARN_ON_ONCE(atomic_dec_return(&sp->srcu_exp_cnt) < 0);
711 }
712 }
713 EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
714
715 /**
716 * synchronize_srcu - wait for prior SRCU read-side critical-section completion
717 * @sp: srcu_struct with which to synchronize.
718 *
719 * Wait for the count to drain to zero of both indexes. To avoid the
720 * possible starvation of synchronize_srcu(), it waits for the count of
721 * the index=((->srcu_idx & 1) ^ 1) to drain to zero at first,
722 * and then flip the srcu_idx and wait for the count of the other index.
723 *
724 * Can block; must be called from process context.
725 *
726 * Note that it is illegal to call synchronize_srcu() from the corresponding
727 * SRCU read-side critical section; doing so will result in deadlock.
728 * However, it is perfectly legal to call synchronize_srcu() on one
729 * srcu_struct from some other srcu_struct's read-side critical section,
730 * as long as the resulting graph of srcu_structs is acyclic.
731 *
732 * There are memory-ordering constraints implied by synchronize_srcu().
733 * On systems with more than one CPU, when synchronize_srcu() returns,
734 * each CPU is guaranteed to have executed a full memory barrier since
735 * the end of its last corresponding SRCU-sched read-side critical section
736 * whose beginning preceded the call to synchronize_srcu(). In addition,
737 * each CPU having an SRCU read-side critical section that extends beyond
738 * the return from synchronize_srcu() is guaranteed to have executed a
739 * full memory barrier after the beginning of synchronize_srcu() and before
740 * the beginning of that SRCU read-side critical section. Note that these
741 * guarantees include CPUs that are offline, idle, or executing in user mode,
742 * as well as CPUs that are executing in the kernel.
743 *
744 * Furthermore, if CPU A invoked synchronize_srcu(), which returned
745 * to its caller on CPU B, then both CPU A and CPU B are guaranteed
746 * to have executed a full memory barrier during the execution of
747 * synchronize_srcu(). This guarantee applies even if CPU A and CPU B
748 * are the same CPU, but again only if the system has more than one CPU.
749 *
750 * Of course, these memory-ordering guarantees apply only when
751 * synchronize_srcu(), srcu_read_lock(), and srcu_read_unlock() are
752 * passed the same srcu_struct structure.
753 */
754 void synchronize_srcu(struct srcu_struct *sp)
755 {
756 if (rcu_gp_is_expedited())
757 synchronize_srcu_expedited(sp);
758 else
759 __synchronize_srcu(sp);
760 }
761 EXPORT_SYMBOL_GPL(synchronize_srcu);
762
763 /*
764 * Callback function for srcu_barrier() use.
765 */
766 static void srcu_barrier_cb(struct rcu_head *rhp)
767 {
768 struct srcu_data *sdp;
769 struct srcu_struct *sp;
770
771 sdp = container_of(rhp, struct srcu_data, srcu_barrier_head);
772 sp = sdp->sp;
773 if (atomic_dec_and_test(&sp->srcu_barrier_cpu_cnt))
774 complete(&sp->srcu_barrier_completion);
775 }
776
777 /**
778 * srcu_barrier - Wait until all in-flight call_srcu() callbacks complete.
779 * @sp: srcu_struct on which to wait for in-flight callbacks.
780 */
781 void srcu_barrier(struct srcu_struct *sp)
782 {
783 int cpu;
784 struct srcu_data *sdp;
785 unsigned long s = rcu_seq_snap(&sp->srcu_barrier_seq);
786
787 check_init_srcu_struct(sp);
788 mutex_lock(&sp->srcu_barrier_mutex);
789 if (rcu_seq_done(&sp->srcu_barrier_seq, s)) {
790 smp_mb(); /* Force ordering following return. */
791 mutex_unlock(&sp->srcu_barrier_mutex);
792 return; /* Someone else did our work for us. */
793 }
794 rcu_seq_start(&sp->srcu_barrier_seq);
795 init_completion(&sp->srcu_barrier_completion);
796
797 /* Initial count prevents reaching zero until all CBs are posted. */
798 atomic_set(&sp->srcu_barrier_cpu_cnt, 1);
799
800 /*
801 * Each pass through this loop enqueues a callback, but only
802 * on CPUs already having callbacks enqueued. Note that if
803 * a CPU already has callbacks enqueue, it must have already
804 * registered the need for a future grace period, so all we
805 * need do is enqueue a callback that will use the same
806 * grace period as the last callback already in the queue.
807 */
808 for_each_possible_cpu(cpu) {
809 sdp = per_cpu_ptr(sp->sda, cpu);
810 spin_lock_irq(&sdp->lock);
811 atomic_inc(&sp->srcu_barrier_cpu_cnt);
812 sdp->srcu_barrier_head.func = srcu_barrier_cb;
813 if (!rcu_segcblist_entrain(&sdp->srcu_cblist,
814 &sdp->srcu_barrier_head, 0))
815 atomic_dec(&sp->srcu_barrier_cpu_cnt);
816 spin_unlock_irq(&sdp->lock);
817 }
818
819 /* Remove the initial count, at which point reaching zero can happen. */
820 if (atomic_dec_and_test(&sp->srcu_barrier_cpu_cnt))
821 complete(&sp->srcu_barrier_completion);
822 wait_for_completion(&sp->srcu_barrier_completion);
823
824 rcu_seq_end(&sp->srcu_barrier_seq);
825 mutex_unlock(&sp->srcu_barrier_mutex);
826 }
827 EXPORT_SYMBOL_GPL(srcu_barrier);
828
829 /**
830 * srcu_batches_completed - return batches completed.
831 * @sp: srcu_struct on which to report batch completion.
832 *
833 * Report the number of batches, correlated with, but not necessarily
834 * precisely the same as, the number of grace periods that have elapsed.
835 */
836 unsigned long srcu_batches_completed(struct srcu_struct *sp)
837 {
838 return sp->srcu_idx;
839 }
840 EXPORT_SYMBOL_GPL(srcu_batches_completed);
841
842 /*
843 * Core SRCU state machine. Push state bits of ->srcu_gp_seq
844 * to SRCU_STATE_SCAN2, and invoke srcu_gp_end() when scan has
845 * completed in that state.
846 */
847 static void srcu_advance_state(struct srcu_struct *sp)
848 {
849 int idx;
850
851 mutex_lock(&sp->srcu_gp_mutex);
852
853 /*
854 * Because readers might be delayed for an extended period after
855 * fetching ->srcu_idx for their index, at any point in time there
856 * might well be readers using both idx=0 and idx=1. We therefore
857 * need to wait for readers to clear from both index values before
858 * invoking a callback.
859 *
860 * The load-acquire ensures that we see the accesses performed
861 * by the prior grace period.
862 */
863 idx = rcu_seq_state(smp_load_acquire(&sp->srcu_gp_seq)); /* ^^^ */
864 if (idx == SRCU_STATE_IDLE) {
865 spin_lock_irq(&sp->gp_lock);
866 if (ULONG_CMP_GE(sp->srcu_gp_seq, sp->srcu_gp_seq_needed)) {
867 WARN_ON_ONCE(rcu_seq_state(sp->srcu_gp_seq));
868 spin_unlock_irq(&sp->gp_lock);
869 mutex_unlock(&sp->srcu_gp_mutex);
870 return;
871 }
872 idx = rcu_seq_state(READ_ONCE(sp->srcu_gp_seq));
873 if (idx == SRCU_STATE_IDLE)
874 srcu_gp_start(sp);
875 spin_unlock_irq(&sp->gp_lock);
876 if (idx != SRCU_STATE_IDLE) {
877 mutex_unlock(&sp->srcu_gp_mutex);
878 return; /* Someone else started the grace period. */
879 }
880 }
881
882 if (rcu_seq_state(READ_ONCE(sp->srcu_gp_seq)) == SRCU_STATE_SCAN1) {
883 idx = 1 ^ (sp->srcu_idx & 1);
884 if (!try_check_zero(sp, idx, 1)) {
885 mutex_unlock(&sp->srcu_gp_mutex);
886 return; /* readers present, retry later. */
887 }
888 srcu_flip(sp);
889 rcu_seq_set_state(&sp->srcu_gp_seq, SRCU_STATE_SCAN2);
890 }
891
892 if (rcu_seq_state(READ_ONCE(sp->srcu_gp_seq)) == SRCU_STATE_SCAN2) {
893
894 /*
895 * SRCU read-side critical sections are normally short,
896 * so check at least twice in quick succession after a flip.
897 */
898 idx = 1 ^ (sp->srcu_idx & 1);
899 if (!try_check_zero(sp, idx, 2)) {
900 mutex_unlock(&sp->srcu_gp_mutex);
901 return; /* readers present, retry later. */
902 }
903 srcu_gp_end(sp); /* Releases ->srcu_gp_mutex. */
904 }
905 }
906
907 /*
908 * Invoke a limited number of SRCU callbacks that have passed through
909 * their grace period. If there are more to do, SRCU will reschedule
910 * the workqueue. Note that needed memory barriers have been executed
911 * in this task's context by srcu_readers_active_idx_check().
912 */
913 static void srcu_invoke_callbacks(struct work_struct *work)
914 {
915 bool more;
916 struct rcu_cblist ready_cbs;
917 struct rcu_head *rhp;
918 struct srcu_data *sdp;
919 struct srcu_struct *sp;
920
921 sdp = container_of(work, struct srcu_data, work.work);
922 sp = sdp->sp;
923 rcu_cblist_init(&ready_cbs);
924 spin_lock_irq(&sdp->lock);
925 smp_mb(); /* Old grace periods before callback invocation! */
926 rcu_segcblist_advance(&sdp->srcu_cblist,
927 rcu_seq_current(&sp->srcu_gp_seq));
928 if (sdp->srcu_cblist_invoking ||
929 !rcu_segcblist_ready_cbs(&sdp->srcu_cblist)) {
930 spin_unlock_irq(&sdp->lock);
931 return; /* Someone else on the job or nothing to do. */
932 }
933
934 /* We are on the job! Extract and invoke ready callbacks. */
935 sdp->srcu_cblist_invoking = true;
936 rcu_segcblist_extract_done_cbs(&sdp->srcu_cblist, &ready_cbs);
937 spin_unlock_irq(&sdp->lock);
938 rhp = rcu_cblist_dequeue(&ready_cbs);
939 for (; rhp != NULL; rhp = rcu_cblist_dequeue(&ready_cbs)) {
940 local_bh_disable();
941 rhp->func(rhp);
942 local_bh_enable();
943 }
944
945 /*
946 * Update counts, accelerate new callbacks, and if needed,
947 * schedule another round of callback invocation.
948 */
949 spin_lock_irq(&sdp->lock);
950 rcu_segcblist_insert_count(&sdp->srcu_cblist, &ready_cbs);
951 (void)rcu_segcblist_accelerate(&sdp->srcu_cblist,
952 rcu_seq_snap(&sp->srcu_gp_seq));
953 sdp->srcu_cblist_invoking = false;
954 more = rcu_segcblist_ready_cbs(&sdp->srcu_cblist);
955 spin_unlock_irq(&sdp->lock);
956 if (more)
957 srcu_schedule_cbs_sdp(sdp, 0);
958 }
959
960 /*
961 * Finished one round of SRCU grace period. Start another if there are
962 * more SRCU callbacks queued, otherwise put SRCU into not-running state.
963 */
964 static void srcu_reschedule(struct srcu_struct *sp, unsigned long delay)
965 {
966 bool pushgp = true;
967
968 spin_lock_irq(&sp->gp_lock);
969 if (ULONG_CMP_GE(sp->srcu_gp_seq, sp->srcu_gp_seq_needed)) {
970 if (!WARN_ON_ONCE(rcu_seq_state(sp->srcu_gp_seq))) {
971 /* All requests fulfilled, time to go idle. */
972 pushgp = false;
973 }
974 } else if (!rcu_seq_state(sp->srcu_gp_seq)) {
975 /* Outstanding request and no GP. Start one. */
976 srcu_gp_start(sp);
977 }
978 spin_unlock_irq(&sp->gp_lock);
979
980 if (pushgp)
981 queue_delayed_work(system_power_efficient_wq, &sp->work, delay);
982 }
983
984 /*
985 * This is the work-queue function that handles SRCU grace periods.
986 */
987 void process_srcu(struct work_struct *work)
988 {
989 struct srcu_struct *sp;
990
991 sp = container_of(work, struct srcu_struct, work.work);
992
993 srcu_advance_state(sp);
994 srcu_reschedule(sp, atomic_read(&sp->srcu_exp_cnt) ? 0 : SRCU_INTERVAL);
995 }
996 EXPORT_SYMBOL_GPL(process_srcu);