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