]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - kernel/rcu/tree.c
rcu: Better hotplug handling for synchronize_sched_expedited()
[karo-tx-linux.git] / kernel / rcu / tree.c
1 /*
2  * 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 IBM Corporation, 2008
19  *
20  * Authors: Dipankar Sarma <dipankar@in.ibm.com>
21  *          Manfred Spraul <manfred@colorfullife.com>
22  *          Paul E. McKenney <paulmck@linux.vnet.ibm.com> Hierarchical version
23  *
24  * Based on the original work by Paul McKenney <paulmck@us.ibm.com>
25  * and inputs from Rusty Russell, Andrea Arcangeli and Andi Kleen.
26  *
27  * For detailed explanation of Read-Copy Update mechanism see -
28  *      Documentation/RCU
29  */
30 #include <linux/types.h>
31 #include <linux/kernel.h>
32 #include <linux/init.h>
33 #include <linux/spinlock.h>
34 #include <linux/smp.h>
35 #include <linux/rcupdate.h>
36 #include <linux/interrupt.h>
37 #include <linux/sched.h>
38 #include <linux/nmi.h>
39 #include <linux/atomic.h>
40 #include <linux/bitops.h>
41 #include <linux/export.h>
42 #include <linux/completion.h>
43 #include <linux/moduleparam.h>
44 #include <linux/module.h>
45 #include <linux/percpu.h>
46 #include <linux/notifier.h>
47 #include <linux/cpu.h>
48 #include <linux/mutex.h>
49 #include <linux/time.h>
50 #include <linux/kernel_stat.h>
51 #include <linux/wait.h>
52 #include <linux/kthread.h>
53 #include <linux/prefetch.h>
54 #include <linux/delay.h>
55 #include <linux/stop_machine.h>
56 #include <linux/random.h>
57 #include <linux/trace_events.h>
58 #include <linux/suspend.h>
59
60 #include "tree.h"
61 #include "rcu.h"
62
63 MODULE_ALIAS("rcutree");
64 #ifdef MODULE_PARAM_PREFIX
65 #undef MODULE_PARAM_PREFIX
66 #endif
67 #define MODULE_PARAM_PREFIX "rcutree."
68
69 /* Data structures. */
70
71 static struct lock_class_key rcu_node_class[RCU_NUM_LVLS];
72 static struct lock_class_key rcu_fqs_class[RCU_NUM_LVLS];
73 static struct lock_class_key rcu_exp_class[RCU_NUM_LVLS];
74
75 /*
76  * In order to export the rcu_state name to the tracing tools, it
77  * needs to be added in the __tracepoint_string section.
78  * This requires defining a separate variable tp_<sname>_varname
79  * that points to the string being used, and this will allow
80  * the tracing userspace tools to be able to decipher the string
81  * address to the matching string.
82  */
83 #ifdef CONFIG_TRACING
84 # define DEFINE_RCU_TPS(sname) \
85 static char sname##_varname[] = #sname; \
86 static const char *tp_##sname##_varname __used __tracepoint_string = sname##_varname;
87 # define RCU_STATE_NAME(sname) sname##_varname
88 #else
89 # define DEFINE_RCU_TPS(sname)
90 # define RCU_STATE_NAME(sname) __stringify(sname)
91 #endif
92
93 #define RCU_STATE_INITIALIZER(sname, sabbr, cr) \
94 DEFINE_RCU_TPS(sname) \
95 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rcu_data, sname##_data); \
96 struct rcu_state sname##_state = { \
97         .level = { &sname##_state.node[0] }, \
98         .rda = &sname##_data, \
99         .call = cr, \
100         .fqs_state = RCU_GP_IDLE, \
101         .gpnum = 0UL - 300UL, \
102         .completed = 0UL - 300UL, \
103         .orphan_lock = __RAW_SPIN_LOCK_UNLOCKED(&sname##_state.orphan_lock), \
104         .orphan_nxttail = &sname##_state.orphan_nxtlist, \
105         .orphan_donetail = &sname##_state.orphan_donelist, \
106         .barrier_mutex = __MUTEX_INITIALIZER(sname##_state.barrier_mutex), \
107         .name = RCU_STATE_NAME(sname), \
108         .abbr = sabbr, \
109 }
110
111 RCU_STATE_INITIALIZER(rcu_sched, 's', call_rcu_sched);
112 RCU_STATE_INITIALIZER(rcu_bh, 'b', call_rcu_bh);
113
114 static struct rcu_state *const rcu_state_p;
115 static struct rcu_data __percpu *const rcu_data_p;
116 LIST_HEAD(rcu_struct_flavors);
117
118 /* Dump rcu_node combining tree at boot to verify correct setup. */
119 static bool dump_tree;
120 module_param(dump_tree, bool, 0444);
121 /* Control rcu_node-tree auto-balancing at boot time. */
122 static bool rcu_fanout_exact;
123 module_param(rcu_fanout_exact, bool, 0444);
124 /* Increase (but not decrease) the RCU_FANOUT_LEAF at boot time. */
125 static int rcu_fanout_leaf = RCU_FANOUT_LEAF;
126 module_param(rcu_fanout_leaf, int, 0444);
127 int rcu_num_lvls __read_mostly = RCU_NUM_LVLS;
128 /* Number of rcu_nodes at specified level. */
129 static int num_rcu_lvl[] = NUM_RCU_LVL_INIT;
130 int rcu_num_nodes __read_mostly = NUM_RCU_NODES; /* Total # rcu_nodes in use. */
131
132 /*
133  * The rcu_scheduler_active variable transitions from zero to one just
134  * before the first task is spawned.  So when this variable is zero, RCU
135  * can assume that there is but one task, allowing RCU to (for example)
136  * optimize synchronize_sched() to a simple barrier().  When this variable
137  * is one, RCU must actually do all the hard work required to detect real
138  * grace periods.  This variable is also used to suppress boot-time false
139  * positives from lockdep-RCU error checking.
140  */
141 int rcu_scheduler_active __read_mostly;
142 EXPORT_SYMBOL_GPL(rcu_scheduler_active);
143
144 /*
145  * The rcu_scheduler_fully_active variable transitions from zero to one
146  * during the early_initcall() processing, which is after the scheduler
147  * is capable of creating new tasks.  So RCU processing (for example,
148  * creating tasks for RCU priority boosting) must be delayed until after
149  * rcu_scheduler_fully_active transitions from zero to one.  We also
150  * currently delay invocation of any RCU callbacks until after this point.
151  *
152  * It might later prove better for people registering RCU callbacks during
153  * early boot to take responsibility for these callbacks, but one step at
154  * a time.
155  */
156 static int rcu_scheduler_fully_active __read_mostly;
157
158 static void rcu_init_new_rnp(struct rcu_node *rnp_leaf);
159 static void rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf);
160 static void rcu_boost_kthread_setaffinity(struct rcu_node *rnp, int outgoingcpu);
161 static void invoke_rcu_core(void);
162 static void invoke_rcu_callbacks(struct rcu_state *rsp, struct rcu_data *rdp);
163 static void rcu_report_exp_rdp(struct rcu_state *rsp,
164                                struct rcu_data *rdp, bool wake);
165
166 /* rcuc/rcub kthread realtime priority */
167 #ifdef CONFIG_RCU_KTHREAD_PRIO
168 static int kthread_prio = CONFIG_RCU_KTHREAD_PRIO;
169 #else /* #ifdef CONFIG_RCU_KTHREAD_PRIO */
170 static int kthread_prio = IS_ENABLED(CONFIG_RCU_BOOST) ? 1 : 0;
171 #endif /* #else #ifdef CONFIG_RCU_KTHREAD_PRIO */
172 module_param(kthread_prio, int, 0644);
173
174 /* Delay in jiffies for grace-period initialization delays, debug only. */
175
176 #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_PREINIT
177 static int gp_preinit_delay = CONFIG_RCU_TORTURE_TEST_SLOW_PREINIT_DELAY;
178 module_param(gp_preinit_delay, int, 0644);
179 #else /* #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_PREINIT */
180 static const int gp_preinit_delay;
181 #endif /* #else #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_PREINIT */
182
183 #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_INIT
184 static int gp_init_delay = CONFIG_RCU_TORTURE_TEST_SLOW_INIT_DELAY;
185 module_param(gp_init_delay, int, 0644);
186 #else /* #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_INIT */
187 static const int gp_init_delay;
188 #endif /* #else #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_INIT */
189
190 #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_CLEANUP
191 static int gp_cleanup_delay = CONFIG_RCU_TORTURE_TEST_SLOW_CLEANUP_DELAY;
192 module_param(gp_cleanup_delay, int, 0644);
193 #else /* #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_CLEANUP */
194 static const int gp_cleanup_delay;
195 #endif /* #else #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_CLEANUP */
196
197 /*
198  * Number of grace periods between delays, normalized by the duration of
199  * the delay.  The longer the the delay, the more the grace periods between
200  * each delay.  The reason for this normalization is that it means that,
201  * for non-zero delays, the overall slowdown of grace periods is constant
202  * regardless of the duration of the delay.  This arrangement balances
203  * the need for long delays to increase some race probabilities with the
204  * need for fast grace periods to increase other race probabilities.
205  */
206 #define PER_RCU_NODE_PERIOD 3   /* Number of grace periods between delays. */
207
208 /*
209  * Track the rcutorture test sequence number and the update version
210  * number within a given test.  The rcutorture_testseq is incremented
211  * on every rcutorture module load and unload, so has an odd value
212  * when a test is running.  The rcutorture_vernum is set to zero
213  * when rcutorture starts and is incremented on each rcutorture update.
214  * These variables enable correlating rcutorture output with the
215  * RCU tracing information.
216  */
217 unsigned long rcutorture_testseq;
218 unsigned long rcutorture_vernum;
219
220 /*
221  * Compute the mask of online CPUs for the specified rcu_node structure.
222  * This will not be stable unless the rcu_node structure's ->lock is
223  * held, but the bit corresponding to the current CPU will be stable
224  * in most contexts.
225  */
226 unsigned long rcu_rnp_online_cpus(struct rcu_node *rnp)
227 {
228         return READ_ONCE(rnp->qsmaskinitnext);
229 }
230
231 /*
232  * Return true if an RCU grace period is in progress.  The READ_ONCE()s
233  * permit this function to be invoked without holding the root rcu_node
234  * structure's ->lock, but of course results can be subject to change.
235  */
236 static int rcu_gp_in_progress(struct rcu_state *rsp)
237 {
238         return READ_ONCE(rsp->completed) != READ_ONCE(rsp->gpnum);
239 }
240
241 /*
242  * Note a quiescent state.  Because we do not need to know
243  * how many quiescent states passed, just if there was at least
244  * one since the start of the grace period, this just sets a flag.
245  * The caller must have disabled preemption.
246  */
247 void rcu_sched_qs(void)
248 {
249         unsigned long flags;
250
251         if (__this_cpu_read(rcu_sched_data.cpu_no_qs.s)) {
252                 trace_rcu_grace_period(TPS("rcu_sched"),
253                                        __this_cpu_read(rcu_sched_data.gpnum),
254                                        TPS("cpuqs"));
255                 __this_cpu_write(rcu_sched_data.cpu_no_qs.b.norm, false);
256                 if (!__this_cpu_read(rcu_sched_data.cpu_no_qs.b.exp))
257                         return;
258                 local_irq_save(flags);
259                 if (__this_cpu_read(rcu_sched_data.cpu_no_qs.b.exp)) {
260                         __this_cpu_write(rcu_sched_data.cpu_no_qs.b.exp, false);
261                         rcu_report_exp_rdp(&rcu_sched_state,
262                                            this_cpu_ptr(&rcu_sched_data),
263                                            true);
264                 }
265                 local_irq_restore(flags);
266         }
267 }
268
269 void rcu_bh_qs(void)
270 {
271         if (__this_cpu_read(rcu_bh_data.cpu_no_qs.s)) {
272                 trace_rcu_grace_period(TPS("rcu_bh"),
273                                        __this_cpu_read(rcu_bh_data.gpnum),
274                                        TPS("cpuqs"));
275                 __this_cpu_write(rcu_bh_data.cpu_no_qs.b.norm, false);
276         }
277 }
278
279 static DEFINE_PER_CPU(int, rcu_sched_qs_mask);
280
281 static DEFINE_PER_CPU(struct rcu_dynticks, rcu_dynticks) = {
282         .dynticks_nesting = DYNTICK_TASK_EXIT_IDLE,
283         .dynticks = ATOMIC_INIT(1),
284 #ifdef CONFIG_NO_HZ_FULL_SYSIDLE
285         .dynticks_idle_nesting = DYNTICK_TASK_NEST_VALUE,
286         .dynticks_idle = ATOMIC_INIT(1),
287 #endif /* #ifdef CONFIG_NO_HZ_FULL_SYSIDLE */
288 };
289
290 DEFINE_PER_CPU_SHARED_ALIGNED(unsigned long, rcu_qs_ctr);
291 EXPORT_PER_CPU_SYMBOL_GPL(rcu_qs_ctr);
292
293 /*
294  * Let the RCU core know that this CPU has gone through the scheduler,
295  * which is a quiescent state.  This is called when the need for a
296  * quiescent state is urgent, so we burn an atomic operation and full
297  * memory barriers to let the RCU core know about it, regardless of what
298  * this CPU might (or might not) do in the near future.
299  *
300  * We inform the RCU core by emulating a zero-duration dyntick-idle
301  * period, which we in turn do by incrementing the ->dynticks counter
302  * by two.
303  */
304 static void rcu_momentary_dyntick_idle(void)
305 {
306         unsigned long flags;
307         struct rcu_data *rdp;
308         struct rcu_dynticks *rdtp;
309         int resched_mask;
310         struct rcu_state *rsp;
311
312         local_irq_save(flags);
313
314         /*
315          * Yes, we can lose flag-setting operations.  This is OK, because
316          * the flag will be set again after some delay.
317          */
318         resched_mask = raw_cpu_read(rcu_sched_qs_mask);
319         raw_cpu_write(rcu_sched_qs_mask, 0);
320
321         /* Find the flavor that needs a quiescent state. */
322         for_each_rcu_flavor(rsp) {
323                 rdp = raw_cpu_ptr(rsp->rda);
324                 if (!(resched_mask & rsp->flavor_mask))
325                         continue;
326                 smp_mb(); /* rcu_sched_qs_mask before cond_resched_completed. */
327                 if (READ_ONCE(rdp->mynode->completed) !=
328                     READ_ONCE(rdp->cond_resched_completed))
329                         continue;
330
331                 /*
332                  * Pretend to be momentarily idle for the quiescent state.
333                  * This allows the grace-period kthread to record the
334                  * quiescent state, with no need for this CPU to do anything
335                  * further.
336                  */
337                 rdtp = this_cpu_ptr(&rcu_dynticks);
338                 smp_mb__before_atomic(); /* Earlier stuff before QS. */
339                 atomic_add(2, &rdtp->dynticks);  /* QS. */
340                 smp_mb__after_atomic(); /* Later stuff after QS. */
341                 break;
342         }
343         local_irq_restore(flags);
344 }
345
346 /*
347  * Note a context switch.  This is a quiescent state for RCU-sched,
348  * and requires special handling for preemptible RCU.
349  * The caller must have disabled preemption.
350  */
351 void rcu_note_context_switch(void)
352 {
353         trace_rcu_utilization(TPS("Start context switch"));
354         rcu_sched_qs();
355         rcu_preempt_note_context_switch();
356         if (unlikely(raw_cpu_read(rcu_sched_qs_mask)))
357                 rcu_momentary_dyntick_idle();
358         trace_rcu_utilization(TPS("End context switch"));
359 }
360 EXPORT_SYMBOL_GPL(rcu_note_context_switch);
361
362 /*
363  * Register a quiescent state for all RCU flavors.  If there is an
364  * emergency, invoke rcu_momentary_dyntick_idle() to do a heavy-weight
365  * dyntick-idle quiescent state visible to other CPUs (but only for those
366  * RCU flavors in desperate need of a quiescent state, which will normally
367  * be none of them).  Either way, do a lightweight quiescent state for
368  * all RCU flavors.
369  */
370 void rcu_all_qs(void)
371 {
372         if (unlikely(raw_cpu_read(rcu_sched_qs_mask)))
373                 rcu_momentary_dyntick_idle();
374         this_cpu_inc(rcu_qs_ctr);
375 }
376 EXPORT_SYMBOL_GPL(rcu_all_qs);
377
378 static long blimit = 10;        /* Maximum callbacks per rcu_do_batch. */
379 static long qhimark = 10000;    /* If this many pending, ignore blimit. */
380 static long qlowmark = 100;     /* Once only this many pending, use blimit. */
381
382 module_param(blimit, long, 0444);
383 module_param(qhimark, long, 0444);
384 module_param(qlowmark, long, 0444);
385
386 static ulong jiffies_till_first_fqs = ULONG_MAX;
387 static ulong jiffies_till_next_fqs = ULONG_MAX;
388
389 module_param(jiffies_till_first_fqs, ulong, 0644);
390 module_param(jiffies_till_next_fqs, ulong, 0644);
391
392 /*
393  * How long the grace period must be before we start recruiting
394  * quiescent-state help from rcu_note_context_switch().
395  */
396 static ulong jiffies_till_sched_qs = HZ / 20;
397 module_param(jiffies_till_sched_qs, ulong, 0644);
398
399 static bool rcu_start_gp_advanced(struct rcu_state *rsp, struct rcu_node *rnp,
400                                   struct rcu_data *rdp);
401 static void force_qs_rnp(struct rcu_state *rsp,
402                          int (*f)(struct rcu_data *rsp, bool *isidle,
403                                   unsigned long *maxj),
404                          bool *isidle, unsigned long *maxj);
405 static void force_quiescent_state(struct rcu_state *rsp);
406 static int rcu_pending(void);
407
408 /*
409  * Return the number of RCU batches started thus far for debug & stats.
410  */
411 unsigned long rcu_batches_started(void)
412 {
413         return rcu_state_p->gpnum;
414 }
415 EXPORT_SYMBOL_GPL(rcu_batches_started);
416
417 /*
418  * Return the number of RCU-sched batches started thus far for debug & stats.
419  */
420 unsigned long rcu_batches_started_sched(void)
421 {
422         return rcu_sched_state.gpnum;
423 }
424 EXPORT_SYMBOL_GPL(rcu_batches_started_sched);
425
426 /*
427  * Return the number of RCU BH batches started thus far for debug & stats.
428  */
429 unsigned long rcu_batches_started_bh(void)
430 {
431         return rcu_bh_state.gpnum;
432 }
433 EXPORT_SYMBOL_GPL(rcu_batches_started_bh);
434
435 /*
436  * Return the number of RCU batches completed thus far for debug & stats.
437  */
438 unsigned long rcu_batches_completed(void)
439 {
440         return rcu_state_p->completed;
441 }
442 EXPORT_SYMBOL_GPL(rcu_batches_completed);
443
444 /*
445  * Return the number of RCU-sched batches completed thus far for debug & stats.
446  */
447 unsigned long rcu_batches_completed_sched(void)
448 {
449         return rcu_sched_state.completed;
450 }
451 EXPORT_SYMBOL_GPL(rcu_batches_completed_sched);
452
453 /*
454  * Return the number of RCU BH batches completed thus far for debug & stats.
455  */
456 unsigned long rcu_batches_completed_bh(void)
457 {
458         return rcu_bh_state.completed;
459 }
460 EXPORT_SYMBOL_GPL(rcu_batches_completed_bh);
461
462 /*
463  * Force a quiescent state.
464  */
465 void rcu_force_quiescent_state(void)
466 {
467         force_quiescent_state(rcu_state_p);
468 }
469 EXPORT_SYMBOL_GPL(rcu_force_quiescent_state);
470
471 /*
472  * Force a quiescent state for RCU BH.
473  */
474 void rcu_bh_force_quiescent_state(void)
475 {
476         force_quiescent_state(&rcu_bh_state);
477 }
478 EXPORT_SYMBOL_GPL(rcu_bh_force_quiescent_state);
479
480 /*
481  * Force a quiescent state for RCU-sched.
482  */
483 void rcu_sched_force_quiescent_state(void)
484 {
485         force_quiescent_state(&rcu_sched_state);
486 }
487 EXPORT_SYMBOL_GPL(rcu_sched_force_quiescent_state);
488
489 /*
490  * Show the state of the grace-period kthreads.
491  */
492 void show_rcu_gp_kthreads(void)
493 {
494         struct rcu_state *rsp;
495
496         for_each_rcu_flavor(rsp) {
497                 pr_info("%s: wait state: %d ->state: %#lx\n",
498                         rsp->name, rsp->gp_state, rsp->gp_kthread->state);
499                 /* sched_show_task(rsp->gp_kthread); */
500         }
501 }
502 EXPORT_SYMBOL_GPL(show_rcu_gp_kthreads);
503
504 /*
505  * Record the number of times rcutorture tests have been initiated and
506  * terminated.  This information allows the debugfs tracing stats to be
507  * correlated to the rcutorture messages, even when the rcutorture module
508  * is being repeatedly loaded and unloaded.  In other words, we cannot
509  * store this state in rcutorture itself.
510  */
511 void rcutorture_record_test_transition(void)
512 {
513         rcutorture_testseq++;
514         rcutorture_vernum = 0;
515 }
516 EXPORT_SYMBOL_GPL(rcutorture_record_test_transition);
517
518 /*
519  * Send along grace-period-related data for rcutorture diagnostics.
520  */
521 void rcutorture_get_gp_data(enum rcutorture_type test_type, int *flags,
522                             unsigned long *gpnum, unsigned long *completed)
523 {
524         struct rcu_state *rsp = NULL;
525
526         switch (test_type) {
527         case RCU_FLAVOR:
528                 rsp = rcu_state_p;
529                 break;
530         case RCU_BH_FLAVOR:
531                 rsp = &rcu_bh_state;
532                 break;
533         case RCU_SCHED_FLAVOR:
534                 rsp = &rcu_sched_state;
535                 break;
536         default:
537                 break;
538         }
539         if (rsp != NULL) {
540                 *flags = READ_ONCE(rsp->gp_flags);
541                 *gpnum = READ_ONCE(rsp->gpnum);
542                 *completed = READ_ONCE(rsp->completed);
543                 return;
544         }
545         *flags = 0;
546         *gpnum = 0;
547         *completed = 0;
548 }
549 EXPORT_SYMBOL_GPL(rcutorture_get_gp_data);
550
551 /*
552  * Record the number of writer passes through the current rcutorture test.
553  * This is also used to correlate debugfs tracing stats with the rcutorture
554  * messages.
555  */
556 void rcutorture_record_progress(unsigned long vernum)
557 {
558         rcutorture_vernum++;
559 }
560 EXPORT_SYMBOL_GPL(rcutorture_record_progress);
561
562 /*
563  * Does the CPU have callbacks ready to be invoked?
564  */
565 static int
566 cpu_has_callbacks_ready_to_invoke(struct rcu_data *rdp)
567 {
568         return &rdp->nxtlist != rdp->nxttail[RCU_DONE_TAIL] &&
569                rdp->nxttail[RCU_DONE_TAIL] != NULL;
570 }
571
572 /*
573  * Return the root node of the specified rcu_state structure.
574  */
575 static struct rcu_node *rcu_get_root(struct rcu_state *rsp)
576 {
577         return &rsp->node[0];
578 }
579
580 /*
581  * Is there any need for future grace periods?
582  * Interrupts must be disabled.  If the caller does not hold the root
583  * rnp_node structure's ->lock, the results are advisory only.
584  */
585 static int rcu_future_needs_gp(struct rcu_state *rsp)
586 {
587         struct rcu_node *rnp = rcu_get_root(rsp);
588         int idx = (READ_ONCE(rnp->completed) + 1) & 0x1;
589         int *fp = &rnp->need_future_gp[idx];
590
591         return READ_ONCE(*fp);
592 }
593
594 /*
595  * Does the current CPU require a not-yet-started grace period?
596  * The caller must have disabled interrupts to prevent races with
597  * normal callback registry.
598  */
599 static int
600 cpu_needs_another_gp(struct rcu_state *rsp, struct rcu_data *rdp)
601 {
602         int i;
603
604         if (rcu_gp_in_progress(rsp))
605                 return 0;  /* No, a grace period is already in progress. */
606         if (rcu_future_needs_gp(rsp))
607                 return 1;  /* Yes, a no-CBs CPU needs one. */
608         if (!rdp->nxttail[RCU_NEXT_TAIL])
609                 return 0;  /* No, this is a no-CBs (or offline) CPU. */
610         if (*rdp->nxttail[RCU_NEXT_READY_TAIL])
611                 return 1;  /* Yes, this CPU has newly registered callbacks. */
612         for (i = RCU_WAIT_TAIL; i < RCU_NEXT_TAIL; i++)
613                 if (rdp->nxttail[i - 1] != rdp->nxttail[i] &&
614                     ULONG_CMP_LT(READ_ONCE(rsp->completed),
615                                  rdp->nxtcompleted[i]))
616                         return 1;  /* Yes, CBs for future grace period. */
617         return 0; /* No grace period needed. */
618 }
619
620 /*
621  * rcu_eqs_enter_common - current CPU is moving towards extended quiescent state
622  *
623  * If the new value of the ->dynticks_nesting counter now is zero,
624  * we really have entered idle, and must do the appropriate accounting.
625  * The caller must have disabled interrupts.
626  */
627 static void rcu_eqs_enter_common(long long oldval, bool user)
628 {
629         struct rcu_state *rsp;
630         struct rcu_data *rdp;
631         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
632
633         trace_rcu_dyntick(TPS("Start"), oldval, rdtp->dynticks_nesting);
634         if (IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
635             !user && !is_idle_task(current)) {
636                 struct task_struct *idle __maybe_unused =
637                         idle_task(smp_processor_id());
638
639                 trace_rcu_dyntick(TPS("Error on entry: not idle task"), oldval, 0);
640                 ftrace_dump(DUMP_ORIG);
641                 WARN_ONCE(1, "Current pid: %d comm: %s / Idle pid: %d comm: %s",
642                           current->pid, current->comm,
643                           idle->pid, idle->comm); /* must be idle task! */
644         }
645         for_each_rcu_flavor(rsp) {
646                 rdp = this_cpu_ptr(rsp->rda);
647                 do_nocb_deferred_wakeup(rdp);
648         }
649         rcu_prepare_for_idle();
650         /* CPUs seeing atomic_inc() must see prior RCU read-side crit sects */
651         smp_mb__before_atomic();  /* See above. */
652         atomic_inc(&rdtp->dynticks);
653         smp_mb__after_atomic();  /* Force ordering with next sojourn. */
654         WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
655                      atomic_read(&rdtp->dynticks) & 0x1);
656         rcu_dynticks_task_enter();
657
658         /*
659          * It is illegal to enter an extended quiescent state while
660          * in an RCU read-side critical section.
661          */
662         RCU_LOCKDEP_WARN(lock_is_held(&rcu_lock_map),
663                          "Illegal idle entry in RCU read-side critical section.");
664         RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map),
665                          "Illegal idle entry in RCU-bh read-side critical section.");
666         RCU_LOCKDEP_WARN(lock_is_held(&rcu_sched_lock_map),
667                          "Illegal idle entry in RCU-sched read-side critical section.");
668 }
669
670 /*
671  * Enter an RCU extended quiescent state, which can be either the
672  * idle loop or adaptive-tickless usermode execution.
673  */
674 static void rcu_eqs_enter(bool user)
675 {
676         long long oldval;
677         struct rcu_dynticks *rdtp;
678
679         rdtp = this_cpu_ptr(&rcu_dynticks);
680         oldval = rdtp->dynticks_nesting;
681         WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
682                      (oldval & DYNTICK_TASK_NEST_MASK) == 0);
683         if ((oldval & DYNTICK_TASK_NEST_MASK) == DYNTICK_TASK_NEST_VALUE) {
684                 rdtp->dynticks_nesting = 0;
685                 rcu_eqs_enter_common(oldval, user);
686         } else {
687                 rdtp->dynticks_nesting -= DYNTICK_TASK_NEST_VALUE;
688         }
689 }
690
691 /**
692  * rcu_idle_enter - inform RCU that current CPU is entering idle
693  *
694  * Enter idle mode, in other words, -leave- the mode in which RCU
695  * read-side critical sections can occur.  (Though RCU read-side
696  * critical sections can occur in irq handlers in idle, a possibility
697  * handled by irq_enter() and irq_exit().)
698  *
699  * We crowbar the ->dynticks_nesting field to zero to allow for
700  * the possibility of usermode upcalls having messed up our count
701  * of interrupt nesting level during the prior busy period.
702  */
703 void rcu_idle_enter(void)
704 {
705         unsigned long flags;
706
707         local_irq_save(flags);
708         rcu_eqs_enter(false);
709         rcu_sysidle_enter(0);
710         local_irq_restore(flags);
711 }
712 EXPORT_SYMBOL_GPL(rcu_idle_enter);
713
714 #ifdef CONFIG_NO_HZ_FULL
715 /**
716  * rcu_user_enter - inform RCU that we are resuming userspace.
717  *
718  * Enter RCU idle mode right before resuming userspace.  No use of RCU
719  * is permitted between this call and rcu_user_exit(). This way the
720  * CPU doesn't need to maintain the tick for RCU maintenance purposes
721  * when the CPU runs in userspace.
722  */
723 void rcu_user_enter(void)
724 {
725         rcu_eqs_enter(1);
726 }
727 #endif /* CONFIG_NO_HZ_FULL */
728
729 /**
730  * rcu_irq_exit - inform RCU that current CPU is exiting irq towards idle
731  *
732  * Exit from an interrupt handler, which might possibly result in entering
733  * idle mode, in other words, leaving the mode in which read-side critical
734  * sections can occur.
735  *
736  * This code assumes that the idle loop never does anything that might
737  * result in unbalanced calls to irq_enter() and irq_exit().  If your
738  * architecture violates this assumption, RCU will give you what you
739  * deserve, good and hard.  But very infrequently and irreproducibly.
740  *
741  * Use things like work queues to work around this limitation.
742  *
743  * You have been warned.
744  */
745 void rcu_irq_exit(void)
746 {
747         unsigned long flags;
748         long long oldval;
749         struct rcu_dynticks *rdtp;
750
751         local_irq_save(flags);
752         rdtp = this_cpu_ptr(&rcu_dynticks);
753         oldval = rdtp->dynticks_nesting;
754         rdtp->dynticks_nesting--;
755         WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
756                      rdtp->dynticks_nesting < 0);
757         if (rdtp->dynticks_nesting)
758                 trace_rcu_dyntick(TPS("--="), oldval, rdtp->dynticks_nesting);
759         else
760                 rcu_eqs_enter_common(oldval, true);
761         rcu_sysidle_enter(1);
762         local_irq_restore(flags);
763 }
764
765 /*
766  * rcu_eqs_exit_common - current CPU moving away from extended quiescent state
767  *
768  * If the new value of the ->dynticks_nesting counter was previously zero,
769  * we really have exited idle, and must do the appropriate accounting.
770  * The caller must have disabled interrupts.
771  */
772 static void rcu_eqs_exit_common(long long oldval, int user)
773 {
774         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
775
776         rcu_dynticks_task_exit();
777         smp_mb__before_atomic();  /* Force ordering w/previous sojourn. */
778         atomic_inc(&rdtp->dynticks);
779         /* CPUs seeing atomic_inc() must see later RCU read-side crit sects */
780         smp_mb__after_atomic();  /* See above. */
781         WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
782                      !(atomic_read(&rdtp->dynticks) & 0x1));
783         rcu_cleanup_after_idle();
784         trace_rcu_dyntick(TPS("End"), oldval, rdtp->dynticks_nesting);
785         if (IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
786             !user && !is_idle_task(current)) {
787                 struct task_struct *idle __maybe_unused =
788                         idle_task(smp_processor_id());
789
790                 trace_rcu_dyntick(TPS("Error on exit: not idle task"),
791                                   oldval, rdtp->dynticks_nesting);
792                 ftrace_dump(DUMP_ORIG);
793                 WARN_ONCE(1, "Current pid: %d comm: %s / Idle pid: %d comm: %s",
794                           current->pid, current->comm,
795                           idle->pid, idle->comm); /* must be idle task! */
796         }
797 }
798
799 /*
800  * Exit an RCU extended quiescent state, which can be either the
801  * idle loop or adaptive-tickless usermode execution.
802  */
803 static void rcu_eqs_exit(bool user)
804 {
805         struct rcu_dynticks *rdtp;
806         long long oldval;
807
808         rdtp = this_cpu_ptr(&rcu_dynticks);
809         oldval = rdtp->dynticks_nesting;
810         WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) && oldval < 0);
811         if (oldval & DYNTICK_TASK_NEST_MASK) {
812                 rdtp->dynticks_nesting += DYNTICK_TASK_NEST_VALUE;
813         } else {
814                 rdtp->dynticks_nesting = DYNTICK_TASK_EXIT_IDLE;
815                 rcu_eqs_exit_common(oldval, user);
816         }
817 }
818
819 /**
820  * rcu_idle_exit - inform RCU that current CPU is leaving idle
821  *
822  * Exit idle mode, in other words, -enter- the mode in which RCU
823  * read-side critical sections can occur.
824  *
825  * We crowbar the ->dynticks_nesting field to DYNTICK_TASK_NEST to
826  * allow for the possibility of usermode upcalls messing up our count
827  * of interrupt nesting level during the busy period that is just
828  * now starting.
829  */
830 void rcu_idle_exit(void)
831 {
832         unsigned long flags;
833
834         local_irq_save(flags);
835         rcu_eqs_exit(false);
836         rcu_sysidle_exit(0);
837         local_irq_restore(flags);
838 }
839 EXPORT_SYMBOL_GPL(rcu_idle_exit);
840
841 #ifdef CONFIG_NO_HZ_FULL
842 /**
843  * rcu_user_exit - inform RCU that we are exiting userspace.
844  *
845  * Exit RCU idle mode while entering the kernel because it can
846  * run a RCU read side critical section anytime.
847  */
848 void rcu_user_exit(void)
849 {
850         rcu_eqs_exit(1);
851 }
852 #endif /* CONFIG_NO_HZ_FULL */
853
854 /**
855  * rcu_irq_enter - inform RCU that current CPU is entering irq away from idle
856  *
857  * Enter an interrupt handler, which might possibly result in exiting
858  * idle mode, in other words, entering the mode in which read-side critical
859  * sections can occur.
860  *
861  * Note that the Linux kernel is fully capable of entering an interrupt
862  * handler that it never exits, for example when doing upcalls to
863  * user mode!  This code assumes that the idle loop never does upcalls to
864  * user mode.  If your architecture does do upcalls from the idle loop (or
865  * does anything else that results in unbalanced calls to the irq_enter()
866  * and irq_exit() functions), RCU will give you what you deserve, good
867  * and hard.  But very infrequently and irreproducibly.
868  *
869  * Use things like work queues to work around this limitation.
870  *
871  * You have been warned.
872  */
873 void rcu_irq_enter(void)
874 {
875         unsigned long flags;
876         struct rcu_dynticks *rdtp;
877         long long oldval;
878
879         local_irq_save(flags);
880         rdtp = this_cpu_ptr(&rcu_dynticks);
881         oldval = rdtp->dynticks_nesting;
882         rdtp->dynticks_nesting++;
883         WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
884                      rdtp->dynticks_nesting == 0);
885         if (oldval)
886                 trace_rcu_dyntick(TPS("++="), oldval, rdtp->dynticks_nesting);
887         else
888                 rcu_eqs_exit_common(oldval, true);
889         rcu_sysidle_exit(1);
890         local_irq_restore(flags);
891 }
892
893 /**
894  * rcu_nmi_enter - inform RCU of entry to NMI context
895  *
896  * If the CPU was idle from RCU's viewpoint, update rdtp->dynticks and
897  * rdtp->dynticks_nmi_nesting to let the RCU grace-period handling know
898  * that the CPU is active.  This implementation permits nested NMIs, as
899  * long as the nesting level does not overflow an int.  (You will probably
900  * run out of stack space first.)
901  */
902 void rcu_nmi_enter(void)
903 {
904         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
905         int incby = 2;
906
907         /* Complain about underflow. */
908         WARN_ON_ONCE(rdtp->dynticks_nmi_nesting < 0);
909
910         /*
911          * If idle from RCU viewpoint, atomically increment ->dynticks
912          * to mark non-idle and increment ->dynticks_nmi_nesting by one.
913          * Otherwise, increment ->dynticks_nmi_nesting by two.  This means
914          * if ->dynticks_nmi_nesting is equal to one, we are guaranteed
915          * to be in the outermost NMI handler that interrupted an RCU-idle
916          * period (observation due to Andy Lutomirski).
917          */
918         if (!(atomic_read(&rdtp->dynticks) & 0x1)) {
919                 smp_mb__before_atomic();  /* Force delay from prior write. */
920                 atomic_inc(&rdtp->dynticks);
921                 /* atomic_inc() before later RCU read-side crit sects */
922                 smp_mb__after_atomic();  /* See above. */
923                 WARN_ON_ONCE(!(atomic_read(&rdtp->dynticks) & 0x1));
924                 incby = 1;
925         }
926         rdtp->dynticks_nmi_nesting += incby;
927         barrier();
928 }
929
930 /**
931  * rcu_nmi_exit - inform RCU of exit from NMI context
932  *
933  * If we are returning from the outermost NMI handler that interrupted an
934  * RCU-idle period, update rdtp->dynticks and rdtp->dynticks_nmi_nesting
935  * to let the RCU grace-period handling know that the CPU is back to
936  * being RCU-idle.
937  */
938 void rcu_nmi_exit(void)
939 {
940         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
941
942         /*
943          * Check for ->dynticks_nmi_nesting underflow and bad ->dynticks.
944          * (We are exiting an NMI handler, so RCU better be paying attention
945          * to us!)
946          */
947         WARN_ON_ONCE(rdtp->dynticks_nmi_nesting <= 0);
948         WARN_ON_ONCE(!(atomic_read(&rdtp->dynticks) & 0x1));
949
950         /*
951          * If the nesting level is not 1, the CPU wasn't RCU-idle, so
952          * leave it in non-RCU-idle state.
953          */
954         if (rdtp->dynticks_nmi_nesting != 1) {
955                 rdtp->dynticks_nmi_nesting -= 2;
956                 return;
957         }
958
959         /* This NMI interrupted an RCU-idle CPU, restore RCU-idleness. */
960         rdtp->dynticks_nmi_nesting = 0;
961         /* CPUs seeing atomic_inc() must see prior RCU read-side crit sects */
962         smp_mb__before_atomic();  /* See above. */
963         atomic_inc(&rdtp->dynticks);
964         smp_mb__after_atomic();  /* Force delay to next write. */
965         WARN_ON_ONCE(atomic_read(&rdtp->dynticks) & 0x1);
966 }
967
968 /**
969  * __rcu_is_watching - are RCU read-side critical sections safe?
970  *
971  * Return true if RCU is watching the running CPU, which means that
972  * this CPU can safely enter RCU read-side critical sections.  Unlike
973  * rcu_is_watching(), the caller of __rcu_is_watching() must have at
974  * least disabled preemption.
975  */
976 bool notrace __rcu_is_watching(void)
977 {
978         return atomic_read(this_cpu_ptr(&rcu_dynticks.dynticks)) & 0x1;
979 }
980
981 /**
982  * rcu_is_watching - see if RCU thinks that the current CPU is idle
983  *
984  * If the current CPU is in its idle loop and is neither in an interrupt
985  * or NMI handler, return true.
986  */
987 bool notrace rcu_is_watching(void)
988 {
989         bool ret;
990
991         preempt_disable_notrace();
992         ret = __rcu_is_watching();
993         preempt_enable_notrace();
994         return ret;
995 }
996 EXPORT_SYMBOL_GPL(rcu_is_watching);
997
998 #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU)
999
1000 /*
1001  * Is the current CPU online?  Disable preemption to avoid false positives
1002  * that could otherwise happen due to the current CPU number being sampled,
1003  * this task being preempted, its old CPU being taken offline, resuming
1004  * on some other CPU, then determining that its old CPU is now offline.
1005  * It is OK to use RCU on an offline processor during initial boot, hence
1006  * the check for rcu_scheduler_fully_active.  Note also that it is OK
1007  * for a CPU coming online to use RCU for one jiffy prior to marking itself
1008  * online in the cpu_online_mask.  Similarly, it is OK for a CPU going
1009  * offline to continue to use RCU for one jiffy after marking itself
1010  * offline in the cpu_online_mask.  This leniency is necessary given the
1011  * non-atomic nature of the online and offline processing, for example,
1012  * the fact that a CPU enters the scheduler after completing the CPU_DYING
1013  * notifiers.
1014  *
1015  * This is also why RCU internally marks CPUs online during the
1016  * CPU_UP_PREPARE phase and offline during the CPU_DEAD phase.
1017  *
1018  * Disable checking if in an NMI handler because we cannot safely report
1019  * errors from NMI handlers anyway.
1020  */
1021 bool rcu_lockdep_current_cpu_online(void)
1022 {
1023         struct rcu_data *rdp;
1024         struct rcu_node *rnp;
1025         bool ret;
1026
1027         if (in_nmi())
1028                 return true;
1029         preempt_disable();
1030         rdp = this_cpu_ptr(&rcu_sched_data);
1031         rnp = rdp->mynode;
1032         ret = (rdp->grpmask & rcu_rnp_online_cpus(rnp)) ||
1033               !rcu_scheduler_fully_active;
1034         preempt_enable();
1035         return ret;
1036 }
1037 EXPORT_SYMBOL_GPL(rcu_lockdep_current_cpu_online);
1038
1039 #endif /* #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU) */
1040
1041 /**
1042  * rcu_is_cpu_rrupt_from_idle - see if idle or immediately interrupted from idle
1043  *
1044  * If the current CPU is idle or running at a first-level (not nested)
1045  * interrupt from idle, return true.  The caller must have at least
1046  * disabled preemption.
1047  */
1048 static int rcu_is_cpu_rrupt_from_idle(void)
1049 {
1050         return __this_cpu_read(rcu_dynticks.dynticks_nesting) <= 1;
1051 }
1052
1053 /*
1054  * Snapshot the specified CPU's dynticks counter so that we can later
1055  * credit them with an implicit quiescent state.  Return 1 if this CPU
1056  * is in dynticks idle mode, which is an extended quiescent state.
1057  */
1058 static int dyntick_save_progress_counter(struct rcu_data *rdp,
1059                                          bool *isidle, unsigned long *maxj)
1060 {
1061         rdp->dynticks_snap = atomic_add_return(0, &rdp->dynticks->dynticks);
1062         rcu_sysidle_check_cpu(rdp, isidle, maxj);
1063         if ((rdp->dynticks_snap & 0x1) == 0) {
1064                 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, TPS("dti"));
1065                 return 1;
1066         } else {
1067                 if (ULONG_CMP_LT(READ_ONCE(rdp->gpnum) + ULONG_MAX / 4,
1068                                  rdp->mynode->gpnum))
1069                         WRITE_ONCE(rdp->gpwrap, true);
1070                 return 0;
1071         }
1072 }
1073
1074 /*
1075  * Return true if the specified CPU has passed through a quiescent
1076  * state by virtue of being in or having passed through an dynticks
1077  * idle state since the last call to dyntick_save_progress_counter()
1078  * for this same CPU, or by virtue of having been offline.
1079  */
1080 static int rcu_implicit_dynticks_qs(struct rcu_data *rdp,
1081                                     bool *isidle, unsigned long *maxj)
1082 {
1083         unsigned int curr;
1084         int *rcrmp;
1085         unsigned int snap;
1086
1087         curr = (unsigned int)atomic_add_return(0, &rdp->dynticks->dynticks);
1088         snap = (unsigned int)rdp->dynticks_snap;
1089
1090         /*
1091          * If the CPU passed through or entered a dynticks idle phase with
1092          * no active irq/NMI handlers, then we can safely pretend that the CPU
1093          * already acknowledged the request to pass through a quiescent
1094          * state.  Either way, that CPU cannot possibly be in an RCU
1095          * read-side critical section that started before the beginning
1096          * of the current RCU grace period.
1097          */
1098         if ((curr & 0x1) == 0 || UINT_CMP_GE(curr, snap + 2)) {
1099                 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, TPS("dti"));
1100                 rdp->dynticks_fqs++;
1101                 return 1;
1102         }
1103
1104         /*
1105          * Check for the CPU being offline, but only if the grace period
1106          * is old enough.  We don't need to worry about the CPU changing
1107          * state: If we see it offline even once, it has been through a
1108          * quiescent state.
1109          *
1110          * The reason for insisting that the grace period be at least
1111          * one jiffy old is that CPUs that are not quite online and that
1112          * have just gone offline can still execute RCU read-side critical
1113          * sections.
1114          */
1115         if (ULONG_CMP_GE(rdp->rsp->gp_start + 2, jiffies))
1116                 return 0;  /* Grace period is not old enough. */
1117         barrier();
1118         if (cpu_is_offline(rdp->cpu)) {
1119                 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, TPS("ofl"));
1120                 rdp->offline_fqs++;
1121                 return 1;
1122         }
1123
1124         /*
1125          * A CPU running for an extended time within the kernel can
1126          * delay RCU grace periods.  When the CPU is in NO_HZ_FULL mode,
1127          * even context-switching back and forth between a pair of
1128          * in-kernel CPU-bound tasks cannot advance grace periods.
1129          * So if the grace period is old enough, make the CPU pay attention.
1130          * Note that the unsynchronized assignments to the per-CPU
1131          * rcu_sched_qs_mask variable are safe.  Yes, setting of
1132          * bits can be lost, but they will be set again on the next
1133          * force-quiescent-state pass.  So lost bit sets do not result
1134          * in incorrect behavior, merely in a grace period lasting
1135          * a few jiffies longer than it might otherwise.  Because
1136          * there are at most four threads involved, and because the
1137          * updates are only once every few jiffies, the probability of
1138          * lossage (and thus of slight grace-period extension) is
1139          * quite low.
1140          *
1141          * Note that if the jiffies_till_sched_qs boot/sysfs parameter
1142          * is set too high, we override with half of the RCU CPU stall
1143          * warning delay.
1144          */
1145         rcrmp = &per_cpu(rcu_sched_qs_mask, rdp->cpu);
1146         if (ULONG_CMP_GE(jiffies,
1147                          rdp->rsp->gp_start + jiffies_till_sched_qs) ||
1148             ULONG_CMP_GE(jiffies, rdp->rsp->jiffies_resched)) {
1149                 if (!(READ_ONCE(*rcrmp) & rdp->rsp->flavor_mask)) {
1150                         WRITE_ONCE(rdp->cond_resched_completed,
1151                                    READ_ONCE(rdp->mynode->completed));
1152                         smp_mb(); /* ->cond_resched_completed before *rcrmp. */
1153                         WRITE_ONCE(*rcrmp,
1154                                    READ_ONCE(*rcrmp) + rdp->rsp->flavor_mask);
1155                         resched_cpu(rdp->cpu);  /* Force CPU into scheduler. */
1156                         rdp->rsp->jiffies_resched += 5; /* Enable beating. */
1157                 } else if (ULONG_CMP_GE(jiffies, rdp->rsp->jiffies_resched)) {
1158                         /* Time to beat on that CPU again! */
1159                         resched_cpu(rdp->cpu);  /* Force CPU into scheduler. */
1160                         rdp->rsp->jiffies_resched += 5; /* Re-enable beating. */
1161                 }
1162         }
1163
1164         return 0;
1165 }
1166
1167 static void record_gp_stall_check_time(struct rcu_state *rsp)
1168 {
1169         unsigned long j = jiffies;
1170         unsigned long j1;
1171
1172         rsp->gp_start = j;
1173         smp_wmb(); /* Record start time before stall time. */
1174         j1 = rcu_jiffies_till_stall_check();
1175         WRITE_ONCE(rsp->jiffies_stall, j + j1);
1176         rsp->jiffies_resched = j + j1 / 2;
1177         rsp->n_force_qs_gpstart = READ_ONCE(rsp->n_force_qs);
1178 }
1179
1180 /*
1181  * Complain about starvation of grace-period kthread.
1182  */
1183 static void rcu_check_gp_kthread_starvation(struct rcu_state *rsp)
1184 {
1185         unsigned long gpa;
1186         unsigned long j;
1187
1188         j = jiffies;
1189         gpa = READ_ONCE(rsp->gp_activity);
1190         if (j - gpa > 2 * HZ)
1191                 pr_err("%s kthread starved for %ld jiffies! g%lu c%lu f%#x s%d ->state=%#lx\n",
1192                        rsp->name, j - gpa,
1193                        rsp->gpnum, rsp->completed,
1194                        rsp->gp_flags, rsp->gp_state,
1195                        rsp->gp_kthread ? rsp->gp_kthread->state : 0);
1196 }
1197
1198 /*
1199  * Dump stacks of all tasks running on stalled CPUs.
1200  */
1201 static void rcu_dump_cpu_stacks(struct rcu_state *rsp)
1202 {
1203         int cpu;
1204         unsigned long flags;
1205         struct rcu_node *rnp;
1206
1207         rcu_for_each_leaf_node(rsp, rnp) {
1208                 raw_spin_lock_irqsave(&rnp->lock, flags);
1209                 if (rnp->qsmask != 0) {
1210                         for (cpu = 0; cpu <= rnp->grphi - rnp->grplo; cpu++)
1211                                 if (rnp->qsmask & (1UL << cpu))
1212                                         dump_cpu_task(rnp->grplo + cpu);
1213                 }
1214                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1215         }
1216 }
1217
1218 static void print_other_cpu_stall(struct rcu_state *rsp, unsigned long gpnum)
1219 {
1220         int cpu;
1221         long delta;
1222         unsigned long flags;
1223         unsigned long gpa;
1224         unsigned long j;
1225         int ndetected = 0;
1226         struct rcu_node *rnp = rcu_get_root(rsp);
1227         long totqlen = 0;
1228
1229         /* Only let one CPU complain about others per time interval. */
1230
1231         raw_spin_lock_irqsave(&rnp->lock, flags);
1232         delta = jiffies - READ_ONCE(rsp->jiffies_stall);
1233         if (delta < RCU_STALL_RAT_DELAY || !rcu_gp_in_progress(rsp)) {
1234                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1235                 return;
1236         }
1237         WRITE_ONCE(rsp->jiffies_stall,
1238                    jiffies + 3 * rcu_jiffies_till_stall_check() + 3);
1239         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1240
1241         /*
1242          * OK, time to rat on our buddy...
1243          * See Documentation/RCU/stallwarn.txt for info on how to debug
1244          * RCU CPU stall warnings.
1245          */
1246         pr_err("INFO: %s detected stalls on CPUs/tasks:",
1247                rsp->name);
1248         print_cpu_stall_info_begin();
1249         rcu_for_each_leaf_node(rsp, rnp) {
1250                 raw_spin_lock_irqsave(&rnp->lock, flags);
1251                 ndetected += rcu_print_task_stall(rnp);
1252                 if (rnp->qsmask != 0) {
1253                         for (cpu = 0; cpu <= rnp->grphi - rnp->grplo; cpu++)
1254                                 if (rnp->qsmask & (1UL << cpu)) {
1255                                         print_cpu_stall_info(rsp,
1256                                                              rnp->grplo + cpu);
1257                                         ndetected++;
1258                                 }
1259                 }
1260                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1261         }
1262
1263         print_cpu_stall_info_end();
1264         for_each_possible_cpu(cpu)
1265                 totqlen += per_cpu_ptr(rsp->rda, cpu)->qlen;
1266         pr_cont("(detected by %d, t=%ld jiffies, g=%ld, c=%ld, q=%lu)\n",
1267                smp_processor_id(), (long)(jiffies - rsp->gp_start),
1268                (long)rsp->gpnum, (long)rsp->completed, totqlen);
1269         if (ndetected) {
1270                 rcu_dump_cpu_stacks(rsp);
1271         } else {
1272                 if (READ_ONCE(rsp->gpnum) != gpnum ||
1273                     READ_ONCE(rsp->completed) == gpnum) {
1274                         pr_err("INFO: Stall ended before state dump start\n");
1275                 } else {
1276                         j = jiffies;
1277                         gpa = READ_ONCE(rsp->gp_activity);
1278                         pr_err("All QSes seen, last %s kthread activity %ld (%ld-%ld), jiffies_till_next_fqs=%ld, root ->qsmask %#lx\n",
1279                                rsp->name, j - gpa, j, gpa,
1280                                jiffies_till_next_fqs,
1281                                rcu_get_root(rsp)->qsmask);
1282                         /* In this case, the current CPU might be at fault. */
1283                         sched_show_task(current);
1284                 }
1285         }
1286
1287         /* Complain about tasks blocking the grace period. */
1288         rcu_print_detail_task_stall(rsp);
1289
1290         rcu_check_gp_kthread_starvation(rsp);
1291
1292         force_quiescent_state(rsp);  /* Kick them all. */
1293 }
1294
1295 static void print_cpu_stall(struct rcu_state *rsp)
1296 {
1297         int cpu;
1298         unsigned long flags;
1299         struct rcu_node *rnp = rcu_get_root(rsp);
1300         long totqlen = 0;
1301
1302         /*
1303          * OK, time to rat on ourselves...
1304          * See Documentation/RCU/stallwarn.txt for info on how to debug
1305          * RCU CPU stall warnings.
1306          */
1307         pr_err("INFO: %s self-detected stall on CPU", rsp->name);
1308         print_cpu_stall_info_begin();
1309         print_cpu_stall_info(rsp, smp_processor_id());
1310         print_cpu_stall_info_end();
1311         for_each_possible_cpu(cpu)
1312                 totqlen += per_cpu_ptr(rsp->rda, cpu)->qlen;
1313         pr_cont(" (t=%lu jiffies g=%ld c=%ld q=%lu)\n",
1314                 jiffies - rsp->gp_start,
1315                 (long)rsp->gpnum, (long)rsp->completed, totqlen);
1316
1317         rcu_check_gp_kthread_starvation(rsp);
1318
1319         rcu_dump_cpu_stacks(rsp);
1320
1321         raw_spin_lock_irqsave(&rnp->lock, flags);
1322         if (ULONG_CMP_GE(jiffies, READ_ONCE(rsp->jiffies_stall)))
1323                 WRITE_ONCE(rsp->jiffies_stall,
1324                            jiffies + 3 * rcu_jiffies_till_stall_check() + 3);
1325         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1326
1327         /*
1328          * Attempt to revive the RCU machinery by forcing a context switch.
1329          *
1330          * A context switch would normally allow the RCU state machine to make
1331          * progress and it could be we're stuck in kernel space without context
1332          * switches for an entirely unreasonable amount of time.
1333          */
1334         resched_cpu(smp_processor_id());
1335 }
1336
1337 static void check_cpu_stall(struct rcu_state *rsp, struct rcu_data *rdp)
1338 {
1339         unsigned long completed;
1340         unsigned long gpnum;
1341         unsigned long gps;
1342         unsigned long j;
1343         unsigned long js;
1344         struct rcu_node *rnp;
1345
1346         if (rcu_cpu_stall_suppress || !rcu_gp_in_progress(rsp))
1347                 return;
1348         j = jiffies;
1349
1350         /*
1351          * Lots of memory barriers to reject false positives.
1352          *
1353          * The idea is to pick up rsp->gpnum, then rsp->jiffies_stall,
1354          * then rsp->gp_start, and finally rsp->completed.  These values
1355          * are updated in the opposite order with memory barriers (or
1356          * equivalent) during grace-period initialization and cleanup.
1357          * Now, a false positive can occur if we get an new value of
1358          * rsp->gp_start and a old value of rsp->jiffies_stall.  But given
1359          * the memory barriers, the only way that this can happen is if one
1360          * grace period ends and another starts between these two fetches.
1361          * Detect this by comparing rsp->completed with the previous fetch
1362          * from rsp->gpnum.
1363          *
1364          * Given this check, comparisons of jiffies, rsp->jiffies_stall,
1365          * and rsp->gp_start suffice to forestall false positives.
1366          */
1367         gpnum = READ_ONCE(rsp->gpnum);
1368         smp_rmb(); /* Pick up ->gpnum first... */
1369         js = READ_ONCE(rsp->jiffies_stall);
1370         smp_rmb(); /* ...then ->jiffies_stall before the rest... */
1371         gps = READ_ONCE(rsp->gp_start);
1372         smp_rmb(); /* ...and finally ->gp_start before ->completed. */
1373         completed = READ_ONCE(rsp->completed);
1374         if (ULONG_CMP_GE(completed, gpnum) ||
1375             ULONG_CMP_LT(j, js) ||
1376             ULONG_CMP_GE(gps, js))
1377                 return; /* No stall or GP completed since entering function. */
1378         rnp = rdp->mynode;
1379         if (rcu_gp_in_progress(rsp) &&
1380             (READ_ONCE(rnp->qsmask) & rdp->grpmask)) {
1381
1382                 /* We haven't checked in, so go dump stack. */
1383                 print_cpu_stall(rsp);
1384
1385         } else if (rcu_gp_in_progress(rsp) &&
1386                    ULONG_CMP_GE(j, js + RCU_STALL_RAT_DELAY)) {
1387
1388                 /* They had a few time units to dump stack, so complain. */
1389                 print_other_cpu_stall(rsp, gpnum);
1390         }
1391 }
1392
1393 /**
1394  * rcu_cpu_stall_reset - prevent further stall warnings in current grace period
1395  *
1396  * Set the stall-warning timeout way off into the future, thus preventing
1397  * any RCU CPU stall-warning messages from appearing in the current set of
1398  * RCU grace periods.
1399  *
1400  * The caller must disable hard irqs.
1401  */
1402 void rcu_cpu_stall_reset(void)
1403 {
1404         struct rcu_state *rsp;
1405
1406         for_each_rcu_flavor(rsp)
1407                 WRITE_ONCE(rsp->jiffies_stall, jiffies + ULONG_MAX / 2);
1408 }
1409
1410 /*
1411  * Initialize the specified rcu_data structure's default callback list
1412  * to empty.  The default callback list is the one that is not used by
1413  * no-callbacks CPUs.
1414  */
1415 static void init_default_callback_list(struct rcu_data *rdp)
1416 {
1417         int i;
1418
1419         rdp->nxtlist = NULL;
1420         for (i = 0; i < RCU_NEXT_SIZE; i++)
1421                 rdp->nxttail[i] = &rdp->nxtlist;
1422 }
1423
1424 /*
1425  * Initialize the specified rcu_data structure's callback list to empty.
1426  */
1427 static void init_callback_list(struct rcu_data *rdp)
1428 {
1429         if (init_nocb_callback_list(rdp))
1430                 return;
1431         init_default_callback_list(rdp);
1432 }
1433
1434 /*
1435  * Determine the value that ->completed will have at the end of the
1436  * next subsequent grace period.  This is used to tag callbacks so that
1437  * a CPU can invoke callbacks in a timely fashion even if that CPU has
1438  * been dyntick-idle for an extended period with callbacks under the
1439  * influence of RCU_FAST_NO_HZ.
1440  *
1441  * The caller must hold rnp->lock with interrupts disabled.
1442  */
1443 static unsigned long rcu_cbs_completed(struct rcu_state *rsp,
1444                                        struct rcu_node *rnp)
1445 {
1446         /*
1447          * If RCU is idle, we just wait for the next grace period.
1448          * But we can only be sure that RCU is idle if we are looking
1449          * at the root rcu_node structure -- otherwise, a new grace
1450          * period might have started, but just not yet gotten around
1451          * to initializing the current non-root rcu_node structure.
1452          */
1453         if (rcu_get_root(rsp) == rnp && rnp->gpnum == rnp->completed)
1454                 return rnp->completed + 1;
1455
1456         /*
1457          * Otherwise, wait for a possible partial grace period and
1458          * then the subsequent full grace period.
1459          */
1460         return rnp->completed + 2;
1461 }
1462
1463 /*
1464  * Trace-event helper function for rcu_start_future_gp() and
1465  * rcu_nocb_wait_gp().
1466  */
1467 static void trace_rcu_future_gp(struct rcu_node *rnp, struct rcu_data *rdp,
1468                                 unsigned long c, const char *s)
1469 {
1470         trace_rcu_future_grace_period(rdp->rsp->name, rnp->gpnum,
1471                                       rnp->completed, c, rnp->level,
1472                                       rnp->grplo, rnp->grphi, s);
1473 }
1474
1475 /*
1476  * Start some future grace period, as needed to handle newly arrived
1477  * callbacks.  The required future grace periods are recorded in each
1478  * rcu_node structure's ->need_future_gp field.  Returns true if there
1479  * is reason to awaken the grace-period kthread.
1480  *
1481  * The caller must hold the specified rcu_node structure's ->lock.
1482  */
1483 static bool __maybe_unused
1484 rcu_start_future_gp(struct rcu_node *rnp, struct rcu_data *rdp,
1485                     unsigned long *c_out)
1486 {
1487         unsigned long c;
1488         int i;
1489         bool ret = false;
1490         struct rcu_node *rnp_root = rcu_get_root(rdp->rsp);
1491
1492         /*
1493          * Pick up grace-period number for new callbacks.  If this
1494          * grace period is already marked as needed, return to the caller.
1495          */
1496         c = rcu_cbs_completed(rdp->rsp, rnp);
1497         trace_rcu_future_gp(rnp, rdp, c, TPS("Startleaf"));
1498         if (rnp->need_future_gp[c & 0x1]) {
1499                 trace_rcu_future_gp(rnp, rdp, c, TPS("Prestartleaf"));
1500                 goto out;
1501         }
1502
1503         /*
1504          * If either this rcu_node structure or the root rcu_node structure
1505          * believe that a grace period is in progress, then we must wait
1506          * for the one following, which is in "c".  Because our request
1507          * will be noticed at the end of the current grace period, we don't
1508          * need to explicitly start one.  We only do the lockless check
1509          * of rnp_root's fields if the current rcu_node structure thinks
1510          * there is no grace period in flight, and because we hold rnp->lock,
1511          * the only possible change is when rnp_root's two fields are
1512          * equal, in which case rnp_root->gpnum might be concurrently
1513          * incremented.  But that is OK, as it will just result in our
1514          * doing some extra useless work.
1515          */
1516         if (rnp->gpnum != rnp->completed ||
1517             READ_ONCE(rnp_root->gpnum) != READ_ONCE(rnp_root->completed)) {
1518                 rnp->need_future_gp[c & 0x1]++;
1519                 trace_rcu_future_gp(rnp, rdp, c, TPS("Startedleaf"));
1520                 goto out;
1521         }
1522
1523         /*
1524          * There might be no grace period in progress.  If we don't already
1525          * hold it, acquire the root rcu_node structure's lock in order to
1526          * start one (if needed).
1527          */
1528         if (rnp != rnp_root) {
1529                 raw_spin_lock(&rnp_root->lock);
1530                 smp_mb__after_unlock_lock();
1531         }
1532
1533         /*
1534          * Get a new grace-period number.  If there really is no grace
1535          * period in progress, it will be smaller than the one we obtained
1536          * earlier.  Adjust callbacks as needed.  Note that even no-CBs
1537          * CPUs have a ->nxtcompleted[] array, so no no-CBs checks needed.
1538          */
1539         c = rcu_cbs_completed(rdp->rsp, rnp_root);
1540         for (i = RCU_DONE_TAIL; i < RCU_NEXT_TAIL; i++)
1541                 if (ULONG_CMP_LT(c, rdp->nxtcompleted[i]))
1542                         rdp->nxtcompleted[i] = c;
1543
1544         /*
1545          * If the needed for the required grace period is already
1546          * recorded, trace and leave.
1547          */
1548         if (rnp_root->need_future_gp[c & 0x1]) {
1549                 trace_rcu_future_gp(rnp, rdp, c, TPS("Prestartedroot"));
1550                 goto unlock_out;
1551         }
1552
1553         /* Record the need for the future grace period. */
1554         rnp_root->need_future_gp[c & 0x1]++;
1555
1556         /* If a grace period is not already in progress, start one. */
1557         if (rnp_root->gpnum != rnp_root->completed) {
1558                 trace_rcu_future_gp(rnp, rdp, c, TPS("Startedleafroot"));
1559         } else {
1560                 trace_rcu_future_gp(rnp, rdp, c, TPS("Startedroot"));
1561                 ret = rcu_start_gp_advanced(rdp->rsp, rnp_root, rdp);
1562         }
1563 unlock_out:
1564         if (rnp != rnp_root)
1565                 raw_spin_unlock(&rnp_root->lock);
1566 out:
1567         if (c_out != NULL)
1568                 *c_out = c;
1569         return ret;
1570 }
1571
1572 /*
1573  * Clean up any old requests for the just-ended grace period.  Also return
1574  * whether any additional grace periods have been requested.  Also invoke
1575  * rcu_nocb_gp_cleanup() in order to wake up any no-callbacks kthreads
1576  * waiting for this grace period to complete.
1577  */
1578 static int rcu_future_gp_cleanup(struct rcu_state *rsp, struct rcu_node *rnp)
1579 {
1580         int c = rnp->completed;
1581         int needmore;
1582         struct rcu_data *rdp = this_cpu_ptr(rsp->rda);
1583
1584         rcu_nocb_gp_cleanup(rsp, rnp);
1585         rnp->need_future_gp[c & 0x1] = 0;
1586         needmore = rnp->need_future_gp[(c + 1) & 0x1];
1587         trace_rcu_future_gp(rnp, rdp, c,
1588                             needmore ? TPS("CleanupMore") : TPS("Cleanup"));
1589         return needmore;
1590 }
1591
1592 /*
1593  * Awaken the grace-period kthread for the specified flavor of RCU.
1594  * Don't do a self-awaken, and don't bother awakening when there is
1595  * nothing for the grace-period kthread to do (as in several CPUs
1596  * raced to awaken, and we lost), and finally don't try to awaken
1597  * a kthread that has not yet been created.
1598  */
1599 static void rcu_gp_kthread_wake(struct rcu_state *rsp)
1600 {
1601         if (current == rsp->gp_kthread ||
1602             !READ_ONCE(rsp->gp_flags) ||
1603             !rsp->gp_kthread)
1604                 return;
1605         wake_up(&rsp->gp_wq);
1606 }
1607
1608 /*
1609  * If there is room, assign a ->completed number to any callbacks on
1610  * this CPU that have not already been assigned.  Also accelerate any
1611  * callbacks that were previously assigned a ->completed number that has
1612  * since proven to be too conservative, which can happen if callbacks get
1613  * assigned a ->completed number while RCU is idle, but with reference to
1614  * a non-root rcu_node structure.  This function is idempotent, so it does
1615  * not hurt to call it repeatedly.  Returns an flag saying that we should
1616  * awaken the RCU grace-period kthread.
1617  *
1618  * The caller must hold rnp->lock with interrupts disabled.
1619  */
1620 static bool rcu_accelerate_cbs(struct rcu_state *rsp, struct rcu_node *rnp,
1621                                struct rcu_data *rdp)
1622 {
1623         unsigned long c;
1624         int i;
1625         bool ret;
1626
1627         /* If the CPU has no callbacks, nothing to do. */
1628         if (!rdp->nxttail[RCU_NEXT_TAIL] || !*rdp->nxttail[RCU_DONE_TAIL])
1629                 return false;
1630
1631         /*
1632          * Starting from the sublist containing the callbacks most
1633          * recently assigned a ->completed number and working down, find the
1634          * first sublist that is not assignable to an upcoming grace period.
1635          * Such a sublist has something in it (first two tests) and has
1636          * a ->completed number assigned that will complete sooner than
1637          * the ->completed number for newly arrived callbacks (last test).
1638          *
1639          * The key point is that any later sublist can be assigned the
1640          * same ->completed number as the newly arrived callbacks, which
1641          * means that the callbacks in any of these later sublist can be
1642          * grouped into a single sublist, whether or not they have already
1643          * been assigned a ->completed number.
1644          */
1645         c = rcu_cbs_completed(rsp, rnp);
1646         for (i = RCU_NEXT_TAIL - 1; i > RCU_DONE_TAIL; i--)
1647                 if (rdp->nxttail[i] != rdp->nxttail[i - 1] &&
1648                     !ULONG_CMP_GE(rdp->nxtcompleted[i], c))
1649                         break;
1650
1651         /*
1652          * If there are no sublist for unassigned callbacks, leave.
1653          * At the same time, advance "i" one sublist, so that "i" will
1654          * index into the sublist where all the remaining callbacks should
1655          * be grouped into.
1656          */
1657         if (++i >= RCU_NEXT_TAIL)
1658                 return false;
1659
1660         /*
1661          * Assign all subsequent callbacks' ->completed number to the next
1662          * full grace period and group them all in the sublist initially
1663          * indexed by "i".
1664          */
1665         for (; i <= RCU_NEXT_TAIL; i++) {
1666                 rdp->nxttail[i] = rdp->nxttail[RCU_NEXT_TAIL];
1667                 rdp->nxtcompleted[i] = c;
1668         }
1669         /* Record any needed additional grace periods. */
1670         ret = rcu_start_future_gp(rnp, rdp, NULL);
1671
1672         /* Trace depending on how much we were able to accelerate. */
1673         if (!*rdp->nxttail[RCU_WAIT_TAIL])
1674                 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("AccWaitCB"));
1675         else
1676                 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("AccReadyCB"));
1677         return ret;
1678 }
1679
1680 /*
1681  * Move any callbacks whose grace period has completed to the
1682  * RCU_DONE_TAIL sublist, then compact the remaining sublists and
1683  * assign ->completed numbers to any callbacks in the RCU_NEXT_TAIL
1684  * sublist.  This function is idempotent, so it does not hurt to
1685  * invoke it repeatedly.  As long as it is not invoked -too- often...
1686  * Returns true if the RCU grace-period kthread needs to be awakened.
1687  *
1688  * The caller must hold rnp->lock with interrupts disabled.
1689  */
1690 static bool rcu_advance_cbs(struct rcu_state *rsp, struct rcu_node *rnp,
1691                             struct rcu_data *rdp)
1692 {
1693         int i, j;
1694
1695         /* If the CPU has no callbacks, nothing to do. */
1696         if (!rdp->nxttail[RCU_NEXT_TAIL] || !*rdp->nxttail[RCU_DONE_TAIL])
1697                 return false;
1698
1699         /*
1700          * Find all callbacks whose ->completed numbers indicate that they
1701          * are ready to invoke, and put them into the RCU_DONE_TAIL sublist.
1702          */
1703         for (i = RCU_WAIT_TAIL; i < RCU_NEXT_TAIL; i++) {
1704                 if (ULONG_CMP_LT(rnp->completed, rdp->nxtcompleted[i]))
1705                         break;
1706                 rdp->nxttail[RCU_DONE_TAIL] = rdp->nxttail[i];
1707         }
1708         /* Clean up any sublist tail pointers that were misordered above. */
1709         for (j = RCU_WAIT_TAIL; j < i; j++)
1710                 rdp->nxttail[j] = rdp->nxttail[RCU_DONE_TAIL];
1711
1712         /* Copy down callbacks to fill in empty sublists. */
1713         for (j = RCU_WAIT_TAIL; i < RCU_NEXT_TAIL; i++, j++) {
1714                 if (rdp->nxttail[j] == rdp->nxttail[RCU_NEXT_TAIL])
1715                         break;
1716                 rdp->nxttail[j] = rdp->nxttail[i];
1717                 rdp->nxtcompleted[j] = rdp->nxtcompleted[i];
1718         }
1719
1720         /* Classify any remaining callbacks. */
1721         return rcu_accelerate_cbs(rsp, rnp, rdp);
1722 }
1723
1724 /*
1725  * Update CPU-local rcu_data state to record the beginnings and ends of
1726  * grace periods.  The caller must hold the ->lock of the leaf rcu_node
1727  * structure corresponding to the current CPU, and must have irqs disabled.
1728  * Returns true if the grace-period kthread needs to be awakened.
1729  */
1730 static bool __note_gp_changes(struct rcu_state *rsp, struct rcu_node *rnp,
1731                               struct rcu_data *rdp)
1732 {
1733         bool ret;
1734
1735         /* Handle the ends of any preceding grace periods first. */
1736         if (rdp->completed == rnp->completed &&
1737             !unlikely(READ_ONCE(rdp->gpwrap))) {
1738
1739                 /* No grace period end, so just accelerate recent callbacks. */
1740                 ret = rcu_accelerate_cbs(rsp, rnp, rdp);
1741
1742         } else {
1743
1744                 /* Advance callbacks. */
1745                 ret = rcu_advance_cbs(rsp, rnp, rdp);
1746
1747                 /* Remember that we saw this grace-period completion. */
1748                 rdp->completed = rnp->completed;
1749                 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("cpuend"));
1750         }
1751
1752         if (rdp->gpnum != rnp->gpnum || unlikely(READ_ONCE(rdp->gpwrap))) {
1753                 /*
1754                  * If the current grace period is waiting for this CPU,
1755                  * set up to detect a quiescent state, otherwise don't
1756                  * go looking for one.
1757                  */
1758                 rdp->gpnum = rnp->gpnum;
1759                 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("cpustart"));
1760                 rdp->cpu_no_qs.b.norm = true;
1761                 rdp->rcu_qs_ctr_snap = __this_cpu_read(rcu_qs_ctr);
1762                 rdp->core_needs_qs = !!(rnp->qsmask & rdp->grpmask);
1763                 zero_cpu_stall_ticks(rdp);
1764                 WRITE_ONCE(rdp->gpwrap, false);
1765         }
1766         return ret;
1767 }
1768
1769 static void note_gp_changes(struct rcu_state *rsp, struct rcu_data *rdp)
1770 {
1771         unsigned long flags;
1772         bool needwake;
1773         struct rcu_node *rnp;
1774
1775         local_irq_save(flags);
1776         rnp = rdp->mynode;
1777         if ((rdp->gpnum == READ_ONCE(rnp->gpnum) &&
1778              rdp->completed == READ_ONCE(rnp->completed) &&
1779              !unlikely(READ_ONCE(rdp->gpwrap))) || /* w/out lock. */
1780             !raw_spin_trylock(&rnp->lock)) { /* irqs already off, so later. */
1781                 local_irq_restore(flags);
1782                 return;
1783         }
1784         smp_mb__after_unlock_lock();
1785         needwake = __note_gp_changes(rsp, rnp, rdp);
1786         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1787         if (needwake)
1788                 rcu_gp_kthread_wake(rsp);
1789 }
1790
1791 static void rcu_gp_slow(struct rcu_state *rsp, int delay)
1792 {
1793         if (delay > 0 &&
1794             !(rsp->gpnum % (rcu_num_nodes * PER_RCU_NODE_PERIOD * delay)))
1795                 schedule_timeout_uninterruptible(delay);
1796 }
1797
1798 /*
1799  * Initialize a new grace period.  Return 0 if no grace period required.
1800  */
1801 static int rcu_gp_init(struct rcu_state *rsp)
1802 {
1803         unsigned long oldmask;
1804         struct rcu_data *rdp;
1805         struct rcu_node *rnp = rcu_get_root(rsp);
1806
1807         WRITE_ONCE(rsp->gp_activity, jiffies);
1808         raw_spin_lock_irq(&rnp->lock);
1809         smp_mb__after_unlock_lock();
1810         if (!READ_ONCE(rsp->gp_flags)) {
1811                 /* Spurious wakeup, tell caller to go back to sleep.  */
1812                 raw_spin_unlock_irq(&rnp->lock);
1813                 return 0;
1814         }
1815         WRITE_ONCE(rsp->gp_flags, 0); /* Clear all flags: New grace period. */
1816
1817         if (WARN_ON_ONCE(rcu_gp_in_progress(rsp))) {
1818                 /*
1819                  * Grace period already in progress, don't start another.
1820                  * Not supposed to be able to happen.
1821                  */
1822                 raw_spin_unlock_irq(&rnp->lock);
1823                 return 0;
1824         }
1825
1826         /* Advance to a new grace period and initialize state. */
1827         record_gp_stall_check_time(rsp);
1828         /* Record GP times before starting GP, hence smp_store_release(). */
1829         smp_store_release(&rsp->gpnum, rsp->gpnum + 1);
1830         trace_rcu_grace_period(rsp->name, rsp->gpnum, TPS("start"));
1831         raw_spin_unlock_irq(&rnp->lock);
1832
1833         /*
1834          * Apply per-leaf buffered online and offline operations to the
1835          * rcu_node tree.  Note that this new grace period need not wait
1836          * for subsequent online CPUs, and that quiescent-state forcing
1837          * will handle subsequent offline CPUs.
1838          */
1839         rcu_for_each_leaf_node(rsp, rnp) {
1840                 rcu_gp_slow(rsp, gp_preinit_delay);
1841                 raw_spin_lock_irq(&rnp->lock);
1842                 smp_mb__after_unlock_lock();
1843                 if (rnp->qsmaskinit == rnp->qsmaskinitnext &&
1844                     !rnp->wait_blkd_tasks) {
1845                         /* Nothing to do on this leaf rcu_node structure. */
1846                         raw_spin_unlock_irq(&rnp->lock);
1847                         continue;
1848                 }
1849
1850                 /* Record old state, apply changes to ->qsmaskinit field. */
1851                 oldmask = rnp->qsmaskinit;
1852                 rnp->qsmaskinit = rnp->qsmaskinitnext;
1853
1854                 /* If zero-ness of ->qsmaskinit changed, propagate up tree. */
1855                 if (!oldmask != !rnp->qsmaskinit) {
1856                         if (!oldmask) /* First online CPU for this rcu_node. */
1857                                 rcu_init_new_rnp(rnp);
1858                         else if (rcu_preempt_has_tasks(rnp)) /* blocked tasks */
1859                                 rnp->wait_blkd_tasks = true;
1860                         else /* Last offline CPU and can propagate. */
1861                                 rcu_cleanup_dead_rnp(rnp);
1862                 }
1863
1864                 /*
1865                  * If all waited-on tasks from prior grace period are
1866                  * done, and if all this rcu_node structure's CPUs are
1867                  * still offline, propagate up the rcu_node tree and
1868                  * clear ->wait_blkd_tasks.  Otherwise, if one of this
1869                  * rcu_node structure's CPUs has since come back online,
1870                  * simply clear ->wait_blkd_tasks (but rcu_cleanup_dead_rnp()
1871                  * checks for this, so just call it unconditionally).
1872                  */
1873                 if (rnp->wait_blkd_tasks &&
1874                     (!rcu_preempt_has_tasks(rnp) ||
1875                      rnp->qsmaskinit)) {
1876                         rnp->wait_blkd_tasks = false;
1877                         rcu_cleanup_dead_rnp(rnp);
1878                 }
1879
1880                 raw_spin_unlock_irq(&rnp->lock);
1881         }
1882
1883         /*
1884          * Set the quiescent-state-needed bits in all the rcu_node
1885          * structures for all currently online CPUs in breadth-first order,
1886          * starting from the root rcu_node structure, relying on the layout
1887          * of the tree within the rsp->node[] array.  Note that other CPUs
1888          * will access only the leaves of the hierarchy, thus seeing that no
1889          * grace period is in progress, at least until the corresponding
1890          * leaf node has been initialized.  In addition, we have excluded
1891          * CPU-hotplug operations.
1892          *
1893          * The grace period cannot complete until the initialization
1894          * process finishes, because this kthread handles both.
1895          */
1896         rcu_for_each_node_breadth_first(rsp, rnp) {
1897                 rcu_gp_slow(rsp, gp_init_delay);
1898                 raw_spin_lock_irq(&rnp->lock);
1899                 smp_mb__after_unlock_lock();
1900                 rdp = this_cpu_ptr(rsp->rda);
1901                 rcu_preempt_check_blocked_tasks(rnp);
1902                 rnp->qsmask = rnp->qsmaskinit;
1903                 WRITE_ONCE(rnp->gpnum, rsp->gpnum);
1904                 if (WARN_ON_ONCE(rnp->completed != rsp->completed))
1905                         WRITE_ONCE(rnp->completed, rsp->completed);
1906                 if (rnp == rdp->mynode)
1907                         (void)__note_gp_changes(rsp, rnp, rdp);
1908                 rcu_preempt_boost_start_gp(rnp);
1909                 trace_rcu_grace_period_init(rsp->name, rnp->gpnum,
1910                                             rnp->level, rnp->grplo,
1911                                             rnp->grphi, rnp->qsmask);
1912                 raw_spin_unlock_irq(&rnp->lock);
1913                 cond_resched_rcu_qs();
1914                 WRITE_ONCE(rsp->gp_activity, jiffies);
1915         }
1916
1917         return 1;
1918 }
1919
1920 /*
1921  * Helper function for wait_event_interruptible_timeout() wakeup
1922  * at force-quiescent-state time.
1923  */
1924 static bool rcu_gp_fqs_check_wake(struct rcu_state *rsp, int *gfp)
1925 {
1926         struct rcu_node *rnp = rcu_get_root(rsp);
1927
1928         /* Someone like call_rcu() requested a force-quiescent-state scan. */
1929         *gfp = READ_ONCE(rsp->gp_flags);
1930         if (*gfp & RCU_GP_FLAG_FQS)
1931                 return true;
1932
1933         /* The current grace period has completed. */
1934         if (!READ_ONCE(rnp->qsmask) && !rcu_preempt_blocked_readers_cgp(rnp))
1935                 return true;
1936
1937         return false;
1938 }
1939
1940 /*
1941  * Do one round of quiescent-state forcing.
1942  */
1943 static int rcu_gp_fqs(struct rcu_state *rsp, int fqs_state_in)
1944 {
1945         int fqs_state = fqs_state_in;
1946         bool isidle = false;
1947         unsigned long maxj;
1948         struct rcu_node *rnp = rcu_get_root(rsp);
1949
1950         WRITE_ONCE(rsp->gp_activity, jiffies);
1951         rsp->n_force_qs++;
1952         if (fqs_state == RCU_SAVE_DYNTICK) {
1953                 /* Collect dyntick-idle snapshots. */
1954                 if (is_sysidle_rcu_state(rsp)) {
1955                         isidle = true;
1956                         maxj = jiffies - ULONG_MAX / 4;
1957                 }
1958                 force_qs_rnp(rsp, dyntick_save_progress_counter,
1959                              &isidle, &maxj);
1960                 rcu_sysidle_report_gp(rsp, isidle, maxj);
1961                 fqs_state = RCU_FORCE_QS;
1962         } else {
1963                 /* Handle dyntick-idle and offline CPUs. */
1964                 isidle = true;
1965                 force_qs_rnp(rsp, rcu_implicit_dynticks_qs, &isidle, &maxj);
1966         }
1967         /* Clear flag to prevent immediate re-entry. */
1968         if (READ_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) {
1969                 raw_spin_lock_irq(&rnp->lock);
1970                 smp_mb__after_unlock_lock();
1971                 WRITE_ONCE(rsp->gp_flags,
1972                            READ_ONCE(rsp->gp_flags) & ~RCU_GP_FLAG_FQS);
1973                 raw_spin_unlock_irq(&rnp->lock);
1974         }
1975         return fqs_state;
1976 }
1977
1978 /*
1979  * Clean up after the old grace period.
1980  */
1981 static void rcu_gp_cleanup(struct rcu_state *rsp)
1982 {
1983         unsigned long gp_duration;
1984         bool needgp = false;
1985         int nocb = 0;
1986         struct rcu_data *rdp;
1987         struct rcu_node *rnp = rcu_get_root(rsp);
1988
1989         WRITE_ONCE(rsp->gp_activity, jiffies);
1990         raw_spin_lock_irq(&rnp->lock);
1991         smp_mb__after_unlock_lock();
1992         gp_duration = jiffies - rsp->gp_start;
1993         if (gp_duration > rsp->gp_max)
1994                 rsp->gp_max = gp_duration;
1995
1996         /*
1997          * We know the grace period is complete, but to everyone else
1998          * it appears to still be ongoing.  But it is also the case
1999          * that to everyone else it looks like there is nothing that
2000          * they can do to advance the grace period.  It is therefore
2001          * safe for us to drop the lock in order to mark the grace
2002          * period as completed in all of the rcu_node structures.
2003          */
2004         raw_spin_unlock_irq(&rnp->lock);
2005
2006         /*
2007          * Propagate new ->completed value to rcu_node structures so
2008          * that other CPUs don't have to wait until the start of the next
2009          * grace period to process their callbacks.  This also avoids
2010          * some nasty RCU grace-period initialization races by forcing
2011          * the end of the current grace period to be completely recorded in
2012          * all of the rcu_node structures before the beginning of the next
2013          * grace period is recorded in any of the rcu_node structures.
2014          */
2015         rcu_for_each_node_breadth_first(rsp, rnp) {
2016                 raw_spin_lock_irq(&rnp->lock);
2017                 smp_mb__after_unlock_lock();
2018                 WARN_ON_ONCE(rcu_preempt_blocked_readers_cgp(rnp));
2019                 WARN_ON_ONCE(rnp->qsmask);
2020                 WRITE_ONCE(rnp->completed, rsp->gpnum);
2021                 rdp = this_cpu_ptr(rsp->rda);
2022                 if (rnp == rdp->mynode)
2023                         needgp = __note_gp_changes(rsp, rnp, rdp) || needgp;
2024                 /* smp_mb() provided by prior unlock-lock pair. */
2025                 nocb += rcu_future_gp_cleanup(rsp, rnp);
2026                 raw_spin_unlock_irq(&rnp->lock);
2027                 cond_resched_rcu_qs();
2028                 WRITE_ONCE(rsp->gp_activity, jiffies);
2029                 rcu_gp_slow(rsp, gp_cleanup_delay);
2030         }
2031         rnp = rcu_get_root(rsp);
2032         raw_spin_lock_irq(&rnp->lock);
2033         smp_mb__after_unlock_lock(); /* Order GP before ->completed update. */
2034         rcu_nocb_gp_set(rnp, nocb);
2035
2036         /* Declare grace period done. */
2037         WRITE_ONCE(rsp->completed, rsp->gpnum);
2038         trace_rcu_grace_period(rsp->name, rsp->completed, TPS("end"));
2039         rsp->fqs_state = RCU_GP_IDLE;
2040         rdp = this_cpu_ptr(rsp->rda);
2041         /* Advance CBs to reduce false positives below. */
2042         needgp = rcu_advance_cbs(rsp, rnp, rdp) || needgp;
2043         if (needgp || cpu_needs_another_gp(rsp, rdp)) {
2044                 WRITE_ONCE(rsp->gp_flags, RCU_GP_FLAG_INIT);
2045                 trace_rcu_grace_period(rsp->name,
2046                                        READ_ONCE(rsp->gpnum),
2047                                        TPS("newreq"));
2048         }
2049         raw_spin_unlock_irq(&rnp->lock);
2050 }
2051
2052 /*
2053  * Body of kthread that handles grace periods.
2054  */
2055 static int __noreturn rcu_gp_kthread(void *arg)
2056 {
2057         int fqs_state;
2058         int gf;
2059         unsigned long j;
2060         int ret;
2061         struct rcu_state *rsp = arg;
2062         struct rcu_node *rnp = rcu_get_root(rsp);
2063
2064         rcu_bind_gp_kthread();
2065         for (;;) {
2066
2067                 /* Handle grace-period start. */
2068                 for (;;) {
2069                         trace_rcu_grace_period(rsp->name,
2070                                                READ_ONCE(rsp->gpnum),
2071                                                TPS("reqwait"));
2072                         rsp->gp_state = RCU_GP_WAIT_GPS;
2073                         wait_event_interruptible(rsp->gp_wq,
2074                                                  READ_ONCE(rsp->gp_flags) &
2075                                                  RCU_GP_FLAG_INIT);
2076                         rsp->gp_state = RCU_GP_DONE_GPS;
2077                         /* Locking provides needed memory barrier. */
2078                         if (rcu_gp_init(rsp))
2079                                 break;
2080                         cond_resched_rcu_qs();
2081                         WRITE_ONCE(rsp->gp_activity, jiffies);
2082                         WARN_ON(signal_pending(current));
2083                         trace_rcu_grace_period(rsp->name,
2084                                                READ_ONCE(rsp->gpnum),
2085                                                TPS("reqwaitsig"));
2086                 }
2087
2088                 /* Handle quiescent-state forcing. */
2089                 fqs_state = RCU_SAVE_DYNTICK;
2090                 j = jiffies_till_first_fqs;
2091                 if (j > HZ) {
2092                         j = HZ;
2093                         jiffies_till_first_fqs = HZ;
2094                 }
2095                 ret = 0;
2096                 for (;;) {
2097                         if (!ret)
2098                                 rsp->jiffies_force_qs = jiffies + j;
2099                         trace_rcu_grace_period(rsp->name,
2100                                                READ_ONCE(rsp->gpnum),
2101                                                TPS("fqswait"));
2102                         rsp->gp_state = RCU_GP_WAIT_FQS;
2103                         ret = wait_event_interruptible_timeout(rsp->gp_wq,
2104                                         rcu_gp_fqs_check_wake(rsp, &gf), j);
2105                         rsp->gp_state = RCU_GP_DOING_FQS;
2106                         /* Locking provides needed memory barriers. */
2107                         /* If grace period done, leave loop. */
2108                         if (!READ_ONCE(rnp->qsmask) &&
2109                             !rcu_preempt_blocked_readers_cgp(rnp))
2110                                 break;
2111                         /* If time for quiescent-state forcing, do it. */
2112                         if (ULONG_CMP_GE(jiffies, rsp->jiffies_force_qs) ||
2113                             (gf & RCU_GP_FLAG_FQS)) {
2114                                 trace_rcu_grace_period(rsp->name,
2115                                                        READ_ONCE(rsp->gpnum),
2116                                                        TPS("fqsstart"));
2117                                 fqs_state = rcu_gp_fqs(rsp, fqs_state);
2118                                 trace_rcu_grace_period(rsp->name,
2119                                                        READ_ONCE(rsp->gpnum),
2120                                                        TPS("fqsend"));
2121                                 cond_resched_rcu_qs();
2122                                 WRITE_ONCE(rsp->gp_activity, jiffies);
2123                         } else {
2124                                 /* Deal with stray signal. */
2125                                 cond_resched_rcu_qs();
2126                                 WRITE_ONCE(rsp->gp_activity, jiffies);
2127                                 WARN_ON(signal_pending(current));
2128                                 trace_rcu_grace_period(rsp->name,
2129                                                        READ_ONCE(rsp->gpnum),
2130                                                        TPS("fqswaitsig"));
2131                         }
2132                         j = jiffies_till_next_fqs;
2133                         if (j > HZ) {
2134                                 j = HZ;
2135                                 jiffies_till_next_fqs = HZ;
2136                         } else if (j < 1) {
2137                                 j = 1;
2138                                 jiffies_till_next_fqs = 1;
2139                         }
2140                 }
2141
2142                 /* Handle grace-period end. */
2143                 rsp->gp_state = RCU_GP_CLEANUP;
2144                 rcu_gp_cleanup(rsp);
2145                 rsp->gp_state = RCU_GP_CLEANED;
2146         }
2147 }
2148
2149 /*
2150  * Start a new RCU grace period if warranted, re-initializing the hierarchy
2151  * in preparation for detecting the next grace period.  The caller must hold
2152  * the root node's ->lock and hard irqs must be disabled.
2153  *
2154  * Note that it is legal for a dying CPU (which is marked as offline) to
2155  * invoke this function.  This can happen when the dying CPU reports its
2156  * quiescent state.
2157  *
2158  * Returns true if the grace-period kthread must be awakened.
2159  */
2160 static bool
2161 rcu_start_gp_advanced(struct rcu_state *rsp, struct rcu_node *rnp,
2162                       struct rcu_data *rdp)
2163 {
2164         if (!rsp->gp_kthread || !cpu_needs_another_gp(rsp, rdp)) {
2165                 /*
2166                  * Either we have not yet spawned the grace-period
2167                  * task, this CPU does not need another grace period,
2168                  * or a grace period is already in progress.
2169                  * Either way, don't start a new grace period.
2170                  */
2171                 return false;
2172         }
2173         WRITE_ONCE(rsp->gp_flags, RCU_GP_FLAG_INIT);
2174         trace_rcu_grace_period(rsp->name, READ_ONCE(rsp->gpnum),
2175                                TPS("newreq"));
2176
2177         /*
2178          * We can't do wakeups while holding the rnp->lock, as that
2179          * could cause possible deadlocks with the rq->lock. Defer
2180          * the wakeup to our caller.
2181          */
2182         return true;
2183 }
2184
2185 /*
2186  * Similar to rcu_start_gp_advanced(), but also advance the calling CPU's
2187  * callbacks.  Note that rcu_start_gp_advanced() cannot do this because it
2188  * is invoked indirectly from rcu_advance_cbs(), which would result in
2189  * endless recursion -- or would do so if it wasn't for the self-deadlock
2190  * that is encountered beforehand.
2191  *
2192  * Returns true if the grace-period kthread needs to be awakened.
2193  */
2194 static bool rcu_start_gp(struct rcu_state *rsp)
2195 {
2196         struct rcu_data *rdp = this_cpu_ptr(rsp->rda);
2197         struct rcu_node *rnp = rcu_get_root(rsp);
2198         bool ret = false;
2199
2200         /*
2201          * If there is no grace period in progress right now, any
2202          * callbacks we have up to this point will be satisfied by the
2203          * next grace period.  Also, advancing the callbacks reduces the
2204          * probability of false positives from cpu_needs_another_gp()
2205          * resulting in pointless grace periods.  So, advance callbacks
2206          * then start the grace period!
2207          */
2208         ret = rcu_advance_cbs(rsp, rnp, rdp) || ret;
2209         ret = rcu_start_gp_advanced(rsp, rnp, rdp) || ret;
2210         return ret;
2211 }
2212
2213 /*
2214  * Report a full set of quiescent states to the specified rcu_state
2215  * data structure.  This involves cleaning up after the prior grace
2216  * period and letting rcu_start_gp() start up the next grace period
2217  * if one is needed.  Note that the caller must hold rnp->lock, which
2218  * is released before return.
2219  */
2220 static void rcu_report_qs_rsp(struct rcu_state *rsp, unsigned long flags)
2221         __releases(rcu_get_root(rsp)->lock)
2222 {
2223         WARN_ON_ONCE(!rcu_gp_in_progress(rsp));
2224         WRITE_ONCE(rsp->gp_flags, READ_ONCE(rsp->gp_flags) | RCU_GP_FLAG_FQS);
2225         raw_spin_unlock_irqrestore(&rcu_get_root(rsp)->lock, flags);
2226         rcu_gp_kthread_wake(rsp);
2227 }
2228
2229 /*
2230  * Similar to rcu_report_qs_rdp(), for which it is a helper function.
2231  * Allows quiescent states for a group of CPUs to be reported at one go
2232  * to the specified rcu_node structure, though all the CPUs in the group
2233  * must be represented by the same rcu_node structure (which need not be a
2234  * leaf rcu_node structure, though it often will be).  The gps parameter
2235  * is the grace-period snapshot, which means that the quiescent states
2236  * are valid only if rnp->gpnum is equal to gps.  That structure's lock
2237  * must be held upon entry, and it is released before return.
2238  */
2239 static void
2240 rcu_report_qs_rnp(unsigned long mask, struct rcu_state *rsp,
2241                   struct rcu_node *rnp, unsigned long gps, unsigned long flags)
2242         __releases(rnp->lock)
2243 {
2244         unsigned long oldmask = 0;
2245         struct rcu_node *rnp_c;
2246
2247         /* Walk up the rcu_node hierarchy. */
2248         for (;;) {
2249                 if (!(rnp->qsmask & mask) || rnp->gpnum != gps) {
2250
2251                         /*
2252                          * Our bit has already been cleared, or the
2253                          * relevant grace period is already over, so done.
2254                          */
2255                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
2256                         return;
2257                 }
2258                 WARN_ON_ONCE(oldmask); /* Any child must be all zeroed! */
2259                 rnp->qsmask &= ~mask;
2260                 trace_rcu_quiescent_state_report(rsp->name, rnp->gpnum,
2261                                                  mask, rnp->qsmask, rnp->level,
2262                                                  rnp->grplo, rnp->grphi,
2263                                                  !!rnp->gp_tasks);
2264                 if (rnp->qsmask != 0 || rcu_preempt_blocked_readers_cgp(rnp)) {
2265
2266                         /* Other bits still set at this level, so done. */
2267                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
2268                         return;
2269                 }
2270                 mask = rnp->grpmask;
2271                 if (rnp->parent == NULL) {
2272
2273                         /* No more levels.  Exit loop holding root lock. */
2274
2275                         break;
2276                 }
2277                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2278                 rnp_c = rnp;
2279                 rnp = rnp->parent;
2280                 raw_spin_lock_irqsave(&rnp->lock, flags);
2281                 smp_mb__after_unlock_lock();
2282                 oldmask = rnp_c->qsmask;
2283         }
2284
2285         /*
2286          * Get here if we are the last CPU to pass through a quiescent
2287          * state for this grace period.  Invoke rcu_report_qs_rsp()
2288          * to clean up and start the next grace period if one is needed.
2289          */
2290         rcu_report_qs_rsp(rsp, flags); /* releases rnp->lock. */
2291 }
2292
2293 /*
2294  * Record a quiescent state for all tasks that were previously queued
2295  * on the specified rcu_node structure and that were blocking the current
2296  * RCU grace period.  The caller must hold the specified rnp->lock with
2297  * irqs disabled, and this lock is released upon return, but irqs remain
2298  * disabled.
2299  */
2300 static void rcu_report_unblock_qs_rnp(struct rcu_state *rsp,
2301                                       struct rcu_node *rnp, unsigned long flags)
2302         __releases(rnp->lock)
2303 {
2304         unsigned long gps;
2305         unsigned long mask;
2306         struct rcu_node *rnp_p;
2307
2308         if (rcu_state_p == &rcu_sched_state || rsp != rcu_state_p ||
2309             rnp->qsmask != 0 || rcu_preempt_blocked_readers_cgp(rnp)) {
2310                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2311                 return;  /* Still need more quiescent states! */
2312         }
2313
2314         rnp_p = rnp->parent;
2315         if (rnp_p == NULL) {
2316                 /*
2317                  * Only one rcu_node structure in the tree, so don't
2318                  * try to report up to its nonexistent parent!
2319                  */
2320                 rcu_report_qs_rsp(rsp, flags);
2321                 return;
2322         }
2323
2324         /* Report up the rest of the hierarchy, tracking current ->gpnum. */
2325         gps = rnp->gpnum;
2326         mask = rnp->grpmask;
2327         raw_spin_unlock(&rnp->lock);    /* irqs remain disabled. */
2328         raw_spin_lock(&rnp_p->lock);    /* irqs already disabled. */
2329         smp_mb__after_unlock_lock();
2330         rcu_report_qs_rnp(mask, rsp, rnp_p, gps, flags);
2331 }
2332
2333 /*
2334  * Record a quiescent state for the specified CPU to that CPU's rcu_data
2335  * structure.  This must be either called from the specified CPU, or
2336  * called when the specified CPU is known to be offline (and when it is
2337  * also known that no other CPU is concurrently trying to help the offline
2338  * CPU).  The lastcomp argument is used to make sure we are still in the
2339  * grace period of interest.  We don't want to end the current grace period
2340  * based on quiescent states detected in an earlier grace period!
2341  */
2342 static void
2343 rcu_report_qs_rdp(int cpu, struct rcu_state *rsp, struct rcu_data *rdp)
2344 {
2345         unsigned long flags;
2346         unsigned long mask;
2347         bool needwake;
2348         struct rcu_node *rnp;
2349
2350         rnp = rdp->mynode;
2351         raw_spin_lock_irqsave(&rnp->lock, flags);
2352         smp_mb__after_unlock_lock();
2353         if ((rdp->cpu_no_qs.b.norm &&
2354              rdp->rcu_qs_ctr_snap == __this_cpu_read(rcu_qs_ctr)) ||
2355             rdp->gpnum != rnp->gpnum || rnp->completed == rnp->gpnum ||
2356             rdp->gpwrap) {
2357
2358                 /*
2359                  * The grace period in which this quiescent state was
2360                  * recorded has ended, so don't report it upwards.
2361                  * We will instead need a new quiescent state that lies
2362                  * within the current grace period.
2363                  */
2364                 rdp->cpu_no_qs.b.norm = true;   /* need qs for new gp. */
2365                 rdp->rcu_qs_ctr_snap = __this_cpu_read(rcu_qs_ctr);
2366                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2367                 return;
2368         }
2369         mask = rdp->grpmask;
2370         if ((rnp->qsmask & mask) == 0) {
2371                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2372         } else {
2373                 rdp->core_needs_qs = 0;
2374
2375                 /*
2376                  * This GP can't end until cpu checks in, so all of our
2377                  * callbacks can be processed during the next GP.
2378                  */
2379                 needwake = rcu_accelerate_cbs(rsp, rnp, rdp);
2380
2381                 rcu_report_qs_rnp(mask, rsp, rnp, rnp->gpnum, flags);
2382                 /* ^^^ Released rnp->lock */
2383                 if (needwake)
2384                         rcu_gp_kthread_wake(rsp);
2385         }
2386 }
2387
2388 /*
2389  * Check to see if there is a new grace period of which this CPU
2390  * is not yet aware, and if so, set up local rcu_data state for it.
2391  * Otherwise, see if this CPU has just passed through its first
2392  * quiescent state for this grace period, and record that fact if so.
2393  */
2394 static void
2395 rcu_check_quiescent_state(struct rcu_state *rsp, struct rcu_data *rdp)
2396 {
2397         /* Check for grace-period ends and beginnings. */
2398         note_gp_changes(rsp, rdp);
2399
2400         /*
2401          * Does this CPU still need to do its part for current grace period?
2402          * If no, return and let the other CPUs do their part as well.
2403          */
2404         if (!rdp->core_needs_qs)
2405                 return;
2406
2407         /*
2408          * Was there a quiescent state since the beginning of the grace
2409          * period? If no, then exit and wait for the next call.
2410          */
2411         if (rdp->cpu_no_qs.b.norm &&
2412             rdp->rcu_qs_ctr_snap == __this_cpu_read(rcu_qs_ctr))
2413                 return;
2414
2415         /*
2416          * Tell RCU we are done (but rcu_report_qs_rdp() will be the
2417          * judge of that).
2418          */
2419         rcu_report_qs_rdp(rdp->cpu, rsp, rdp);
2420 }
2421
2422 /*
2423  * Send the specified CPU's RCU callbacks to the orphanage.  The
2424  * specified CPU must be offline, and the caller must hold the
2425  * ->orphan_lock.
2426  */
2427 static void
2428 rcu_send_cbs_to_orphanage(int cpu, struct rcu_state *rsp,
2429                           struct rcu_node *rnp, struct rcu_data *rdp)
2430 {
2431         /* No-CBs CPUs do not have orphanable callbacks. */
2432         if (!IS_ENABLED(CONFIG_HOTPLUG_CPU) || rcu_is_nocb_cpu(rdp->cpu))
2433                 return;
2434
2435         /*
2436          * Orphan the callbacks.  First adjust the counts.  This is safe
2437          * because _rcu_barrier() excludes CPU-hotplug operations, so it
2438          * cannot be running now.  Thus no memory barrier is required.
2439          */
2440         if (rdp->nxtlist != NULL) {
2441                 rsp->qlen_lazy += rdp->qlen_lazy;
2442                 rsp->qlen += rdp->qlen;
2443                 rdp->n_cbs_orphaned += rdp->qlen;
2444                 rdp->qlen_lazy = 0;
2445                 WRITE_ONCE(rdp->qlen, 0);
2446         }
2447
2448         /*
2449          * Next, move those callbacks still needing a grace period to
2450          * the orphanage, where some other CPU will pick them up.
2451          * Some of the callbacks might have gone partway through a grace
2452          * period, but that is too bad.  They get to start over because we
2453          * cannot assume that grace periods are synchronized across CPUs.
2454          * We don't bother updating the ->nxttail[] array yet, instead
2455          * we just reset the whole thing later on.
2456          */
2457         if (*rdp->nxttail[RCU_DONE_TAIL] != NULL) {
2458                 *rsp->orphan_nxttail = *rdp->nxttail[RCU_DONE_TAIL];
2459                 rsp->orphan_nxttail = rdp->nxttail[RCU_NEXT_TAIL];
2460                 *rdp->nxttail[RCU_DONE_TAIL] = NULL;
2461         }
2462
2463         /*
2464          * Then move the ready-to-invoke callbacks to the orphanage,
2465          * where some other CPU will pick them up.  These will not be
2466          * required to pass though another grace period: They are done.
2467          */
2468         if (rdp->nxtlist != NULL) {
2469                 *rsp->orphan_donetail = rdp->nxtlist;
2470                 rsp->orphan_donetail = rdp->nxttail[RCU_DONE_TAIL];
2471         }
2472
2473         /*
2474          * Finally, initialize the rcu_data structure's list to empty and
2475          * disallow further callbacks on this CPU.
2476          */
2477         init_callback_list(rdp);
2478         rdp->nxttail[RCU_NEXT_TAIL] = NULL;
2479 }
2480
2481 /*
2482  * Adopt the RCU callbacks from the specified rcu_state structure's
2483  * orphanage.  The caller must hold the ->orphan_lock.
2484  */
2485 static void rcu_adopt_orphan_cbs(struct rcu_state *rsp, unsigned long flags)
2486 {
2487         int i;
2488         struct rcu_data *rdp = raw_cpu_ptr(rsp->rda);
2489
2490         /* No-CBs CPUs are handled specially. */
2491         if (!IS_ENABLED(CONFIG_HOTPLUG_CPU) ||
2492             rcu_nocb_adopt_orphan_cbs(rsp, rdp, flags))
2493                 return;
2494
2495         /* Do the accounting first. */
2496         rdp->qlen_lazy += rsp->qlen_lazy;
2497         rdp->qlen += rsp->qlen;
2498         rdp->n_cbs_adopted += rsp->qlen;
2499         if (rsp->qlen_lazy != rsp->qlen)
2500                 rcu_idle_count_callbacks_posted();
2501         rsp->qlen_lazy = 0;
2502         rsp->qlen = 0;
2503
2504         /*
2505          * We do not need a memory barrier here because the only way we
2506          * can get here if there is an rcu_barrier() in flight is if
2507          * we are the task doing the rcu_barrier().
2508          */
2509
2510         /* First adopt the ready-to-invoke callbacks. */
2511         if (rsp->orphan_donelist != NULL) {
2512                 *rsp->orphan_donetail = *rdp->nxttail[RCU_DONE_TAIL];
2513                 *rdp->nxttail[RCU_DONE_TAIL] = rsp->orphan_donelist;
2514                 for (i = RCU_NEXT_SIZE - 1; i >= RCU_DONE_TAIL; i--)
2515                         if (rdp->nxttail[i] == rdp->nxttail[RCU_DONE_TAIL])
2516                                 rdp->nxttail[i] = rsp->orphan_donetail;
2517                 rsp->orphan_donelist = NULL;
2518                 rsp->orphan_donetail = &rsp->orphan_donelist;
2519         }
2520
2521         /* And then adopt the callbacks that still need a grace period. */
2522         if (rsp->orphan_nxtlist != NULL) {
2523                 *rdp->nxttail[RCU_NEXT_TAIL] = rsp->orphan_nxtlist;
2524                 rdp->nxttail[RCU_NEXT_TAIL] = rsp->orphan_nxttail;
2525                 rsp->orphan_nxtlist = NULL;
2526                 rsp->orphan_nxttail = &rsp->orphan_nxtlist;
2527         }
2528 }
2529
2530 /*
2531  * Trace the fact that this CPU is going offline.
2532  */
2533 static void rcu_cleanup_dying_cpu(struct rcu_state *rsp)
2534 {
2535         RCU_TRACE(unsigned long mask);
2536         RCU_TRACE(struct rcu_data *rdp = this_cpu_ptr(rsp->rda));
2537         RCU_TRACE(struct rcu_node *rnp = rdp->mynode);
2538
2539         if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))
2540                 return;
2541
2542         RCU_TRACE(mask = rdp->grpmask);
2543         trace_rcu_grace_period(rsp->name,
2544                                rnp->gpnum + 1 - !!(rnp->qsmask & mask),
2545                                TPS("cpuofl"));
2546 }
2547
2548 /*
2549  * All CPUs for the specified rcu_node structure have gone offline,
2550  * and all tasks that were preempted within an RCU read-side critical
2551  * section while running on one of those CPUs have since exited their RCU
2552  * read-side critical section.  Some other CPU is reporting this fact with
2553  * the specified rcu_node structure's ->lock held and interrupts disabled.
2554  * This function therefore goes up the tree of rcu_node structures,
2555  * clearing the corresponding bits in the ->qsmaskinit fields.  Note that
2556  * the leaf rcu_node structure's ->qsmaskinit field has already been
2557  * updated
2558  *
2559  * This function does check that the specified rcu_node structure has
2560  * all CPUs offline and no blocked tasks, so it is OK to invoke it
2561  * prematurely.  That said, invoking it after the fact will cost you
2562  * a needless lock acquisition.  So once it has done its work, don't
2563  * invoke it again.
2564  */
2565 static void rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf)
2566 {
2567         long mask;
2568         struct rcu_node *rnp = rnp_leaf;
2569
2570         if (!IS_ENABLED(CONFIG_HOTPLUG_CPU) ||
2571             rnp->qsmaskinit || rcu_preempt_has_tasks(rnp))
2572                 return;
2573         for (;;) {
2574                 mask = rnp->grpmask;
2575                 rnp = rnp->parent;
2576                 if (!rnp)
2577                         break;
2578                 raw_spin_lock(&rnp->lock); /* irqs already disabled. */
2579                 smp_mb__after_unlock_lock(); /* GP memory ordering. */
2580                 rnp->qsmaskinit &= ~mask;
2581                 rnp->qsmask &= ~mask;
2582                 if (rnp->qsmaskinit) {
2583                         raw_spin_unlock(&rnp->lock); /* irqs remain disabled. */
2584                         return;
2585                 }
2586                 raw_spin_unlock(&rnp->lock); /* irqs remain disabled. */
2587         }
2588 }
2589
2590 /*
2591  * The CPU is exiting the idle loop into the arch_cpu_idle_dead()
2592  * function.  We now remove it from the rcu_node tree's ->qsmaskinit
2593  * bit masks.
2594  */
2595 static void rcu_cleanup_dying_idle_cpu(int cpu, struct rcu_state *rsp)
2596 {
2597         unsigned long flags;
2598         unsigned long mask;
2599         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
2600         struct rcu_node *rnp = rdp->mynode;  /* Outgoing CPU's rdp & rnp. */
2601
2602         if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))
2603                 return;
2604
2605         /* Remove outgoing CPU from mask in the leaf rcu_node structure. */
2606         mask = rdp->grpmask;
2607         raw_spin_lock_irqsave(&rnp->lock, flags);
2608         smp_mb__after_unlock_lock();    /* Enforce GP memory-order guarantee. */
2609         rnp->qsmaskinitnext &= ~mask;
2610         raw_spin_unlock_irqrestore(&rnp->lock, flags);
2611 }
2612
2613 /*
2614  * The CPU has been completely removed, and some other CPU is reporting
2615  * this fact from process context.  Do the remainder of the cleanup,
2616  * including orphaning the outgoing CPU's RCU callbacks, and also
2617  * adopting them.  There can only be one CPU hotplug operation at a time,
2618  * so no other CPU can be attempting to update rcu_cpu_kthread_task.
2619  */
2620 static void rcu_cleanup_dead_cpu(int cpu, struct rcu_state *rsp)
2621 {
2622         unsigned long flags;
2623         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
2624         struct rcu_node *rnp = rdp->mynode;  /* Outgoing CPU's rdp & rnp. */
2625
2626         if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))
2627                 return;
2628
2629         /* Adjust any no-longer-needed kthreads. */
2630         rcu_boost_kthread_setaffinity(rnp, -1);
2631
2632         /* Orphan the dead CPU's callbacks, and adopt them if appropriate. */
2633         raw_spin_lock_irqsave(&rsp->orphan_lock, flags);
2634         rcu_send_cbs_to_orphanage(cpu, rsp, rnp, rdp);
2635         rcu_adopt_orphan_cbs(rsp, flags);
2636         raw_spin_unlock_irqrestore(&rsp->orphan_lock, flags);
2637
2638         WARN_ONCE(rdp->qlen != 0 || rdp->nxtlist != NULL,
2639                   "rcu_cleanup_dead_cpu: Callbacks on offline CPU %d: qlen=%lu, nxtlist=%p\n",
2640                   cpu, rdp->qlen, rdp->nxtlist);
2641 }
2642
2643 /*
2644  * Invoke any RCU callbacks that have made it to the end of their grace
2645  * period.  Thottle as specified by rdp->blimit.
2646  */
2647 static void rcu_do_batch(struct rcu_state *rsp, struct rcu_data *rdp)
2648 {
2649         unsigned long flags;
2650         struct rcu_head *next, *list, **tail;
2651         long bl, count, count_lazy;
2652         int i;
2653
2654         /* If no callbacks are ready, just return. */
2655         if (!cpu_has_callbacks_ready_to_invoke(rdp)) {
2656                 trace_rcu_batch_start(rsp->name, rdp->qlen_lazy, rdp->qlen, 0);
2657                 trace_rcu_batch_end(rsp->name, 0, !!READ_ONCE(rdp->nxtlist),
2658                                     need_resched(), is_idle_task(current),
2659                                     rcu_is_callbacks_kthread());
2660                 return;
2661         }
2662
2663         /*
2664          * Extract the list of ready callbacks, disabling to prevent
2665          * races with call_rcu() from interrupt handlers.
2666          */
2667         local_irq_save(flags);
2668         WARN_ON_ONCE(cpu_is_offline(smp_processor_id()));
2669         bl = rdp->blimit;
2670         trace_rcu_batch_start(rsp->name, rdp->qlen_lazy, rdp->qlen, bl);
2671         list = rdp->nxtlist;
2672         rdp->nxtlist = *rdp->nxttail[RCU_DONE_TAIL];
2673         *rdp->nxttail[RCU_DONE_TAIL] = NULL;
2674         tail = rdp->nxttail[RCU_DONE_TAIL];
2675         for (i = RCU_NEXT_SIZE - 1; i >= 0; i--)
2676                 if (rdp->nxttail[i] == rdp->nxttail[RCU_DONE_TAIL])
2677                         rdp->nxttail[i] = &rdp->nxtlist;
2678         local_irq_restore(flags);
2679
2680         /* Invoke callbacks. */
2681         count = count_lazy = 0;
2682         while (list) {
2683                 next = list->next;
2684                 prefetch(next);
2685                 debug_rcu_head_unqueue(list);
2686                 if (__rcu_reclaim(rsp->name, list))
2687                         count_lazy++;
2688                 list = next;
2689                 /* Stop only if limit reached and CPU has something to do. */
2690                 if (++count >= bl &&
2691                     (need_resched() ||
2692                      (!is_idle_task(current) && !rcu_is_callbacks_kthread())))
2693                         break;
2694         }
2695
2696         local_irq_save(flags);
2697         trace_rcu_batch_end(rsp->name, count, !!list, need_resched(),
2698                             is_idle_task(current),
2699                             rcu_is_callbacks_kthread());
2700
2701         /* Update count, and requeue any remaining callbacks. */
2702         if (list != NULL) {
2703                 *tail = rdp->nxtlist;
2704                 rdp->nxtlist = list;
2705                 for (i = 0; i < RCU_NEXT_SIZE; i++)
2706                         if (&rdp->nxtlist == rdp->nxttail[i])
2707                                 rdp->nxttail[i] = tail;
2708                         else
2709                                 break;
2710         }
2711         smp_mb(); /* List handling before counting for rcu_barrier(). */
2712         rdp->qlen_lazy -= count_lazy;
2713         WRITE_ONCE(rdp->qlen, rdp->qlen - count);
2714         rdp->n_cbs_invoked += count;
2715
2716         /* Reinstate batch limit if we have worked down the excess. */
2717         if (rdp->blimit == LONG_MAX && rdp->qlen <= qlowmark)
2718                 rdp->blimit = blimit;
2719
2720         /* Reset ->qlen_last_fqs_check trigger if enough CBs have drained. */
2721         if (rdp->qlen == 0 && rdp->qlen_last_fqs_check != 0) {
2722                 rdp->qlen_last_fqs_check = 0;
2723                 rdp->n_force_qs_snap = rsp->n_force_qs;
2724         } else if (rdp->qlen < rdp->qlen_last_fqs_check - qhimark)
2725                 rdp->qlen_last_fqs_check = rdp->qlen;
2726         WARN_ON_ONCE((rdp->nxtlist == NULL) != (rdp->qlen == 0));
2727
2728         local_irq_restore(flags);
2729
2730         /* Re-invoke RCU core processing if there are callbacks remaining. */
2731         if (cpu_has_callbacks_ready_to_invoke(rdp))
2732                 invoke_rcu_core();
2733 }
2734
2735 /*
2736  * Check to see if this CPU is in a non-context-switch quiescent state
2737  * (user mode or idle loop for rcu, non-softirq execution for rcu_bh).
2738  * Also schedule RCU core processing.
2739  *
2740  * This function must be called from hardirq context.  It is normally
2741  * invoked from the scheduling-clock interrupt.  If rcu_pending returns
2742  * false, there is no point in invoking rcu_check_callbacks().
2743  */
2744 void rcu_check_callbacks(int user)
2745 {
2746         trace_rcu_utilization(TPS("Start scheduler-tick"));
2747         increment_cpu_stall_ticks();
2748         if (user || rcu_is_cpu_rrupt_from_idle()) {
2749
2750                 /*
2751                  * Get here if this CPU took its interrupt from user
2752                  * mode or from the idle loop, and if this is not a
2753                  * nested interrupt.  In this case, the CPU is in
2754                  * a quiescent state, so note it.
2755                  *
2756                  * No memory barrier is required here because both
2757                  * rcu_sched_qs() and rcu_bh_qs() reference only CPU-local
2758                  * variables that other CPUs neither access nor modify,
2759                  * at least not while the corresponding CPU is online.
2760                  */
2761
2762                 rcu_sched_qs();
2763                 rcu_bh_qs();
2764
2765         } else if (!in_softirq()) {
2766
2767                 /*
2768                  * Get here if this CPU did not take its interrupt from
2769                  * softirq, in other words, if it is not interrupting
2770                  * a rcu_bh read-side critical section.  This is an _bh
2771                  * critical section, so note it.
2772                  */
2773
2774                 rcu_bh_qs();
2775         }
2776         rcu_preempt_check_callbacks();
2777         if (rcu_pending())
2778                 invoke_rcu_core();
2779         if (user)
2780                 rcu_note_voluntary_context_switch(current);
2781         trace_rcu_utilization(TPS("End scheduler-tick"));
2782 }
2783
2784 /*
2785  * Scan the leaf rcu_node structures, processing dyntick state for any that
2786  * have not yet encountered a quiescent state, using the function specified.
2787  * Also initiate boosting for any threads blocked on the root rcu_node.
2788  *
2789  * The caller must have suppressed start of new grace periods.
2790  */
2791 static void force_qs_rnp(struct rcu_state *rsp,
2792                          int (*f)(struct rcu_data *rsp, bool *isidle,
2793                                   unsigned long *maxj),
2794                          bool *isidle, unsigned long *maxj)
2795 {
2796         unsigned long bit;
2797         int cpu;
2798         unsigned long flags;
2799         unsigned long mask;
2800         struct rcu_node *rnp;
2801
2802         rcu_for_each_leaf_node(rsp, rnp) {
2803                 cond_resched_rcu_qs();
2804                 mask = 0;
2805                 raw_spin_lock_irqsave(&rnp->lock, flags);
2806                 smp_mb__after_unlock_lock();
2807                 if (rnp->qsmask == 0) {
2808                         if (rcu_state_p == &rcu_sched_state ||
2809                             rsp != rcu_state_p ||
2810                             rcu_preempt_blocked_readers_cgp(rnp)) {
2811                                 /*
2812                                  * No point in scanning bits because they
2813                                  * are all zero.  But we might need to
2814                                  * priority-boost blocked readers.
2815                                  */
2816                                 rcu_initiate_boost(rnp, flags);
2817                                 /* rcu_initiate_boost() releases rnp->lock */
2818                                 continue;
2819                         }
2820                         if (rnp->parent &&
2821                             (rnp->parent->qsmask & rnp->grpmask)) {
2822                                 /*
2823                                  * Race between grace-period
2824                                  * initialization and task exiting RCU
2825                                  * read-side critical section: Report.
2826                                  */
2827                                 rcu_report_unblock_qs_rnp(rsp, rnp, flags);
2828                                 /* rcu_report_unblock_qs_rnp() rlses ->lock */
2829                                 continue;
2830                         }
2831                 }
2832                 cpu = rnp->grplo;
2833                 bit = 1;
2834                 for (; cpu <= rnp->grphi; cpu++, bit <<= 1) {
2835                         if ((rnp->qsmask & bit) != 0) {
2836                                 if (f(per_cpu_ptr(rsp->rda, cpu), isidle, maxj))
2837                                         mask |= bit;
2838                         }
2839                 }
2840                 if (mask != 0) {
2841                         /* Idle/offline CPUs, report (releases rnp->lock. */
2842                         rcu_report_qs_rnp(mask, rsp, rnp, rnp->gpnum, flags);
2843                 } else {
2844                         /* Nothing to do here, so just drop the lock. */
2845                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
2846                 }
2847         }
2848 }
2849
2850 /*
2851  * Force quiescent states on reluctant CPUs, and also detect which
2852  * CPUs are in dyntick-idle mode.
2853  */
2854 static void force_quiescent_state(struct rcu_state *rsp)
2855 {
2856         unsigned long flags;
2857         bool ret;
2858         struct rcu_node *rnp;
2859         struct rcu_node *rnp_old = NULL;
2860
2861         /* Funnel through hierarchy to reduce memory contention. */
2862         rnp = __this_cpu_read(rsp->rda->mynode);
2863         for (; rnp != NULL; rnp = rnp->parent) {
2864                 ret = (READ_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) ||
2865                       !raw_spin_trylock(&rnp->fqslock);
2866                 if (rnp_old != NULL)
2867                         raw_spin_unlock(&rnp_old->fqslock);
2868                 if (ret) {
2869                         rsp->n_force_qs_lh++;
2870                         return;
2871                 }
2872                 rnp_old = rnp;
2873         }
2874         /* rnp_old == rcu_get_root(rsp), rnp == NULL. */
2875
2876         /* Reached the root of the rcu_node tree, acquire lock. */
2877         raw_spin_lock_irqsave(&rnp_old->lock, flags);
2878         smp_mb__after_unlock_lock();
2879         raw_spin_unlock(&rnp_old->fqslock);
2880         if (READ_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) {
2881                 rsp->n_force_qs_lh++;
2882                 raw_spin_unlock_irqrestore(&rnp_old->lock, flags);
2883                 return;  /* Someone beat us to it. */
2884         }
2885         WRITE_ONCE(rsp->gp_flags, READ_ONCE(rsp->gp_flags) | RCU_GP_FLAG_FQS);
2886         raw_spin_unlock_irqrestore(&rnp_old->lock, flags);
2887         rcu_gp_kthread_wake(rsp);
2888 }
2889
2890 /*
2891  * This does the RCU core processing work for the specified rcu_state
2892  * and rcu_data structures.  This may be called only from the CPU to
2893  * whom the rdp belongs.
2894  */
2895 static void
2896 __rcu_process_callbacks(struct rcu_state *rsp)
2897 {
2898         unsigned long flags;
2899         bool needwake;
2900         struct rcu_data *rdp = raw_cpu_ptr(rsp->rda);
2901
2902         WARN_ON_ONCE(rdp->beenonline == 0);
2903
2904         /* Update RCU state based on any recent quiescent states. */
2905         rcu_check_quiescent_state(rsp, rdp);
2906
2907         /* Does this CPU require a not-yet-started grace period? */
2908         local_irq_save(flags);
2909         if (cpu_needs_another_gp(rsp, rdp)) {
2910                 raw_spin_lock(&rcu_get_root(rsp)->lock); /* irqs disabled. */
2911                 needwake = rcu_start_gp(rsp);
2912                 raw_spin_unlock_irqrestore(&rcu_get_root(rsp)->lock, flags);
2913                 if (needwake)
2914                         rcu_gp_kthread_wake(rsp);
2915         } else {
2916                 local_irq_restore(flags);
2917         }
2918
2919         /* If there are callbacks ready, invoke them. */
2920         if (cpu_has_callbacks_ready_to_invoke(rdp))
2921                 invoke_rcu_callbacks(rsp, rdp);
2922
2923         /* Do any needed deferred wakeups of rcuo kthreads. */
2924         do_nocb_deferred_wakeup(rdp);
2925 }
2926
2927 /*
2928  * Do RCU core processing for the current CPU.
2929  */
2930 static void rcu_process_callbacks(struct softirq_action *unused)
2931 {
2932         struct rcu_state *rsp;
2933
2934         if (cpu_is_offline(smp_processor_id()))
2935                 return;
2936         trace_rcu_utilization(TPS("Start RCU core"));
2937         for_each_rcu_flavor(rsp)
2938                 __rcu_process_callbacks(rsp);
2939         trace_rcu_utilization(TPS("End RCU core"));
2940 }
2941
2942 /*
2943  * Schedule RCU callback invocation.  If the specified type of RCU
2944  * does not support RCU priority boosting, just do a direct call,
2945  * otherwise wake up the per-CPU kernel kthread.  Note that because we
2946  * are running on the current CPU with softirqs disabled, the
2947  * rcu_cpu_kthread_task cannot disappear out from under us.
2948  */
2949 static void invoke_rcu_callbacks(struct rcu_state *rsp, struct rcu_data *rdp)
2950 {
2951         if (unlikely(!READ_ONCE(rcu_scheduler_fully_active)))
2952                 return;
2953         if (likely(!rsp->boost)) {
2954                 rcu_do_batch(rsp, rdp);
2955                 return;
2956         }
2957         invoke_rcu_callbacks_kthread();
2958 }
2959
2960 static void invoke_rcu_core(void)
2961 {
2962         if (cpu_online(smp_processor_id()))
2963                 raise_softirq(RCU_SOFTIRQ);
2964 }
2965
2966 /*
2967  * Handle any core-RCU processing required by a call_rcu() invocation.
2968  */
2969 static void __call_rcu_core(struct rcu_state *rsp, struct rcu_data *rdp,
2970                             struct rcu_head *head, unsigned long flags)
2971 {
2972         bool needwake;
2973
2974         /*
2975          * If called from an extended quiescent state, invoke the RCU
2976          * core in order to force a re-evaluation of RCU's idleness.
2977          */
2978         if (!rcu_is_watching())
2979                 invoke_rcu_core();
2980
2981         /* If interrupts were disabled or CPU offline, don't invoke RCU core. */
2982         if (irqs_disabled_flags(flags) || cpu_is_offline(smp_processor_id()))
2983                 return;
2984
2985         /*
2986          * Force the grace period if too many callbacks or too long waiting.
2987          * Enforce hysteresis, and don't invoke force_quiescent_state()
2988          * if some other CPU has recently done so.  Also, don't bother
2989          * invoking force_quiescent_state() if the newly enqueued callback
2990          * is the only one waiting for a grace period to complete.
2991          */
2992         if (unlikely(rdp->qlen > rdp->qlen_last_fqs_check + qhimark)) {
2993
2994                 /* Are we ignoring a completed grace period? */
2995                 note_gp_changes(rsp, rdp);
2996
2997                 /* Start a new grace period if one not already started. */
2998                 if (!rcu_gp_in_progress(rsp)) {
2999                         struct rcu_node *rnp_root = rcu_get_root(rsp);
3000
3001                         raw_spin_lock(&rnp_root->lock);
3002                         smp_mb__after_unlock_lock();
3003                         needwake = rcu_start_gp(rsp);
3004                         raw_spin_unlock(&rnp_root->lock);
3005                         if (needwake)
3006                                 rcu_gp_kthread_wake(rsp);
3007                 } else {
3008                         /* Give the grace period a kick. */
3009                         rdp->blimit = LONG_MAX;
3010                         if (rsp->n_force_qs == rdp->n_force_qs_snap &&
3011                             *rdp->nxttail[RCU_DONE_TAIL] != head)
3012                                 force_quiescent_state(rsp);
3013                         rdp->n_force_qs_snap = rsp->n_force_qs;
3014                         rdp->qlen_last_fqs_check = rdp->qlen;
3015                 }
3016         }
3017 }
3018
3019 /*
3020  * RCU callback function to leak a callback.
3021  */
3022 static void rcu_leak_callback(struct rcu_head *rhp)
3023 {
3024 }
3025
3026 /*
3027  * Helper function for call_rcu() and friends.  The cpu argument will
3028  * normally be -1, indicating "currently running CPU".  It may specify
3029  * a CPU only if that CPU is a no-CBs CPU.  Currently, only _rcu_barrier()
3030  * is expected to specify a CPU.
3031  */
3032 static void
3033 __call_rcu(struct rcu_head *head, void (*func)(struct rcu_head *rcu),
3034            struct rcu_state *rsp, int cpu, bool lazy)
3035 {
3036         unsigned long flags;
3037         struct rcu_data *rdp;
3038
3039         WARN_ON_ONCE((unsigned long)head & 0x1); /* Misaligned rcu_head! */
3040         if (debug_rcu_head_queue(head)) {
3041                 /* Probable double call_rcu(), so leak the callback. */
3042                 WRITE_ONCE(head->func, rcu_leak_callback);
3043                 WARN_ONCE(1, "__call_rcu(): Leaked duplicate callback\n");
3044                 return;
3045         }
3046         head->func = func;
3047         head->next = NULL;
3048
3049         /*
3050          * Opportunistically note grace-period endings and beginnings.
3051          * Note that we might see a beginning right after we see an
3052          * end, but never vice versa, since this CPU has to pass through
3053          * a quiescent state betweentimes.
3054          */
3055         local_irq_save(flags);
3056         rdp = this_cpu_ptr(rsp->rda);
3057
3058         /* Add the callback to our list. */
3059         if (unlikely(rdp->nxttail[RCU_NEXT_TAIL] == NULL) || cpu != -1) {
3060                 int offline;
3061
3062                 if (cpu != -1)
3063                         rdp = per_cpu_ptr(rsp->rda, cpu);
3064                 if (likely(rdp->mynode)) {
3065                         /* Post-boot, so this should be for a no-CBs CPU. */
3066                         offline = !__call_rcu_nocb(rdp, head, lazy, flags);
3067                         WARN_ON_ONCE(offline);
3068                         /* Offline CPU, _call_rcu() illegal, leak callback.  */
3069                         local_irq_restore(flags);
3070                         return;
3071                 }
3072                 /*
3073                  * Very early boot, before rcu_init().  Initialize if needed
3074                  * and then drop through to queue the callback.
3075                  */
3076                 BUG_ON(cpu != -1);
3077                 WARN_ON_ONCE(!rcu_is_watching());
3078                 if (!likely(rdp->nxtlist))
3079                         init_default_callback_list(rdp);
3080         }
3081         WRITE_ONCE(rdp->qlen, rdp->qlen + 1);
3082         if (lazy)
3083                 rdp->qlen_lazy++;
3084         else
3085                 rcu_idle_count_callbacks_posted();
3086         smp_mb();  /* Count before adding callback for rcu_barrier(). */
3087         *rdp->nxttail[RCU_NEXT_TAIL] = head;
3088         rdp->nxttail[RCU_NEXT_TAIL] = &head->next;
3089
3090         if (__is_kfree_rcu_offset((unsigned long)func))
3091                 trace_rcu_kfree_callback(rsp->name, head, (unsigned long)func,
3092                                          rdp->qlen_lazy, rdp->qlen);
3093         else
3094                 trace_rcu_callback(rsp->name, head, rdp->qlen_lazy, rdp->qlen);
3095
3096         /* Go handle any RCU core processing required. */
3097         __call_rcu_core(rsp, rdp, head, flags);
3098         local_irq_restore(flags);
3099 }
3100
3101 /*
3102  * Queue an RCU-sched callback for invocation after a grace period.
3103  */
3104 void call_rcu_sched(struct rcu_head *head, void (*func)(struct rcu_head *rcu))
3105 {
3106         __call_rcu(head, func, &rcu_sched_state, -1, 0);
3107 }
3108 EXPORT_SYMBOL_GPL(call_rcu_sched);
3109
3110 /*
3111  * Queue an RCU callback for invocation after a quicker grace period.
3112  */
3113 void call_rcu_bh(struct rcu_head *head, void (*func)(struct rcu_head *rcu))
3114 {
3115         __call_rcu(head, func, &rcu_bh_state, -1, 0);
3116 }
3117 EXPORT_SYMBOL_GPL(call_rcu_bh);
3118
3119 /*
3120  * Queue an RCU callback for lazy invocation after a grace period.
3121  * This will likely be later named something like "call_rcu_lazy()",
3122  * but this change will require some way of tagging the lazy RCU
3123  * callbacks in the list of pending callbacks. Until then, this
3124  * function may only be called from __kfree_rcu().
3125  */
3126 void kfree_call_rcu(struct rcu_head *head,
3127                     void (*func)(struct rcu_head *rcu))
3128 {
3129         __call_rcu(head, func, rcu_state_p, -1, 1);
3130 }
3131 EXPORT_SYMBOL_GPL(kfree_call_rcu);
3132
3133 /*
3134  * Because a context switch is a grace period for RCU-sched and RCU-bh,
3135  * any blocking grace-period wait automatically implies a grace period
3136  * if there is only one CPU online at any point time during execution
3137  * of either synchronize_sched() or synchronize_rcu_bh().  It is OK to
3138  * occasionally incorrectly indicate that there are multiple CPUs online
3139  * when there was in fact only one the whole time, as this just adds
3140  * some overhead: RCU still operates correctly.
3141  */
3142 static inline int rcu_blocking_is_gp(void)
3143 {
3144         int ret;
3145
3146         might_sleep();  /* Check for RCU read-side critical section. */
3147         preempt_disable();
3148         ret = num_online_cpus() <= 1;
3149         preempt_enable();
3150         return ret;
3151 }
3152
3153 /**
3154  * synchronize_sched - wait until an rcu-sched grace period has elapsed.
3155  *
3156  * Control will return to the caller some time after a full rcu-sched
3157  * grace period has elapsed, in other words after all currently executing
3158  * rcu-sched read-side critical sections have completed.   These read-side
3159  * critical sections are delimited by rcu_read_lock_sched() and
3160  * rcu_read_unlock_sched(), and may be nested.  Note that preempt_disable(),
3161  * local_irq_disable(), and so on may be used in place of
3162  * rcu_read_lock_sched().
3163  *
3164  * This means that all preempt_disable code sequences, including NMI and
3165  * non-threaded hardware-interrupt handlers, in progress on entry will
3166  * have completed before this primitive returns.  However, this does not
3167  * guarantee that softirq handlers will have completed, since in some
3168  * kernels, these handlers can run in process context, and can block.
3169  *
3170  * Note that this guarantee implies further memory-ordering guarantees.
3171  * On systems with more than one CPU, when synchronize_sched() returns,
3172  * each CPU is guaranteed to have executed a full memory barrier since the
3173  * end of its last RCU-sched read-side critical section whose beginning
3174  * preceded the call to synchronize_sched().  In addition, each CPU having
3175  * an RCU read-side critical section that extends beyond the return from
3176  * synchronize_sched() is guaranteed to have executed a full memory barrier
3177  * after the beginning of synchronize_sched() and before the beginning of
3178  * that RCU read-side critical section.  Note that these guarantees include
3179  * CPUs that are offline, idle, or executing in user mode, as well as CPUs
3180  * that are executing in the kernel.
3181  *
3182  * Furthermore, if CPU A invoked synchronize_sched(), which returned
3183  * to its caller on CPU B, then both CPU A and CPU B are guaranteed
3184  * to have executed a full memory barrier during the execution of
3185  * synchronize_sched() -- even if CPU A and CPU B are the same CPU (but
3186  * again only if the system has more than one CPU).
3187  *
3188  * This primitive provides the guarantees made by the (now removed)
3189  * synchronize_kernel() API.  In contrast, synchronize_rcu() only
3190  * guarantees that rcu_read_lock() sections will have completed.
3191  * In "classic RCU", these two guarantees happen to be one and
3192  * the same, but can differ in realtime RCU implementations.
3193  */
3194 void synchronize_sched(void)
3195 {
3196         RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map) ||
3197                          lock_is_held(&rcu_lock_map) ||
3198                          lock_is_held(&rcu_sched_lock_map),
3199                          "Illegal synchronize_sched() in RCU-sched read-side critical section");
3200         if (rcu_blocking_is_gp())
3201                 return;
3202         if (rcu_gp_is_expedited())
3203                 synchronize_sched_expedited();
3204         else
3205                 wait_rcu_gp(call_rcu_sched);
3206 }
3207 EXPORT_SYMBOL_GPL(synchronize_sched);
3208
3209 /**
3210  * synchronize_rcu_bh - wait until an rcu_bh grace period has elapsed.
3211  *
3212  * Control will return to the caller some time after a full rcu_bh grace
3213  * period has elapsed, in other words after all currently executing rcu_bh
3214  * read-side critical sections have completed.  RCU read-side critical
3215  * sections are delimited by rcu_read_lock_bh() and rcu_read_unlock_bh(),
3216  * and may be nested.
3217  *
3218  * See the description of synchronize_sched() for more detailed information
3219  * on memory ordering guarantees.
3220  */
3221 void synchronize_rcu_bh(void)
3222 {
3223         RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map) ||
3224                          lock_is_held(&rcu_lock_map) ||
3225                          lock_is_held(&rcu_sched_lock_map),
3226                          "Illegal synchronize_rcu_bh() in RCU-bh read-side critical section");
3227         if (rcu_blocking_is_gp())
3228                 return;
3229         if (rcu_gp_is_expedited())
3230                 synchronize_rcu_bh_expedited();
3231         else
3232                 wait_rcu_gp(call_rcu_bh);
3233 }
3234 EXPORT_SYMBOL_GPL(synchronize_rcu_bh);
3235
3236 /**
3237  * get_state_synchronize_rcu - Snapshot current RCU state
3238  *
3239  * Returns a cookie that is used by a later call to cond_synchronize_rcu()
3240  * to determine whether or not a full grace period has elapsed in the
3241  * meantime.
3242  */
3243 unsigned long get_state_synchronize_rcu(void)
3244 {
3245         /*
3246          * Any prior manipulation of RCU-protected data must happen
3247          * before the load from ->gpnum.
3248          */
3249         smp_mb();  /* ^^^ */
3250
3251         /*
3252          * Make sure this load happens before the purportedly
3253          * time-consuming work between get_state_synchronize_rcu()
3254          * and cond_synchronize_rcu().
3255          */
3256         return smp_load_acquire(&rcu_state_p->gpnum);
3257 }
3258 EXPORT_SYMBOL_GPL(get_state_synchronize_rcu);
3259
3260 /**
3261  * cond_synchronize_rcu - Conditionally wait for an RCU grace period
3262  *
3263  * @oldstate: return value from earlier call to get_state_synchronize_rcu()
3264  *
3265  * If a full RCU grace period has elapsed since the earlier call to
3266  * get_state_synchronize_rcu(), just return.  Otherwise, invoke
3267  * synchronize_rcu() to wait for a full grace period.
3268  *
3269  * Yes, this function does not take counter wrap into account.  But
3270  * counter wrap is harmless.  If the counter wraps, we have waited for
3271  * more than 2 billion grace periods (and way more on a 64-bit system!),
3272  * so waiting for one additional grace period should be just fine.
3273  */
3274 void cond_synchronize_rcu(unsigned long oldstate)
3275 {
3276         unsigned long newstate;
3277
3278         /*
3279          * Ensure that this load happens before any RCU-destructive
3280          * actions the caller might carry out after we return.
3281          */
3282         newstate = smp_load_acquire(&rcu_state_p->completed);
3283         if (ULONG_CMP_GE(oldstate, newstate))
3284                 synchronize_rcu();
3285 }
3286 EXPORT_SYMBOL_GPL(cond_synchronize_rcu);
3287
3288 /**
3289  * get_state_synchronize_sched - Snapshot current RCU-sched state
3290  *
3291  * Returns a cookie that is used by a later call to cond_synchronize_sched()
3292  * to determine whether or not a full grace period has elapsed in the
3293  * meantime.
3294  */
3295 unsigned long get_state_synchronize_sched(void)
3296 {
3297         /*
3298          * Any prior manipulation of RCU-protected data must happen
3299          * before the load from ->gpnum.
3300          */
3301         smp_mb();  /* ^^^ */
3302
3303         /*
3304          * Make sure this load happens before the purportedly
3305          * time-consuming work between get_state_synchronize_sched()
3306          * and cond_synchronize_sched().
3307          */
3308         return smp_load_acquire(&rcu_sched_state.gpnum);
3309 }
3310 EXPORT_SYMBOL_GPL(get_state_synchronize_sched);
3311
3312 /**
3313  * cond_synchronize_sched - Conditionally wait for an RCU-sched grace period
3314  *
3315  * @oldstate: return value from earlier call to get_state_synchronize_sched()
3316  *
3317  * If a full RCU-sched grace period has elapsed since the earlier call to
3318  * get_state_synchronize_sched(), just return.  Otherwise, invoke
3319  * synchronize_sched() to wait for a full grace period.
3320  *
3321  * Yes, this function does not take counter wrap into account.  But
3322  * counter wrap is harmless.  If the counter wraps, we have waited for
3323  * more than 2 billion grace periods (and way more on a 64-bit system!),
3324  * so waiting for one additional grace period should be just fine.
3325  */
3326 void cond_synchronize_sched(unsigned long oldstate)
3327 {
3328         unsigned long newstate;
3329
3330         /*
3331          * Ensure that this load happens before any RCU-destructive
3332          * actions the caller might carry out after we return.
3333          */
3334         newstate = smp_load_acquire(&rcu_sched_state.completed);
3335         if (ULONG_CMP_GE(oldstate, newstate))
3336                 synchronize_sched();
3337 }
3338 EXPORT_SYMBOL_GPL(cond_synchronize_sched);
3339
3340 /* Adjust sequence number for start of update-side operation. */
3341 static void rcu_seq_start(unsigned long *sp)
3342 {
3343         WRITE_ONCE(*sp, *sp + 1);
3344         smp_mb(); /* Ensure update-side operation after counter increment. */
3345         WARN_ON_ONCE(!(*sp & 0x1));
3346 }
3347
3348 /* Adjust sequence number for end of update-side operation. */
3349 static void rcu_seq_end(unsigned long *sp)
3350 {
3351         smp_mb(); /* Ensure update-side operation before counter increment. */
3352         WRITE_ONCE(*sp, *sp + 1);
3353         WARN_ON_ONCE(*sp & 0x1);
3354 }
3355
3356 /* Take a snapshot of the update side's sequence number. */
3357 static unsigned long rcu_seq_snap(unsigned long *sp)
3358 {
3359         unsigned long s;
3360
3361         smp_mb(); /* Caller's modifications seen first by other CPUs. */
3362         s = (READ_ONCE(*sp) + 3) & ~0x1;
3363         smp_mb(); /* Above access must not bleed into critical section. */
3364         return s;
3365 }
3366
3367 /*
3368  * Given a snapshot from rcu_seq_snap(), determine whether or not a
3369  * full update-side operation has occurred.
3370  */
3371 static bool rcu_seq_done(unsigned long *sp, unsigned long s)
3372 {
3373         return ULONG_CMP_GE(READ_ONCE(*sp), s);
3374 }
3375
3376 /* Wrapper functions for expedited grace periods.  */
3377 static void rcu_exp_gp_seq_start(struct rcu_state *rsp)
3378 {
3379         rcu_seq_start(&rsp->expedited_sequence);
3380 }
3381 static void rcu_exp_gp_seq_end(struct rcu_state *rsp)
3382 {
3383         rcu_seq_end(&rsp->expedited_sequence);
3384         smp_mb(); /* Ensure that consecutive grace periods serialize. */
3385 }
3386 static unsigned long rcu_exp_gp_seq_snap(struct rcu_state *rsp)
3387 {
3388         return rcu_seq_snap(&rsp->expedited_sequence);
3389 }
3390 static bool rcu_exp_gp_seq_done(struct rcu_state *rsp, unsigned long s)
3391 {
3392         return rcu_seq_done(&rsp->expedited_sequence, s);
3393 }
3394
3395 /*
3396  * Reset the ->expmaskinit values in the rcu_node tree to reflect any
3397  * recent CPU-online activity.  Note that these masks are not cleared
3398  * when CPUs go offline, so they reflect the union of all CPUs that have
3399  * ever been online.  This means that this function normally takes its
3400  * no-work-to-do fastpath.
3401  */
3402 static void sync_exp_reset_tree_hotplug(struct rcu_state *rsp)
3403 {
3404         bool done;
3405         unsigned long flags;
3406         unsigned long mask;
3407         unsigned long oldmask;
3408         int ncpus = READ_ONCE(rsp->ncpus);
3409         struct rcu_node *rnp;
3410         struct rcu_node *rnp_up;
3411
3412         /* If no new CPUs onlined since last time, nothing to do. */
3413         if (likely(ncpus == rsp->ncpus_snap))
3414                 return;
3415         rsp->ncpus_snap = ncpus;
3416
3417         /*
3418          * Each pass through the following loop propagates newly onlined
3419          * CPUs for the current rcu_node structure up the rcu_node tree.
3420          */
3421         rcu_for_each_leaf_node(rsp, rnp) {
3422                 raw_spin_lock_irqsave(&rnp->lock, flags);
3423                 smp_mb__after_unlock_lock();
3424                 if (rnp->expmaskinit == rnp->expmaskinitnext) {
3425                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
3426                         continue;  /* No new CPUs, nothing to do. */
3427                 }
3428
3429                 /* Update this node's mask, track old value for propagation. */
3430                 oldmask = rnp->expmaskinit;
3431                 rnp->expmaskinit = rnp->expmaskinitnext;
3432                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3433
3434                 /* If was already nonzero, nothing to propagate. */
3435                 if (oldmask)
3436                         continue;
3437
3438                 /* Propagate the new CPU up the tree. */
3439                 mask = rnp->grpmask;
3440                 rnp_up = rnp->parent;
3441                 done = false;
3442                 while (rnp_up) {
3443                         raw_spin_lock_irqsave(&rnp_up->lock, flags);
3444                         smp_mb__after_unlock_lock();
3445                         if (rnp_up->expmaskinit)
3446                                 done = true;
3447                         rnp_up->expmaskinit |= mask;
3448                         raw_spin_unlock_irqrestore(&rnp_up->lock, flags);
3449                         if (done)
3450                                 break;
3451                         mask = rnp_up->grpmask;
3452                         rnp_up = rnp_up->parent;
3453                 }
3454         }
3455 }
3456
3457 /*
3458  * Reset the ->expmask values in the rcu_node tree in preparation for
3459  * a new expedited grace period.
3460  */
3461 static void __maybe_unused sync_exp_reset_tree(struct rcu_state *rsp)
3462 {
3463         unsigned long flags;
3464         struct rcu_node *rnp;
3465
3466         sync_exp_reset_tree_hotplug(rsp);
3467         rcu_for_each_node_breadth_first(rsp, rnp) {
3468                 raw_spin_lock_irqsave(&rnp->lock, flags);
3469                 smp_mb__after_unlock_lock();
3470                 WARN_ON_ONCE(rnp->expmask);
3471                 rnp->expmask = rnp->expmaskinit;
3472                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3473         }
3474 }
3475
3476 /*
3477  * Return non-zero if there is no RCU expedited grace period in progress
3478  * for the specified rcu_node structure, in other words, if all CPUs and
3479  * tasks covered by the specified rcu_node structure have done their bit
3480  * for the current expedited grace period.  Works only for preemptible
3481  * RCU -- other RCU implementation use other means.
3482  *
3483  * Caller must hold the root rcu_node's exp_funnel_mutex.
3484  */
3485 static int sync_rcu_preempt_exp_done(struct rcu_node *rnp)
3486 {
3487         return rnp->exp_tasks == NULL &&
3488                READ_ONCE(rnp->expmask) == 0;
3489 }
3490
3491 /*
3492  * Report the exit from RCU read-side critical section for the last task
3493  * that queued itself during or before the current expedited preemptible-RCU
3494  * grace period.  This event is reported either to the rcu_node structure on
3495  * which the task was queued or to one of that rcu_node structure's ancestors,
3496  * recursively up the tree.  (Calm down, calm down, we do the recursion
3497  * iteratively!)
3498  *
3499  * Caller must hold the root rcu_node's exp_funnel_mutex and the
3500  * specified rcu_node structure's ->lock.
3501  */
3502 static void __rcu_report_exp_rnp(struct rcu_state *rsp, struct rcu_node *rnp,
3503                                  bool wake, unsigned long flags)
3504         __releases(rnp->lock)
3505 {
3506         unsigned long mask;
3507
3508         for (;;) {
3509                 if (!sync_rcu_preempt_exp_done(rnp)) {
3510                         if (!rnp->expmask)
3511                                 rcu_initiate_boost(rnp, flags);
3512                         else
3513                                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3514                         break;
3515                 }
3516                 if (rnp->parent == NULL) {
3517                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
3518                         if (wake) {
3519                                 smp_mb(); /* EGP done before wake_up(). */
3520                                 wake_up(&rsp->expedited_wq);
3521                         }
3522                         break;
3523                 }
3524                 mask = rnp->grpmask;
3525                 raw_spin_unlock(&rnp->lock); /* irqs remain disabled */
3526                 rnp = rnp->parent;
3527                 raw_spin_lock(&rnp->lock); /* irqs already disabled */
3528                 smp_mb__after_unlock_lock();
3529                 WARN_ON_ONCE(!(rnp->expmask & mask));
3530                 rnp->expmask &= ~mask;
3531         }
3532 }
3533
3534 /*
3535  * Report expedited quiescent state for specified node.  This is a
3536  * lock-acquisition wrapper function for __rcu_report_exp_rnp().
3537  *
3538  * Caller must hold the root rcu_node's exp_funnel_mutex.
3539  */
3540 static void __maybe_unused rcu_report_exp_rnp(struct rcu_state *rsp,
3541                                               struct rcu_node *rnp, bool wake)
3542 {
3543         unsigned long flags;
3544
3545         raw_spin_lock_irqsave(&rnp->lock, flags);
3546         smp_mb__after_unlock_lock();
3547         __rcu_report_exp_rnp(rsp, rnp, wake, flags);
3548 }
3549
3550 /*
3551  * Report expedited quiescent state for multiple CPUs, all covered by the
3552  * specified leaf rcu_node structure.  Caller must hold the root
3553  * rcu_node's exp_funnel_mutex.
3554  */
3555 static void rcu_report_exp_cpu_mult(struct rcu_state *rsp, struct rcu_node *rnp,
3556                                     unsigned long mask, bool wake)
3557 {
3558         unsigned long flags;
3559
3560         raw_spin_lock_irqsave(&rnp->lock, flags);
3561         smp_mb__after_unlock_lock();
3562         if (!(rnp->expmask & mask)) {
3563                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3564                 return;
3565         }
3566         rnp->expmask &= ~mask;
3567         __rcu_report_exp_rnp(rsp, rnp, wake, flags); /* Releases rnp->lock. */
3568 }
3569
3570 /*
3571  * Report expedited quiescent state for specified rcu_data (CPU).
3572  * Caller must hold the root rcu_node's exp_funnel_mutex.
3573  */
3574 static void rcu_report_exp_rdp(struct rcu_state *rsp, struct rcu_data *rdp,
3575                                bool wake)
3576 {
3577         rcu_report_exp_cpu_mult(rsp, rdp->mynode, rdp->grpmask, wake);
3578 }
3579
3580 /* Common code for synchronize_{rcu,sched}_expedited() work-done checking. */
3581 static bool sync_exp_work_done(struct rcu_state *rsp, struct rcu_node *rnp,
3582                                struct rcu_data *rdp,
3583                                atomic_long_t *stat, unsigned long s)
3584 {
3585         if (rcu_exp_gp_seq_done(rsp, s)) {
3586                 if (rnp)
3587                         mutex_unlock(&rnp->exp_funnel_mutex);
3588                 else if (rdp)
3589                         mutex_unlock(&rdp->exp_funnel_mutex);
3590                 /* Ensure test happens before caller kfree(). */
3591                 smp_mb__before_atomic(); /* ^^^ */
3592                 atomic_long_inc(stat);
3593                 return true;
3594         }
3595         return false;
3596 }
3597
3598 /*
3599  * Funnel-lock acquisition for expedited grace periods.  Returns a
3600  * pointer to the root rcu_node structure, or NULL if some other
3601  * task did the expedited grace period for us.
3602  */
3603 static struct rcu_node *exp_funnel_lock(struct rcu_state *rsp, unsigned long s)
3604 {
3605         struct rcu_data *rdp;
3606         struct rcu_node *rnp0;
3607         struct rcu_node *rnp1 = NULL;
3608
3609         /*
3610          * First try directly acquiring the root lock in order to reduce
3611          * latency in the common case where expedited grace periods are
3612          * rare.  We check mutex_is_locked() to avoid pathological levels of
3613          * memory contention on ->exp_funnel_mutex in the heavy-load case.
3614          */
3615         rnp0 = rcu_get_root(rsp);
3616         if (!mutex_is_locked(&rnp0->exp_funnel_mutex)) {
3617                 if (mutex_trylock(&rnp0->exp_funnel_mutex)) {
3618                         if (sync_exp_work_done(rsp, rnp0, NULL,
3619                                                &rsp->expedited_workdone0, s))
3620                                 return NULL;
3621                         return rnp0;
3622                 }
3623         }
3624
3625         /*
3626          * Each pass through the following loop works its way
3627          * up the rcu_node tree, returning if others have done the
3628          * work or otherwise falls through holding the root rnp's
3629          * ->exp_funnel_mutex.  The mapping from CPU to rcu_node structure
3630          * can be inexact, as it is just promoting locality and is not
3631          * strictly needed for correctness.
3632          */
3633         rdp = per_cpu_ptr(rsp->rda, raw_smp_processor_id());
3634         if (sync_exp_work_done(rsp, NULL, NULL, &rsp->expedited_workdone1, s))
3635                 return NULL;
3636         mutex_lock(&rdp->exp_funnel_mutex);
3637         rnp0 = rdp->mynode;
3638         for (; rnp0 != NULL; rnp0 = rnp0->parent) {
3639                 if (sync_exp_work_done(rsp, rnp1, rdp,
3640                                        &rsp->expedited_workdone2, s))
3641                         return NULL;
3642                 mutex_lock(&rnp0->exp_funnel_mutex);
3643                 if (rnp1)
3644                         mutex_unlock(&rnp1->exp_funnel_mutex);
3645                 else
3646                         mutex_unlock(&rdp->exp_funnel_mutex);
3647                 rnp1 = rnp0;
3648         }
3649         if (sync_exp_work_done(rsp, rnp1, rdp,
3650                                &rsp->expedited_workdone3, s))
3651                 return NULL;
3652         return rnp1;
3653 }
3654
3655 /* Invoked on each online non-idle CPU for expedited quiescent state. */
3656 static void sync_sched_exp_handler(void *data)
3657 {
3658         struct rcu_data *rdp;
3659         struct rcu_node *rnp;
3660         struct rcu_state *rsp = data;
3661
3662         rdp = this_cpu_ptr(rsp->rda);
3663         rnp = rdp->mynode;
3664         if (!(READ_ONCE(rnp->expmask) & rdp->grpmask) ||
3665             __this_cpu_read(rcu_sched_data.cpu_no_qs.b.exp))
3666                 return;
3667         __this_cpu_write(rcu_sched_data.cpu_no_qs.b.exp, true);
3668         resched_cpu(smp_processor_id());
3669 }
3670
3671 /* Send IPI for expedited cleanup if needed at end of CPU-hotplug operation. */
3672 static void sync_sched_exp_online_cleanup(int cpu)
3673 {
3674         struct rcu_data *rdp;
3675         int ret;
3676         struct rcu_node *rnp;
3677         struct rcu_state *rsp = &rcu_sched_state;
3678
3679         rdp = per_cpu_ptr(rsp->rda, cpu);
3680         rnp = rdp->mynode;
3681         if (!(READ_ONCE(rnp->expmask) & rdp->grpmask))
3682                 return;
3683         ret = smp_call_function_single(cpu, sync_sched_exp_handler, rsp, 0);
3684         WARN_ON_ONCE(ret);
3685 }
3686
3687 /*
3688  * Select the nodes that the upcoming expedited grace period needs
3689  * to wait for.
3690  */
3691 static void sync_rcu_exp_select_cpus(struct rcu_state *rsp,
3692                                      smp_call_func_t func)
3693 {
3694         int cpu;
3695         unsigned long flags;
3696         unsigned long mask;
3697         unsigned long mask_ofl_test;
3698         unsigned long mask_ofl_ipi;
3699         int ret;
3700         struct rcu_node *rnp;
3701
3702         sync_exp_reset_tree(rsp);
3703         rcu_for_each_leaf_node(rsp, rnp) {
3704                 raw_spin_lock_irqsave(&rnp->lock, flags);
3705                 smp_mb__after_unlock_lock();
3706
3707                 /* Each pass checks a CPU for identity, offline, and idle. */
3708                 mask_ofl_test = 0;
3709                 for (cpu = rnp->grplo; cpu <= rnp->grphi; cpu++) {
3710                         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
3711                         struct rcu_dynticks *rdtp = &per_cpu(rcu_dynticks, cpu);
3712
3713                         if (raw_smp_processor_id() == cpu ||
3714                             !(atomic_add_return(0, &rdtp->dynticks) & 0x1))
3715                                 mask_ofl_test |= rdp->grpmask;
3716                 }
3717                 mask_ofl_ipi = rnp->expmask & ~mask_ofl_test;
3718
3719                 /*
3720                  * Need to wait for any blocked tasks as well.  Note that
3721                  * additional blocking tasks will also block the expedited
3722                  * GP until such time as the ->expmask bits are cleared.
3723                  */
3724                 if (rcu_preempt_has_tasks(rnp))
3725                         rnp->exp_tasks = rnp->blkd_tasks.next;
3726                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3727
3728                 /* IPI the remaining CPUs for expedited quiescent state. */
3729                 mask = 1;
3730                 for (cpu = rnp->grplo; cpu <= rnp->grphi; cpu++, mask <<= 1) {
3731                         if (!(mask_ofl_ipi & mask))
3732                                 continue;
3733 retry_ipi:
3734                         ret = smp_call_function_single(cpu, func, rsp, 0);
3735                         if (!ret) {
3736                                 mask_ofl_ipi &= ~mask;
3737                         } else {
3738                                 /* Failed, raced with offline. */
3739                                 raw_spin_lock_irqsave(&rnp->lock, flags);
3740                                 if (cpu_online(cpu) &&
3741                                     (rnp->expmask & mask)) {
3742                                         raw_spin_unlock_irqrestore(&rnp->lock,
3743                                                                    flags);
3744                                         schedule_timeout_uninterruptible(1);
3745                                         if (cpu_online(cpu) &&
3746                                             (rnp->expmask & mask))
3747                                                 goto retry_ipi;
3748                                         raw_spin_lock_irqsave(&rnp->lock,
3749                                                               flags);
3750                                 }
3751                                 if (!(rnp->expmask & mask))
3752                                         mask_ofl_ipi &= ~mask;
3753                                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3754                         }
3755                 }
3756                 /* Report quiescent states for those that went offline. */
3757                 mask_ofl_test |= mask_ofl_ipi;
3758                 if (mask_ofl_test)
3759                         rcu_report_exp_cpu_mult(rsp, rnp, mask_ofl_test, false);
3760         }
3761 }
3762
3763 static void synchronize_sched_expedited_wait(struct rcu_state *rsp)
3764 {
3765         int cpu;
3766         unsigned long jiffies_stall;
3767         unsigned long jiffies_start;
3768         unsigned long mask;
3769         struct rcu_node *rnp;
3770         struct rcu_node *rnp_root = rcu_get_root(rsp);
3771         int ret;
3772
3773         jiffies_stall = rcu_jiffies_till_stall_check();
3774         jiffies_start = jiffies;
3775
3776         for (;;) {
3777                 ret = wait_event_interruptible_timeout(
3778                                 rsp->expedited_wq,
3779                                 sync_rcu_preempt_exp_done(rnp_root),
3780                                 jiffies_stall);
3781                 if (ret > 0)
3782                         return;
3783                 if (ret < 0) {
3784                         /* Hit a signal, disable CPU stall warnings. */
3785                         wait_event(rsp->expedited_wq,
3786                                    sync_rcu_preempt_exp_done(rnp_root));
3787                         return;
3788                 }
3789                 pr_err("INFO: %s detected expedited stalls on CPUs/tasks: {",
3790                        rsp->name);
3791                 rcu_for_each_leaf_node(rsp, rnp) {
3792                         (void)rcu_print_task_exp_stall(rnp);
3793                         mask = 1;
3794                         for (cpu = rnp->grplo; cpu <= rnp->grphi; cpu++, mask <<= 1) {
3795                                 struct rcu_data *rdp;
3796
3797                                 if (!(rnp->expmask & mask))
3798                                         continue;
3799                                 rdp = per_cpu_ptr(rsp->rda, cpu);
3800                                 pr_cont(" %d-%c%c%c", cpu,
3801                                         "O."[cpu_online(cpu)],
3802                                         "o."[!!(rdp->grpmask & rnp->expmaskinit)],
3803                                         "N."[!!(rdp->grpmask & rnp->expmaskinitnext)]);
3804                         }
3805                         mask <<= 1;
3806                 }
3807                 pr_cont(" } %lu jiffies s: %lu\n",
3808                         jiffies - jiffies_start, rsp->expedited_sequence);
3809                 rcu_for_each_leaf_node(rsp, rnp) {
3810                         mask = 1;
3811                         for (cpu = rnp->grplo; cpu <= rnp->grphi; cpu++, mask <<= 1) {
3812                                 if (!(rnp->expmask & mask))
3813                                         continue;
3814                                 dump_cpu_task(cpu);
3815                         }
3816                 }
3817                 jiffies_stall = 3 * rcu_jiffies_till_stall_check() + 3;
3818         }
3819 }
3820
3821 /**
3822  * synchronize_sched_expedited - Brute-force RCU-sched grace period
3823  *
3824  * Wait for an RCU-sched grace period to elapse, but use a "big hammer"
3825  * approach to force the grace period to end quickly.  This consumes
3826  * significant time on all CPUs and is unfriendly to real-time workloads,
3827  * so is thus not recommended for any sort of common-case code.  In fact,
3828  * if you are using synchronize_sched_expedited() in a loop, please
3829  * restructure your code to batch your updates, and then use a single
3830  * synchronize_sched() instead.
3831  *
3832  * This implementation can be thought of as an application of sequence
3833  * locking to expedited grace periods, but using the sequence counter to
3834  * determine when someone else has already done the work instead of for
3835  * retrying readers.
3836  */
3837 void synchronize_sched_expedited(void)
3838 {
3839         unsigned long s;
3840         struct rcu_node *rnp;
3841         struct rcu_state *rsp = &rcu_sched_state;
3842
3843         /* Take a snapshot of the sequence number.  */
3844         s = rcu_exp_gp_seq_snap(rsp);
3845
3846         rnp = exp_funnel_lock(rsp, s);
3847         if (rnp == NULL)
3848                 return;  /* Someone else did our work for us. */
3849
3850         rcu_exp_gp_seq_start(rsp);
3851         sync_rcu_exp_select_cpus(rsp, sync_sched_exp_handler);
3852         synchronize_sched_expedited_wait(rsp);
3853
3854         rcu_exp_gp_seq_end(rsp);
3855         mutex_unlock(&rnp->exp_funnel_mutex);
3856 }
3857 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
3858
3859 /*
3860  * Check to see if there is any immediate RCU-related work to be done
3861  * by the current CPU, for the specified type of RCU, returning 1 if so.
3862  * The checks are in order of increasing expense: checks that can be
3863  * carried out against CPU-local state are performed first.  However,
3864  * we must check for CPU stalls first, else we might not get a chance.
3865  */
3866 static int __rcu_pending(struct rcu_state *rsp, struct rcu_data *rdp)
3867 {
3868         struct rcu_node *rnp = rdp->mynode;
3869
3870         rdp->n_rcu_pending++;
3871
3872         /* Check for CPU stalls, if enabled. */
3873         check_cpu_stall(rsp, rdp);
3874
3875         /* Is this CPU a NO_HZ_FULL CPU that should ignore RCU? */
3876         if (rcu_nohz_full_cpu(rsp))
3877                 return 0;
3878
3879         /* Is the RCU core waiting for a quiescent state from this CPU? */
3880         if (rcu_scheduler_fully_active &&
3881             rdp->core_needs_qs && rdp->cpu_no_qs.b.norm &&
3882             rdp->rcu_qs_ctr_snap == __this_cpu_read(rcu_qs_ctr)) {
3883                 rdp->n_rp_core_needs_qs++;
3884         } else if (rdp->core_needs_qs &&
3885                    (!rdp->cpu_no_qs.b.norm ||
3886                     rdp->rcu_qs_ctr_snap != __this_cpu_read(rcu_qs_ctr))) {
3887                 rdp->n_rp_report_qs++;
3888                 return 1;
3889         }
3890
3891         /* Does this CPU have callbacks ready to invoke? */
3892         if (cpu_has_callbacks_ready_to_invoke(rdp)) {
3893                 rdp->n_rp_cb_ready++;
3894                 return 1;
3895         }
3896
3897         /* Has RCU gone idle with this CPU needing another grace period? */
3898         if (cpu_needs_another_gp(rsp, rdp)) {
3899                 rdp->n_rp_cpu_needs_gp++;
3900                 return 1;
3901         }
3902
3903         /* Has another RCU grace period completed?  */
3904         if (READ_ONCE(rnp->completed) != rdp->completed) { /* outside lock */
3905                 rdp->n_rp_gp_completed++;
3906                 return 1;
3907         }
3908
3909         /* Has a new RCU grace period started? */
3910         if (READ_ONCE(rnp->gpnum) != rdp->gpnum ||
3911             unlikely(READ_ONCE(rdp->gpwrap))) { /* outside lock */
3912                 rdp->n_rp_gp_started++;
3913                 return 1;
3914         }
3915
3916         /* Does this CPU need a deferred NOCB wakeup? */
3917         if (rcu_nocb_need_deferred_wakeup(rdp)) {
3918                 rdp->n_rp_nocb_defer_wakeup++;
3919                 return 1;
3920         }
3921
3922         /* nothing to do */
3923         rdp->n_rp_need_nothing++;
3924         return 0;
3925 }
3926
3927 /*
3928  * Check to see if there is any immediate RCU-related work to be done
3929  * by the current CPU, returning 1 if so.  This function is part of the
3930  * RCU implementation; it is -not- an exported member of the RCU API.
3931  */
3932 static int rcu_pending(void)
3933 {
3934         struct rcu_state *rsp;
3935
3936         for_each_rcu_flavor(rsp)
3937                 if (__rcu_pending(rsp, this_cpu_ptr(rsp->rda)))
3938                         return 1;
3939         return 0;
3940 }
3941
3942 /*
3943  * Return true if the specified CPU has any callback.  If all_lazy is
3944  * non-NULL, store an indication of whether all callbacks are lazy.
3945  * (If there are no callbacks, all of them are deemed to be lazy.)
3946  */
3947 static bool __maybe_unused rcu_cpu_has_callbacks(bool *all_lazy)
3948 {
3949         bool al = true;
3950         bool hc = false;
3951         struct rcu_data *rdp;
3952         struct rcu_state *rsp;
3953
3954         for_each_rcu_flavor(rsp) {
3955                 rdp = this_cpu_ptr(rsp->rda);
3956                 if (!rdp->nxtlist)
3957                         continue;
3958                 hc = true;
3959                 if (rdp->qlen != rdp->qlen_lazy || !all_lazy) {
3960                         al = false;
3961                         break;
3962                 }
3963         }
3964         if (all_lazy)
3965                 *all_lazy = al;
3966         return hc;
3967 }
3968
3969 /*
3970  * Helper function for _rcu_barrier() tracing.  If tracing is disabled,
3971  * the compiler is expected to optimize this away.
3972  */
3973 static void _rcu_barrier_trace(struct rcu_state *rsp, const char *s,
3974                                int cpu, unsigned long done)
3975 {
3976         trace_rcu_barrier(rsp->name, s, cpu,
3977                           atomic_read(&rsp->barrier_cpu_count), done);
3978 }
3979
3980 /*
3981  * RCU callback function for _rcu_barrier().  If we are last, wake
3982  * up the task executing _rcu_barrier().
3983  */
3984 static void rcu_barrier_callback(struct rcu_head *rhp)
3985 {
3986         struct rcu_data *rdp = container_of(rhp, struct rcu_data, barrier_head);
3987         struct rcu_state *rsp = rdp->rsp;
3988
3989         if (atomic_dec_and_test(&rsp->barrier_cpu_count)) {
3990                 _rcu_barrier_trace(rsp, "LastCB", -1, rsp->barrier_sequence);
3991                 complete(&rsp->barrier_completion);
3992         } else {
3993                 _rcu_barrier_trace(rsp, "CB", -1, rsp->barrier_sequence);
3994         }
3995 }
3996
3997 /*
3998  * Called with preemption disabled, and from cross-cpu IRQ context.
3999  */
4000 static void rcu_barrier_func(void *type)
4001 {
4002         struct rcu_state *rsp = type;
4003         struct rcu_data *rdp = raw_cpu_ptr(rsp->rda);
4004
4005         _rcu_barrier_trace(rsp, "IRQ", -1, rsp->barrier_sequence);
4006         atomic_inc(&rsp->barrier_cpu_count);
4007         rsp->call(&rdp->barrier_head, rcu_barrier_callback);
4008 }
4009
4010 /*
4011  * Orchestrate the specified type of RCU barrier, waiting for all
4012  * RCU callbacks of the specified type to complete.
4013  */
4014 static void _rcu_barrier(struct rcu_state *rsp)
4015 {
4016         int cpu;
4017         struct rcu_data *rdp;
4018         unsigned long s = rcu_seq_snap(&rsp->barrier_sequence);
4019
4020         _rcu_barrier_trace(rsp, "Begin", -1, s);
4021
4022         /* Take mutex to serialize concurrent rcu_barrier() requests. */
4023         mutex_lock(&rsp->barrier_mutex);
4024
4025         /* Did someone else do our work for us? */
4026         if (rcu_seq_done(&rsp->barrier_sequence, s)) {
4027                 _rcu_barrier_trace(rsp, "EarlyExit", -1, rsp->barrier_sequence);
4028                 smp_mb(); /* caller's subsequent code after above check. */
4029                 mutex_unlock(&rsp->barrier_mutex);
4030                 return;
4031         }
4032
4033         /* Mark the start of the barrier operation. */
4034         rcu_seq_start(&rsp->barrier_sequence);
4035         _rcu_barrier_trace(rsp, "Inc1", -1, rsp->barrier_sequence);
4036
4037         /*
4038          * Initialize the count to one rather than to zero in order to
4039          * avoid a too-soon return to zero in case of a short grace period
4040          * (or preemption of this task).  Exclude CPU-hotplug operations
4041          * to ensure that no offline CPU has callbacks queued.
4042          */
4043         init_completion(&rsp->barrier_completion);
4044         atomic_set(&rsp->barrier_cpu_count, 1);
4045         get_online_cpus();
4046
4047         /*
4048          * Force each CPU with callbacks to register a new callback.
4049          * When that callback is invoked, we will know that all of the
4050          * corresponding CPU's preceding callbacks have been invoked.
4051          */
4052         for_each_possible_cpu(cpu) {
4053                 if (!cpu_online(cpu) && !rcu_is_nocb_cpu(cpu))
4054                         continue;
4055                 rdp = per_cpu_ptr(rsp->rda, cpu);
4056                 if (rcu_is_nocb_cpu(cpu)) {
4057                         if (!rcu_nocb_cpu_needs_barrier(rsp, cpu)) {
4058                                 _rcu_barrier_trace(rsp, "OfflineNoCB", cpu,
4059                                                    rsp->barrier_sequence);
4060                         } else {
4061                                 _rcu_barrier_trace(rsp, "OnlineNoCB", cpu,
4062                                                    rsp->barrier_sequence);
4063                                 smp_mb__before_atomic();
4064                                 atomic_inc(&rsp->barrier_cpu_count);
4065                                 __call_rcu(&rdp->barrier_head,
4066                                            rcu_barrier_callback, rsp, cpu, 0);
4067                         }
4068                 } else if (READ_ONCE(rdp->qlen)) {
4069                         _rcu_barrier_trace(rsp, "OnlineQ", cpu,
4070                                            rsp->barrier_sequence);
4071                         smp_call_function_single(cpu, rcu_barrier_func, rsp, 1);
4072                 } else {
4073                         _rcu_barrier_trace(rsp, "OnlineNQ", cpu,
4074                                            rsp->barrier_sequence);
4075                 }
4076         }
4077         put_online_cpus();
4078
4079         /*
4080          * Now that we have an rcu_barrier_callback() callback on each
4081          * CPU, and thus each counted, remove the initial count.
4082          */
4083         if (atomic_dec_and_test(&rsp->barrier_cpu_count))
4084                 complete(&rsp->barrier_completion);
4085
4086         /* Wait for all rcu_barrier_callback() callbacks to be invoked. */
4087         wait_for_completion(&rsp->barrier_completion);
4088
4089         /* Mark the end of the barrier operation. */
4090         _rcu_barrier_trace(rsp, "Inc2", -1, rsp->barrier_sequence);
4091         rcu_seq_end(&rsp->barrier_sequence);
4092
4093         /* Other rcu_barrier() invocations can now safely proceed. */
4094         mutex_unlock(&rsp->barrier_mutex);
4095 }
4096
4097 /**
4098  * rcu_barrier_bh - Wait until all in-flight call_rcu_bh() callbacks complete.
4099  */
4100 void rcu_barrier_bh(void)
4101 {
4102         _rcu_barrier(&rcu_bh_state);
4103 }
4104 EXPORT_SYMBOL_GPL(rcu_barrier_bh);
4105
4106 /**
4107  * rcu_barrier_sched - Wait for in-flight call_rcu_sched() callbacks.
4108  */
4109 void rcu_barrier_sched(void)
4110 {
4111         _rcu_barrier(&rcu_sched_state);
4112 }
4113 EXPORT_SYMBOL_GPL(rcu_barrier_sched);
4114
4115 /*
4116  * Propagate ->qsinitmask bits up the rcu_node tree to account for the
4117  * first CPU in a given leaf rcu_node structure coming online.  The caller
4118  * must hold the corresponding leaf rcu_node ->lock with interrrupts
4119  * disabled.
4120  */
4121 static void rcu_init_new_rnp(struct rcu_node *rnp_leaf)
4122 {
4123         long mask;
4124         struct rcu_node *rnp = rnp_leaf;
4125
4126         for (;;) {
4127                 mask = rnp->grpmask;
4128                 rnp = rnp->parent;
4129                 if (rnp == NULL)
4130                         return;
4131                 raw_spin_lock(&rnp->lock); /* Interrupts already disabled. */
4132                 rnp->qsmaskinit |= mask;
4133                 raw_spin_unlock(&rnp->lock); /* Interrupts remain disabled. */
4134         }
4135 }
4136
4137 /*
4138  * Do boot-time initialization of a CPU's per-CPU RCU data.
4139  */
4140 static void __init
4141 rcu_boot_init_percpu_data(int cpu, struct rcu_state *rsp)
4142 {
4143         unsigned long flags;
4144         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
4145         struct rcu_node *rnp = rcu_get_root(rsp);
4146
4147         /* Set up local state, ensuring consistent view of global state. */
4148         raw_spin_lock_irqsave(&rnp->lock, flags);
4149         rdp->grpmask = 1UL << (cpu - rdp->mynode->grplo);
4150         rdp->dynticks = &per_cpu(rcu_dynticks, cpu);
4151         WARN_ON_ONCE(rdp->dynticks->dynticks_nesting != DYNTICK_TASK_EXIT_IDLE);
4152         WARN_ON_ONCE(atomic_read(&rdp->dynticks->dynticks) != 1);
4153         rdp->cpu = cpu;
4154         rdp->rsp = rsp;
4155         mutex_init(&rdp->exp_funnel_mutex);
4156         rcu_boot_init_nocb_percpu_data(rdp);
4157         raw_spin_unlock_irqrestore(&rnp->lock, flags);
4158 }
4159
4160 /*
4161  * Initialize a CPU's per-CPU RCU data.  Note that only one online or
4162  * offline event can be happening at a given time.  Note also that we
4163  * can accept some slop in the rsp->completed access due to the fact
4164  * that this CPU cannot possibly have any RCU callbacks in flight yet.
4165  */
4166 static void
4167 rcu_init_percpu_data(int cpu, struct rcu_state *rsp)
4168 {
4169         unsigned long flags;
4170         unsigned long mask;
4171         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
4172         struct rcu_node *rnp = rcu_get_root(rsp);
4173
4174         /* Set up local state, ensuring consistent view of global state. */
4175         raw_spin_lock_irqsave(&rnp->lock, flags);
4176         rdp->qlen_last_fqs_check = 0;
4177         rdp->n_force_qs_snap = rsp->n_force_qs;
4178         rdp->blimit = blimit;
4179         if (!rdp->nxtlist)
4180                 init_callback_list(rdp);  /* Re-enable callbacks on this CPU. */
4181         rdp->dynticks->dynticks_nesting = DYNTICK_TASK_EXIT_IDLE;
4182         rcu_sysidle_init_percpu_data(rdp->dynticks);
4183         atomic_set(&rdp->dynticks->dynticks,
4184                    (atomic_read(&rdp->dynticks->dynticks) & ~0x1) + 1);
4185         raw_spin_unlock(&rnp->lock);            /* irqs remain disabled. */
4186
4187         /*
4188          * Add CPU to leaf rcu_node pending-online bitmask.  Any needed
4189          * propagation up the rcu_node tree will happen at the beginning
4190          * of the next grace period.
4191          */
4192         rnp = rdp->mynode;
4193         mask = rdp->grpmask;
4194         raw_spin_lock(&rnp->lock);              /* irqs already disabled. */
4195         smp_mb__after_unlock_lock();
4196         rnp->qsmaskinitnext |= mask;
4197         rnp->expmaskinitnext |= mask;
4198         if (!rdp->beenonline)
4199                 WRITE_ONCE(rsp->ncpus, READ_ONCE(rsp->ncpus) + 1);
4200         rdp->beenonline = true;  /* We have now been online. */
4201         rdp->gpnum = rnp->completed; /* Make CPU later note any new GP. */
4202         rdp->completed = rnp->completed;
4203         rdp->cpu_no_qs.b.norm = true;
4204         rdp->rcu_qs_ctr_snap = per_cpu(rcu_qs_ctr, cpu);
4205         rdp->core_needs_qs = false;
4206         trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("cpuonl"));
4207         raw_spin_unlock_irqrestore(&rnp->lock, flags);
4208 }
4209
4210 static void rcu_prepare_cpu(int cpu)
4211 {
4212         struct rcu_state *rsp;
4213
4214         for_each_rcu_flavor(rsp)
4215                 rcu_init_percpu_data(cpu, rsp);
4216 }
4217
4218 /*
4219  * Handle CPU online/offline notification events.
4220  */
4221 int rcu_cpu_notify(struct notifier_block *self,
4222                    unsigned long action, void *hcpu)
4223 {
4224         long cpu = (long)hcpu;
4225         struct rcu_data *rdp = per_cpu_ptr(rcu_state_p->rda, cpu);
4226         struct rcu_node *rnp = rdp->mynode;
4227         struct rcu_state *rsp;
4228
4229         switch (action) {
4230         case CPU_UP_PREPARE:
4231         case CPU_UP_PREPARE_FROZEN:
4232                 rcu_prepare_cpu(cpu);
4233                 rcu_prepare_kthreads(cpu);
4234                 rcu_spawn_all_nocb_kthreads(cpu);
4235                 break;
4236         case CPU_ONLINE:
4237         case CPU_DOWN_FAILED:
4238                 sync_sched_exp_online_cleanup(cpu);
4239                 rcu_boost_kthread_setaffinity(rnp, -1);
4240                 break;
4241         case CPU_DOWN_PREPARE:
4242                 rcu_boost_kthread_setaffinity(rnp, cpu);
4243                 break;
4244         case CPU_DYING:
4245         case CPU_DYING_FROZEN:
4246                 for_each_rcu_flavor(rsp)
4247                         rcu_cleanup_dying_cpu(rsp);
4248                 break;
4249         case CPU_DYING_IDLE:
4250                 /* QS for any half-done expedited RCU-sched GP. */
4251                 preempt_disable();
4252                 rcu_report_exp_rdp(&rcu_sched_state,
4253                                    this_cpu_ptr(rcu_sched_state.rda), true);
4254                 preempt_enable();
4255
4256                 for_each_rcu_flavor(rsp) {
4257                         rcu_cleanup_dying_idle_cpu(cpu, rsp);
4258                 }
4259                 break;
4260         case CPU_DEAD:
4261         case CPU_DEAD_FROZEN:
4262         case CPU_UP_CANCELED:
4263         case CPU_UP_CANCELED_FROZEN:
4264                 for_each_rcu_flavor(rsp) {
4265                         rcu_cleanup_dead_cpu(cpu, rsp);
4266                         do_nocb_deferred_wakeup(per_cpu_ptr(rsp->rda, cpu));
4267                 }
4268                 break;
4269         default:
4270                 break;
4271         }
4272         return NOTIFY_OK;
4273 }
4274
4275 static int rcu_pm_notify(struct notifier_block *self,
4276                          unsigned long action, void *hcpu)
4277 {
4278         switch (action) {
4279         case PM_HIBERNATION_PREPARE:
4280         case PM_SUSPEND_PREPARE:
4281                 if (nr_cpu_ids <= 256) /* Expediting bad for large systems. */
4282                         rcu_expedite_gp();
4283                 break;
4284         case PM_POST_HIBERNATION:
4285         case PM_POST_SUSPEND:
4286                 if (nr_cpu_ids <= 256) /* Expediting bad for large systems. */
4287                         rcu_unexpedite_gp();
4288                 break;
4289         default:
4290                 break;
4291         }
4292         return NOTIFY_OK;
4293 }
4294
4295 /*
4296  * Spawn the kthreads that handle each RCU flavor's grace periods.
4297  */
4298 static int __init rcu_spawn_gp_kthread(void)
4299 {
4300         unsigned long flags;
4301         int kthread_prio_in = kthread_prio;
4302         struct rcu_node *rnp;
4303         struct rcu_state *rsp;
4304         struct sched_param sp;
4305         struct task_struct *t;
4306
4307         /* Force priority into range. */
4308         if (IS_ENABLED(CONFIG_RCU_BOOST) && kthread_prio < 1)
4309                 kthread_prio = 1;
4310         else if (kthread_prio < 0)
4311                 kthread_prio = 0;
4312         else if (kthread_prio > 99)
4313                 kthread_prio = 99;
4314         if (kthread_prio != kthread_prio_in)
4315                 pr_alert("rcu_spawn_gp_kthread(): Limited prio to %d from %d\n",
4316                          kthread_prio, kthread_prio_in);
4317
4318         rcu_scheduler_fully_active = 1;
4319         for_each_rcu_flavor(rsp) {
4320                 t = kthread_create(rcu_gp_kthread, rsp, "%s", rsp->name);
4321                 BUG_ON(IS_ERR(t));
4322                 rnp = rcu_get_root(rsp);
4323                 raw_spin_lock_irqsave(&rnp->lock, flags);
4324                 rsp->gp_kthread = t;
4325                 if (kthread_prio) {
4326                         sp.sched_priority = kthread_prio;
4327                         sched_setscheduler_nocheck(t, SCHED_FIFO, &sp);
4328                 }
4329                 wake_up_process(t);
4330                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
4331         }
4332         rcu_spawn_nocb_kthreads();
4333         rcu_spawn_boost_kthreads();
4334         return 0;
4335 }
4336 early_initcall(rcu_spawn_gp_kthread);
4337
4338 /*
4339  * This function is invoked towards the end of the scheduler's initialization
4340  * process.  Before this is called, the idle task might contain
4341  * RCU read-side critical sections (during which time, this idle
4342  * task is booting the system).  After this function is called, the
4343  * idle tasks are prohibited from containing RCU read-side critical
4344  * sections.  This function also enables RCU lockdep checking.
4345  */
4346 void rcu_scheduler_starting(void)
4347 {
4348         WARN_ON(num_online_cpus() != 1);
4349         WARN_ON(nr_context_switches() > 0);
4350         rcu_scheduler_active = 1;
4351 }
4352
4353 /*
4354  * Compute the per-level fanout, either using the exact fanout specified
4355  * or balancing the tree, depending on the rcu_fanout_exact boot parameter.
4356  */
4357 static void __init rcu_init_levelspread(int *levelspread, const int *levelcnt)
4358 {
4359         int i;
4360
4361         if (rcu_fanout_exact) {
4362                 levelspread[rcu_num_lvls - 1] = rcu_fanout_leaf;
4363                 for (i = rcu_num_lvls - 2; i >= 0; i--)
4364                         levelspread[i] = RCU_FANOUT;
4365         } else {
4366                 int ccur;
4367                 int cprv;
4368
4369                 cprv = nr_cpu_ids;
4370                 for (i = rcu_num_lvls - 1; i >= 0; i--) {
4371                         ccur = levelcnt[i];
4372                         levelspread[i] = (cprv + ccur - 1) / ccur;
4373                         cprv = ccur;
4374                 }
4375         }
4376 }
4377
4378 /*
4379  * Helper function for rcu_init() that initializes one rcu_state structure.
4380  */
4381 static void __init rcu_init_one(struct rcu_state *rsp,
4382                 struct rcu_data __percpu *rda)
4383 {
4384         static const char * const buf[] = RCU_NODE_NAME_INIT;
4385         static const char * const fqs[] = RCU_FQS_NAME_INIT;
4386         static const char * const exp[] = RCU_EXP_NAME_INIT;
4387         static u8 fl_mask = 0x1;
4388
4389         int levelcnt[RCU_NUM_LVLS];             /* # nodes in each level. */
4390         int levelspread[RCU_NUM_LVLS];          /* kids/node in each level. */
4391         int cpustride = 1;
4392         int i;
4393         int j;
4394         struct rcu_node *rnp;
4395
4396         BUILD_BUG_ON(RCU_NUM_LVLS > ARRAY_SIZE(buf));  /* Fix buf[] init! */
4397
4398         /* Silence gcc 4.8 false positive about array index out of range. */
4399         if (rcu_num_lvls <= 0 || rcu_num_lvls > RCU_NUM_LVLS)
4400                 panic("rcu_init_one: rcu_num_lvls out of range");
4401
4402         /* Initialize the level-tracking arrays. */
4403
4404         for (i = 0; i < rcu_num_lvls; i++)
4405                 levelcnt[i] = num_rcu_lvl[i];
4406         for (i = 1; i < rcu_num_lvls; i++)
4407                 rsp->level[i] = rsp->level[i - 1] + levelcnt[i - 1];
4408         rcu_init_levelspread(levelspread, levelcnt);
4409         rsp->flavor_mask = fl_mask;
4410         fl_mask <<= 1;
4411
4412         /* Initialize the elements themselves, starting from the leaves. */
4413
4414         for (i = rcu_num_lvls - 1; i >= 0; i--) {
4415                 cpustride *= levelspread[i];
4416                 rnp = rsp->level[i];
4417                 for (j = 0; j < levelcnt[i]; j++, rnp++) {
4418                         raw_spin_lock_init(&rnp->lock);
4419                         lockdep_set_class_and_name(&rnp->lock,
4420                                                    &rcu_node_class[i], buf[i]);
4421                         raw_spin_lock_init(&rnp->fqslock);
4422                         lockdep_set_class_and_name(&rnp->fqslock,
4423                                                    &rcu_fqs_class[i], fqs[i]);
4424                         rnp->gpnum = rsp->gpnum;
4425                         rnp->completed = rsp->completed;
4426                         rnp->qsmask = 0;
4427                         rnp->qsmaskinit = 0;
4428                         rnp->grplo = j * cpustride;
4429                         rnp->grphi = (j + 1) * cpustride - 1;
4430                         if (rnp->grphi >= nr_cpu_ids)
4431                                 rnp->grphi = nr_cpu_ids - 1;
4432                         if (i == 0) {
4433                                 rnp->grpnum = 0;
4434                                 rnp->grpmask = 0;
4435                                 rnp->parent = NULL;
4436                         } else {
4437                                 rnp->grpnum = j % levelspread[i - 1];
4438                                 rnp->grpmask = 1UL << rnp->grpnum;
4439                                 rnp->parent = rsp->level[i - 1] +
4440                                               j / levelspread[i - 1];
4441                         }
4442                         rnp->level = i;
4443                         INIT_LIST_HEAD(&rnp->blkd_tasks);
4444                         rcu_init_one_nocb(rnp);
4445                         mutex_init(&rnp->exp_funnel_mutex);
4446                         lockdep_set_class_and_name(&rnp->exp_funnel_mutex,
4447                                                    &rcu_exp_class[i], exp[i]);
4448                 }
4449         }
4450
4451         init_waitqueue_head(&rsp->gp_wq);
4452         init_waitqueue_head(&rsp->expedited_wq);
4453         rnp = rsp->level[rcu_num_lvls - 1];
4454         for_each_possible_cpu(i) {
4455                 while (i > rnp->grphi)
4456                         rnp++;
4457                 per_cpu_ptr(rsp->rda, i)->mynode = rnp;
4458                 rcu_boot_init_percpu_data(i, rsp);
4459         }
4460         list_add(&rsp->flavors, &rcu_struct_flavors);
4461 }
4462
4463 /*
4464  * Compute the rcu_node tree geometry from kernel parameters.  This cannot
4465  * replace the definitions in tree.h because those are needed to size
4466  * the ->node array in the rcu_state structure.
4467  */
4468 static void __init rcu_init_geometry(void)
4469 {
4470         ulong d;
4471         int i;
4472         int rcu_capacity[RCU_NUM_LVLS];
4473
4474         /*
4475          * Initialize any unspecified boot parameters.
4476          * The default values of jiffies_till_first_fqs and
4477          * jiffies_till_next_fqs are set to the RCU_JIFFIES_TILL_FORCE_QS
4478          * value, which is a function of HZ, then adding one for each
4479          * RCU_JIFFIES_FQS_DIV CPUs that might be on the system.
4480          */
4481         d = RCU_JIFFIES_TILL_FORCE_QS + nr_cpu_ids / RCU_JIFFIES_FQS_DIV;
4482         if (jiffies_till_first_fqs == ULONG_MAX)
4483                 jiffies_till_first_fqs = d;
4484         if (jiffies_till_next_fqs == ULONG_MAX)
4485                 jiffies_till_next_fqs = d;
4486
4487         /* If the compile-time values are accurate, just leave. */
4488         if (rcu_fanout_leaf == RCU_FANOUT_LEAF &&
4489             nr_cpu_ids == NR_CPUS)
4490                 return;
4491         pr_info("RCU: Adjusting geometry for rcu_fanout_leaf=%d, nr_cpu_ids=%d\n",
4492                 rcu_fanout_leaf, nr_cpu_ids);
4493
4494         /*
4495          * The boot-time rcu_fanout_leaf parameter is only permitted
4496          * to increase the leaf-level fanout, not decrease it.  Of course,
4497          * the leaf-level fanout cannot exceed the number of bits in
4498          * the rcu_node masks.  Complain and fall back to the compile-
4499          * time values if these limits are exceeded.
4500          */
4501         if (rcu_fanout_leaf < RCU_FANOUT_LEAF ||
4502             rcu_fanout_leaf > sizeof(unsigned long) * 8) {
4503                 rcu_fanout_leaf = RCU_FANOUT_LEAF;
4504                 WARN_ON(1);
4505                 return;
4506         }
4507
4508         /*
4509          * Compute number of nodes that can be handled an rcu_node tree
4510          * with the given number of levels.
4511          */
4512         rcu_capacity[0] = rcu_fanout_leaf;
4513         for (i = 1; i < RCU_NUM_LVLS; i++)
4514                 rcu_capacity[i] = rcu_capacity[i - 1] * RCU_FANOUT;
4515
4516         /*
4517          * The tree must be able to accommodate the configured number of CPUs.
4518          * If this limit is exceeded than we have a serious problem elsewhere.
4519          */
4520         if (nr_cpu_ids > rcu_capacity[RCU_NUM_LVLS - 1])
4521                 panic("rcu_init_geometry: rcu_capacity[] is too small");
4522
4523         /* Calculate the number of levels in the tree. */
4524         for (i = 0; nr_cpu_ids > rcu_capacity[i]; i++) {
4525         }
4526         rcu_num_lvls = i + 1;
4527
4528         /* Calculate the number of rcu_nodes at each level of the tree. */
4529         for (i = 0; i < rcu_num_lvls; i++) {
4530                 int cap = rcu_capacity[(rcu_num_lvls - 1) - i];
4531                 num_rcu_lvl[i] = DIV_ROUND_UP(nr_cpu_ids, cap);
4532         }
4533
4534         /* Calculate the total number of rcu_node structures. */
4535         rcu_num_nodes = 0;
4536         for (i = 0; i < rcu_num_lvls; i++)
4537                 rcu_num_nodes += num_rcu_lvl[i];
4538 }
4539
4540 /*
4541  * Dump out the structure of the rcu_node combining tree associated
4542  * with the rcu_state structure referenced by rsp.
4543  */
4544 static void __init rcu_dump_rcu_node_tree(struct rcu_state *rsp)
4545 {
4546         int level = 0;
4547         struct rcu_node *rnp;
4548
4549         pr_info("rcu_node tree layout dump\n");
4550         pr_info(" ");
4551         rcu_for_each_node_breadth_first(rsp, rnp) {
4552                 if (rnp->level != level) {
4553                         pr_cont("\n");
4554                         pr_info(" ");
4555                         level = rnp->level;
4556                 }
4557                 pr_cont("%d:%d ^%d  ", rnp->grplo, rnp->grphi, rnp->grpnum);
4558         }
4559         pr_cont("\n");
4560 }
4561
4562 void __init rcu_init(void)
4563 {
4564         int cpu;
4565
4566         rcu_early_boot_tests();
4567
4568         rcu_bootup_announce();
4569         rcu_init_geometry();
4570         rcu_init_one(&rcu_bh_state, &rcu_bh_data);
4571         rcu_init_one(&rcu_sched_state, &rcu_sched_data);
4572         if (dump_tree)
4573                 rcu_dump_rcu_node_tree(&rcu_sched_state);
4574         __rcu_init_preempt();
4575         open_softirq(RCU_SOFTIRQ, rcu_process_callbacks);
4576
4577         /*
4578          * We don't need protection against CPU-hotplug here because
4579          * this is called early in boot, before either interrupts
4580          * or the scheduler are operational.
4581          */
4582         cpu_notifier(rcu_cpu_notify, 0);
4583         pm_notifier(rcu_pm_notify, 0);
4584         for_each_online_cpu(cpu)
4585                 rcu_cpu_notify(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
4586 }
4587
4588 #include "tree_plugin.h"