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