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