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