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