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