xref: /linux/kernel/rcu/tree.c (revision 056a5087d87ead77dedbe9cf5bde53b7cd4b4651)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Read-Copy Update mechanism for mutual exclusion (tree-based version)
4  *
5  * Copyright IBM Corporation, 2008
6  *
7  * Authors: Dipankar Sarma <dipankar@in.ibm.com>
8  *	    Manfred Spraul <manfred@colorfullife.com>
9  *	    Paul E. McKenney <paulmck@linux.ibm.com>
10  *
11  * Based on the original work by Paul McKenney <paulmck@linux.ibm.com>
12  * and inputs from Rusty Russell, Andrea Arcangeli and Andi Kleen.
13  *
14  * For detailed explanation of Read-Copy Update mechanism see -
15  *	Documentation/RCU
16  */
17 
18 #define pr_fmt(fmt) "rcu: " fmt
19 
20 #include <linux/types.h>
21 #include <linux/kernel.h>
22 #include <linux/init.h>
23 #include <linux/spinlock.h>
24 #include <linux/smp.h>
25 #include <linux/rcupdate_wait.h>
26 #include <linux/interrupt.h>
27 #include <linux/sched.h>
28 #include <linux/sched/debug.h>
29 #include <linux/nmi.h>
30 #include <linux/atomic.h>
31 #include <linux/bitops.h>
32 #include <linux/export.h>
33 #include <linux/completion.h>
34 #include <linux/kmemleak.h>
35 #include <linux/moduleparam.h>
36 #include <linux/panic.h>
37 #include <linux/panic_notifier.h>
38 #include <linux/percpu.h>
39 #include <linux/notifier.h>
40 #include <linux/cpu.h>
41 #include <linux/mutex.h>
42 #include <linux/time.h>
43 #include <linux/kernel_stat.h>
44 #include <linux/wait.h>
45 #include <linux/kthread.h>
46 #include <uapi/linux/sched/types.h>
47 #include <linux/prefetch.h>
48 #include <linux/delay.h>
49 #include <linux/random.h>
50 #include <linux/trace_events.h>
51 #include <linux/suspend.h>
52 #include <linux/ftrace.h>
53 #include <linux/tick.h>
54 #include <linux/sysrq.h>
55 #include <linux/kprobes.h>
56 #include <linux/gfp.h>
57 #include <linux/oom.h>
58 #include <linux/smpboot.h>
59 #include <linux/jiffies.h>
60 #include <linux/slab.h>
61 #include <linux/sched/isolation.h>
62 #include <linux/sched/clock.h>
63 #include <linux/vmalloc.h>
64 #include <linux/mm.h>
65 #include <linux/kasan.h>
66 #include <linux/context_tracking.h>
67 #include "../time/tick-internal.h"
68 
69 #include "tree.h"
70 #include "rcu.h"
71 
72 #ifdef MODULE_PARAM_PREFIX
73 #undef MODULE_PARAM_PREFIX
74 #endif
75 #define MODULE_PARAM_PREFIX "rcutree."
76 
77 /* Data structures. */
78 static void rcu_sr_normal_gp_cleanup_work(struct work_struct *);
79 
80 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rcu_data, rcu_data) = {
81 	.gpwrap = true,
82 };
83 
84 int rcu_get_gpwrap_count(int cpu)
85 {
86 	struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
87 
88 	return READ_ONCE(rdp->gpwrap_count);
89 }
90 EXPORT_SYMBOL_GPL(rcu_get_gpwrap_count);
91 
92 static struct rcu_state rcu_state = {
93 	.level = { &rcu_state.node[0] },
94 	.gp_state = RCU_GP_IDLE,
95 	.gp_seq = (0UL - 300UL) << RCU_SEQ_CTR_SHIFT,
96 	.barrier_mutex = __MUTEX_INITIALIZER(rcu_state.barrier_mutex),
97 	.barrier_lock = __RAW_SPIN_LOCK_UNLOCKED(rcu_state.barrier_lock),
98 	.name = RCU_NAME,
99 	.abbr = RCU_ABBR,
100 	.exp_mutex = __MUTEX_INITIALIZER(rcu_state.exp_mutex),
101 	.exp_wake_mutex = __MUTEX_INITIALIZER(rcu_state.exp_wake_mutex),
102 	.ofl_lock = __ARCH_SPIN_LOCK_UNLOCKED,
103 	.srs_cleanup_work = __WORK_INITIALIZER(rcu_state.srs_cleanup_work,
104 		rcu_sr_normal_gp_cleanup_work),
105 	.srs_cleanups_pending = ATOMIC_INIT(0),
106 #ifdef CONFIG_RCU_NOCB_CPU
107 	.nocb_mutex = __MUTEX_INITIALIZER(rcu_state.nocb_mutex),
108 #endif
109 };
110 
111 /* Dump rcu_node combining tree at boot to verify correct setup. */
112 static bool dump_tree;
113 module_param(dump_tree, bool, 0444);
114 /* By default, use RCU_SOFTIRQ instead of rcuc kthreads. */
115 static bool use_softirq = !IS_ENABLED(CONFIG_PREEMPT_RT);
116 #ifndef CONFIG_PREEMPT_RT
117 module_param(use_softirq, bool, 0444);
118 #endif
119 /* Control rcu_node-tree auto-balancing at boot time. */
120 static bool rcu_fanout_exact;
121 module_param(rcu_fanout_exact, bool, 0444);
122 /* Increase (but not decrease) the RCU_FANOUT_LEAF at boot time. */
123 static int rcu_fanout_leaf = RCU_FANOUT_LEAF;
124 module_param(rcu_fanout_leaf, int, 0444);
125 int rcu_num_lvls __read_mostly = RCU_NUM_LVLS;
126 /* Number of rcu_nodes at specified level. */
127 int num_rcu_lvl[] = NUM_RCU_LVL_INIT;
128 int rcu_num_nodes __read_mostly = NUM_RCU_NODES; /* Total # rcu_nodes in use. */
129 
130 /*
131  * The rcu_scheduler_active variable is initialized to the value
132  * RCU_SCHEDULER_INACTIVE and transitions RCU_SCHEDULER_INIT just before the
133  * first task is spawned.  So when this variable is RCU_SCHEDULER_INACTIVE,
134  * RCU can assume that there is but one task, allowing RCU to (for example)
135  * optimize synchronize_rcu() to a simple barrier().  When this variable
136  * is RCU_SCHEDULER_INIT, RCU must actually do all the hard work required
137  * to detect real grace periods.  This variable is also used to suppress
138  * boot-time false positives from lockdep-RCU error checking.  Finally, it
139  * transitions from RCU_SCHEDULER_INIT to RCU_SCHEDULER_RUNNING after RCU
140  * is fully initialized, including all of its kthreads having been spawned.
141  */
142 int rcu_scheduler_active __read_mostly;
143 EXPORT_SYMBOL_GPL(rcu_scheduler_active);
144 
145 /*
146  * The rcu_scheduler_fully_active variable transitions from zero to one
147  * during the early_initcall() processing, which is after the scheduler
148  * is capable of creating new tasks.  So RCU processing (for example,
149  * creating tasks for RCU priority boosting) must be delayed until after
150  * rcu_scheduler_fully_active transitions from zero to one.  We also
151  * currently delay invocation of any RCU callbacks until after this point.
152  *
153  * It might later prove better for people registering RCU callbacks during
154  * early boot to take responsibility for these callbacks, but one step at
155  * a time.
156  */
157 static int rcu_scheduler_fully_active __read_mostly;
158 
159 static void rcu_report_qs_rnp(unsigned long mask, struct rcu_node *rnp,
160 			      unsigned long gps, unsigned long flags);
161 static void invoke_rcu_core(void);
162 static void rcu_report_exp_rdp(struct rcu_data *rdp);
163 static void rcu_report_qs_rdp(struct rcu_data *rdp);
164 static void check_cb_ovld_locked(struct rcu_data *rdp, struct rcu_node *rnp);
165 static bool rcu_rdp_is_offloaded(struct rcu_data *rdp);
166 static bool rcu_rdp_cpu_online(struct rcu_data *rdp);
167 static bool rcu_init_invoked(void);
168 static void rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf);
169 static void rcu_init_new_rnp(struct rcu_node *rnp_leaf);
170 
171 /*
172  * rcuc/rcub/rcuop kthread realtime priority. The "rcuop"
173  * real-time priority(enabling/disabling) is controlled by
174  * the extra CONFIG_RCU_NOCB_CPU_CB_BOOST configuration.
175  */
176 static int kthread_prio = IS_ENABLED(CONFIG_RCU_BOOST) ? 1 : 0;
177 module_param(kthread_prio, int, 0444);
178 
179 /* Delay in jiffies for grace-period initialization delays, debug only. */
180 
181 static int gp_preinit_delay;
182 module_param(gp_preinit_delay, int, 0444);
183 static int gp_init_delay;
184 module_param(gp_init_delay, int, 0444);
185 static int gp_cleanup_delay;
186 module_param(gp_cleanup_delay, int, 0444);
187 static int nohz_full_patience_delay;
188 module_param(nohz_full_patience_delay, int, 0444);
189 static int nohz_full_patience_delay_jiffies;
190 
191 // Add delay to rcu_read_unlock() for strict grace periods.
192 static int rcu_unlock_delay;
193 #ifdef CONFIG_RCU_STRICT_GRACE_PERIOD
194 module_param(rcu_unlock_delay, int, 0444);
195 #endif
196 
197 /* Retrieve RCU kthreads priority for rcutorture */
198 int rcu_get_gp_kthreads_prio(void)
199 {
200 	return kthread_prio;
201 }
202 EXPORT_SYMBOL_GPL(rcu_get_gp_kthreads_prio);
203 
204 /*
205  * Number of grace periods between delays, normalized by the duration of
206  * the delay.  The longer the delay, the more the grace periods between
207  * each delay.  The reason for this normalization is that it means that,
208  * for non-zero delays, the overall slowdown of grace periods is constant
209  * regardless of the duration of the delay.  This arrangement balances
210  * the need for long delays to increase some race probabilities with the
211  * need for fast grace periods to increase other race probabilities.
212  */
213 #define PER_RCU_NODE_PERIOD 3	/* Number of grace periods between delays for debugging. */
214 
215 /*
216  * Return true if an RCU grace period is in progress.  The READ_ONCE()s
217  * permit this function to be invoked without holding the root rcu_node
218  * structure's ->lock, but of course results can be subject to change.
219  */
220 static int rcu_gp_in_progress(void)
221 {
222 	return rcu_seq_state(rcu_seq_current(&rcu_state.gp_seq));
223 }
224 
225 /*
226  * Return the number of callbacks queued on the specified CPU.
227  * Handles both the nocbs and normal cases.
228  */
229 static long rcu_get_n_cbs_cpu(int cpu)
230 {
231 	struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
232 
233 	if (rcu_segcblist_is_enabled(&rdp->cblist))
234 		return rcu_segcblist_n_cbs(&rdp->cblist);
235 	return 0;
236 }
237 
238 /**
239  * rcu_softirq_qs - Provide a set of RCU quiescent states in softirq processing
240  *
241  * Mark a quiescent state for RCU, Tasks RCU, and Tasks Trace RCU.
242  * This is a special-purpose function to be used in the softirq
243  * infrastructure and perhaps the occasional long-running softirq
244  * handler.
245  *
246  * Note that from RCU's viewpoint, a call to rcu_softirq_qs() is
247  * equivalent to momentarily completely enabling preemption.  For
248  * example, given this code::
249  *
250  *	local_bh_disable();
251  *	do_something();
252  *	rcu_softirq_qs();  // A
253  *	do_something_else();
254  *	local_bh_enable();  // B
255  *
256  * A call to synchronize_rcu() that began concurrently with the
257  * call to do_something() would be guaranteed to wait only until
258  * execution reached statement A.  Without that rcu_softirq_qs(),
259  * that same synchronize_rcu() would instead be guaranteed to wait
260  * until execution reached statement B.
261  */
262 void rcu_softirq_qs(void)
263 {
264 	RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map) ||
265 			 lock_is_held(&rcu_lock_map) ||
266 			 lock_is_held(&rcu_sched_lock_map),
267 			 "Illegal rcu_softirq_qs() in RCU read-side critical section");
268 	rcu_qs();
269 	rcu_preempt_deferred_qs(current);
270 	rcu_tasks_qs(current, false);
271 }
272 
273 /*
274  * Reset the current CPU's RCU_WATCHING counter to indicate that the
275  * newly onlined CPU is no longer in an extended quiescent state.
276  * This will either leave the counter unchanged, or increment it
277  * to the next non-quiescent value.
278  *
279  * The non-atomic test/increment sequence works because the upper bits
280  * of the ->state variable are manipulated only by the corresponding CPU,
281  * or when the corresponding CPU is offline.
282  */
283 static void rcu_watching_online(void)
284 {
285 	if (ct_rcu_watching() & CT_RCU_WATCHING)
286 		return;
287 	ct_state_inc(CT_RCU_WATCHING);
288 }
289 
290 /*
291  * Return true if the snapshot returned from ct_rcu_watching()
292  * indicates that RCU is in an extended quiescent state.
293  */
294 static bool rcu_watching_snap_in_eqs(int snap)
295 {
296 	return !(snap & CT_RCU_WATCHING);
297 }
298 
299 /**
300  * rcu_watching_snap_stopped_since() - Has RCU stopped watching a given CPU
301  * since the specified @snap?
302  *
303  * @rdp: The rcu_data corresponding to the CPU for which to check EQS.
304  * @snap: rcu_watching snapshot taken when the CPU wasn't in an EQS.
305  *
306  * Returns true if the CPU corresponding to @rdp has spent some time in an
307  * extended quiescent state since @snap. Note that this doesn't check if it
308  * /still/ is in an EQS, just that it went through one since @snap.
309  *
310  * This is meant to be used in a loop waiting for a CPU to go through an EQS.
311  */
312 static bool rcu_watching_snap_stopped_since(struct rcu_data *rdp, int snap)
313 {
314 	/*
315 	 * The first failing snapshot is already ordered against the accesses
316 	 * performed by the remote CPU after it exits idle.
317 	 *
318 	 * The second snapshot therefore only needs to order against accesses
319 	 * performed by the remote CPU prior to entering idle and therefore can
320 	 * rely solely on acquire semantics.
321 	 */
322 	if (WARN_ON_ONCE(rcu_watching_snap_in_eqs(snap)))
323 		return true;
324 
325 	return snap != ct_rcu_watching_cpu_acquire(rdp->cpu);
326 }
327 
328 /*
329  * Return true if the referenced integer is zero while the specified
330  * CPU remains within a single extended quiescent state.
331  */
332 bool rcu_watching_zero_in_eqs(int cpu, int *vp)
333 {
334 	int snap;
335 
336 	// If not quiescent, force back to earlier extended quiescent state.
337 	snap = ct_rcu_watching_cpu(cpu) & ~CT_RCU_WATCHING;
338 	smp_rmb(); // Order CT state and *vp reads.
339 	if (READ_ONCE(*vp))
340 		return false;  // Non-zero, so report failure;
341 	smp_rmb(); // Order *vp read and CT state re-read.
342 
343 	// If still in the same extended quiescent state, we are good!
344 	return snap == ct_rcu_watching_cpu(cpu);
345 }
346 
347 /*
348  * Let the RCU core know that this CPU has gone through the scheduler,
349  * which is a quiescent state.  This is called when the need for a
350  * quiescent state is urgent, so we burn an atomic operation and full
351  * memory barriers to let the RCU core know about it, regardless of what
352  * this CPU might (or might not) do in the near future.
353  *
354  * We inform the RCU core by emulating a zero-duration dyntick-idle period.
355  *
356  * The caller must have disabled interrupts and must not be idle.
357  */
358 notrace void rcu_momentary_eqs(void)
359 {
360 	int seq;
361 
362 	raw_cpu_write(rcu_data.rcu_need_heavy_qs, false);
363 	seq = ct_state_inc(2 * CT_RCU_WATCHING);
364 	/* It is illegal to call this from idle state. */
365 	WARN_ON_ONCE(!(seq & CT_RCU_WATCHING));
366 	rcu_preempt_deferred_qs(current);
367 }
368 EXPORT_SYMBOL_GPL(rcu_momentary_eqs);
369 
370 /**
371  * rcu_is_cpu_rrupt_from_idle - see if 'interrupted' from idle
372  *
373  * If the current CPU is idle and running at a first-level (not nested)
374  * interrupt, or directly, from idle, return true.
375  *
376  * The caller must have at least disabled IRQs.
377  */
378 static int rcu_is_cpu_rrupt_from_idle(void)
379 {
380 	long nmi_nesting = ct_nmi_nesting();
381 
382 	/*
383 	 * Usually called from the tick; but also used from smp_function_call()
384 	 * for expedited grace periods. This latter can result in running from
385 	 * the idle task, instead of an actual IPI.
386 	 */
387 	lockdep_assert_irqs_disabled();
388 
389 	/* Check for counter underflows */
390 	RCU_LOCKDEP_WARN(ct_nesting() < 0,
391 			 "RCU nesting counter underflow!");
392 
393 	/* Non-idle interrupt or nested idle interrupt */
394 	if (nmi_nesting > 1)
395 		return false;
396 
397 	/*
398 	 * Non nested idle interrupt (interrupting section where RCU
399 	 * wasn't watching).
400 	 */
401 	if (nmi_nesting == 1)
402 		return true;
403 
404 	/* Not in an interrupt */
405 	if (!nmi_nesting) {
406 		RCU_LOCKDEP_WARN(!in_task() || !is_idle_task(current),
407 				 "RCU nmi_nesting counter not in idle task!");
408 		return !rcu_is_watching_curr_cpu();
409 	}
410 
411 	RCU_LOCKDEP_WARN(1, "RCU nmi_nesting counter underflow/zero!");
412 
413 	return false;
414 }
415 
416 #define DEFAULT_RCU_BLIMIT (IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD) ? 1000 : 10)
417 				// Maximum callbacks per rcu_do_batch ...
418 #define DEFAULT_MAX_RCU_BLIMIT 10000 // ... even during callback flood.
419 static long blimit = DEFAULT_RCU_BLIMIT;
420 #define DEFAULT_RCU_QHIMARK 10000 // If this many pending, ignore blimit.
421 static long qhimark = DEFAULT_RCU_QHIMARK;
422 #define DEFAULT_RCU_QLOMARK 100   // Once only this many pending, use blimit.
423 static long qlowmark = DEFAULT_RCU_QLOMARK;
424 #define DEFAULT_RCU_QOVLD_MULT 2
425 #define DEFAULT_RCU_QOVLD (DEFAULT_RCU_QOVLD_MULT * DEFAULT_RCU_QHIMARK)
426 static long qovld = DEFAULT_RCU_QOVLD; // If this many pending, hammer QS.
427 static long qovld_calc = -1;	  // No pre-initialization lock acquisitions!
428 
429 module_param(blimit, long, 0444);
430 module_param(qhimark, long, 0444);
431 module_param(qlowmark, long, 0444);
432 module_param(qovld, long, 0444);
433 
434 static ulong jiffies_till_first_fqs = IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD) ? 0 : ULONG_MAX;
435 static ulong jiffies_till_next_fqs = ULONG_MAX;
436 static bool rcu_kick_kthreads;
437 static int rcu_divisor = 7;
438 module_param(rcu_divisor, int, 0644);
439 
440 /* Force an exit from rcu_do_batch() after 3 milliseconds. */
441 static long rcu_resched_ns = 3 * NSEC_PER_MSEC;
442 module_param(rcu_resched_ns, long, 0644);
443 
444 /*
445  * How long the grace period must be before we start recruiting
446  * quiescent-state help from rcu_note_context_switch().
447  */
448 static ulong jiffies_till_sched_qs = ULONG_MAX;
449 module_param(jiffies_till_sched_qs, ulong, 0444);
450 static ulong jiffies_to_sched_qs; /* See adjust_jiffies_till_sched_qs(). */
451 module_param(jiffies_to_sched_qs, ulong, 0444); /* Display only! */
452 
453 /*
454  * Make sure that we give the grace-period kthread time to detect any
455  * idle CPUs before taking active measures to force quiescent states.
456  * However, don't go below 100 milliseconds, adjusted upwards for really
457  * large systems.
458  */
459 static void adjust_jiffies_till_sched_qs(void)
460 {
461 	unsigned long j;
462 
463 	/* If jiffies_till_sched_qs was specified, respect the request. */
464 	if (jiffies_till_sched_qs != ULONG_MAX) {
465 		WRITE_ONCE(jiffies_to_sched_qs, jiffies_till_sched_qs);
466 		return;
467 	}
468 	/* Otherwise, set to third fqs scan, but bound below on large system. */
469 	j = READ_ONCE(jiffies_till_first_fqs) +
470 		      2 * READ_ONCE(jiffies_till_next_fqs);
471 	if (j < HZ / 10 + nr_cpu_ids / RCU_JIFFIES_FQS_DIV)
472 		j = HZ / 10 + nr_cpu_ids / RCU_JIFFIES_FQS_DIV;
473 	pr_info("RCU calculated value of scheduler-enlistment delay is %ld jiffies.\n", j);
474 	WRITE_ONCE(jiffies_to_sched_qs, j);
475 }
476 
477 static int param_set_first_fqs_jiffies(const char *val, const struct kernel_param *kp)
478 {
479 	ulong j;
480 	int ret = kstrtoul(val, 0, &j);
481 
482 	if (!ret) {
483 		WRITE_ONCE(*(ulong *)kp->arg, (j > HZ) ? HZ : j);
484 		adjust_jiffies_till_sched_qs();
485 	}
486 	return ret;
487 }
488 
489 static int param_set_next_fqs_jiffies(const char *val, const struct kernel_param *kp)
490 {
491 	ulong j;
492 	int ret = kstrtoul(val, 0, &j);
493 
494 	if (!ret) {
495 		WRITE_ONCE(*(ulong *)kp->arg, clamp_val(j, 1, HZ));
496 		adjust_jiffies_till_sched_qs();
497 	}
498 	return ret;
499 }
500 
501 static const struct kernel_param_ops first_fqs_jiffies_ops = {
502 	.set = param_set_first_fqs_jiffies,
503 	.get = param_get_ulong,
504 };
505 
506 static const struct kernel_param_ops next_fqs_jiffies_ops = {
507 	.set = param_set_next_fqs_jiffies,
508 	.get = param_get_ulong,
509 };
510 
511 module_param_cb(jiffies_till_first_fqs, &first_fqs_jiffies_ops, &jiffies_till_first_fqs, 0644);
512 module_param_cb(jiffies_till_next_fqs, &next_fqs_jiffies_ops, &jiffies_till_next_fqs, 0644);
513 module_param(rcu_kick_kthreads, bool, 0644);
514 
515 static void force_qs_rnp(int (*f)(struct rcu_data *rdp));
516 static int rcu_pending(int user);
517 
518 /*
519  * Return the number of RCU GPs completed thus far for debug & stats.
520  */
521 unsigned long rcu_get_gp_seq(void)
522 {
523 	return READ_ONCE(rcu_state.gp_seq);
524 }
525 EXPORT_SYMBOL_GPL(rcu_get_gp_seq);
526 
527 /*
528  * Return the number of RCU expedited batches completed thus far for
529  * debug & stats.  Odd numbers mean that a batch is in progress, even
530  * numbers mean idle.  The value returned will thus be roughly double
531  * the cumulative batches since boot.
532  */
533 unsigned long rcu_exp_batches_completed(void)
534 {
535 	return rcu_state.expedited_sequence;
536 }
537 EXPORT_SYMBOL_GPL(rcu_exp_batches_completed);
538 
539 /*
540  * Return the root node of the rcu_state structure.
541  */
542 static struct rcu_node *rcu_get_root(void)
543 {
544 	return &rcu_state.node[0];
545 }
546 
547 /*
548  * Send along grace-period-related data for rcutorture diagnostics.
549  */
550 void rcutorture_get_gp_data(int *flags, unsigned long *gp_seq)
551 {
552 	*flags = READ_ONCE(rcu_state.gp_flags);
553 	*gp_seq = rcu_seq_current(&rcu_state.gp_seq);
554 }
555 EXPORT_SYMBOL_GPL(rcutorture_get_gp_data);
556 
557 /* Gather grace-period sequence numbers for rcutorture diagnostics. */
558 unsigned long long rcutorture_gather_gp_seqs(void)
559 {
560 	return ((READ_ONCE(rcu_state.gp_seq) & 0xffffULL) << 40) |
561 	       ((READ_ONCE(rcu_state.expedited_sequence) & 0xffffffULL) << 16) |
562 	       (READ_ONCE(rcu_state.gp_seq_polled) & 0xffffULL);
563 }
564 EXPORT_SYMBOL_GPL(rcutorture_gather_gp_seqs);
565 
566 /* Format grace-period sequence numbers for rcutorture diagnostics. */
567 void rcutorture_format_gp_seqs(unsigned long long seqs, char *cp, size_t len)
568 {
569 	unsigned int egp = (seqs >> 16) & 0xffffffULL;
570 	unsigned int ggp = (seqs >> 40) & 0xffffULL;
571 	unsigned int pgp = seqs & 0xffffULL;
572 
573 	snprintf(cp, len, "g%04x:e%06x:p%04x", ggp, egp, pgp);
574 }
575 EXPORT_SYMBOL_GPL(rcutorture_format_gp_seqs);
576 
577 #if defined(CONFIG_NO_HZ_FULL) && (!defined(CONFIG_GENERIC_ENTRY) || !defined(CONFIG_VIRT_XFER_TO_GUEST_WORK))
578 /*
579  * An empty function that will trigger a reschedule on
580  * IRQ tail once IRQs get re-enabled on userspace/guest resume.
581  */
582 static void late_wakeup_func(struct irq_work *work)
583 {
584 }
585 
586 static DEFINE_PER_CPU(struct irq_work, late_wakeup_work) =
587 	IRQ_WORK_INIT(late_wakeup_func);
588 
589 /*
590  * If either:
591  *
592  * 1) the task is about to enter in guest mode and $ARCH doesn't support KVM generic work
593  * 2) the task is about to enter in user mode and $ARCH doesn't support generic entry.
594  *
595  * In these cases the late RCU wake ups aren't supported in the resched loops and our
596  * last resort is to fire a local irq_work that will trigger a reschedule once IRQs
597  * get re-enabled again.
598  */
599 noinstr void rcu_irq_work_resched(void)
600 {
601 	struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
602 
603 	if (IS_ENABLED(CONFIG_GENERIC_ENTRY) && !(current->flags & PF_VCPU))
604 		return;
605 
606 	if (IS_ENABLED(CONFIG_VIRT_XFER_TO_GUEST_WORK) && (current->flags & PF_VCPU))
607 		return;
608 
609 	instrumentation_begin();
610 	if (do_nocb_deferred_wakeup(rdp) && need_resched()) {
611 		irq_work_queue(this_cpu_ptr(&late_wakeup_work));
612 	}
613 	instrumentation_end();
614 }
615 #endif /* #if defined(CONFIG_NO_HZ_FULL) && (!defined(CONFIG_GENERIC_ENTRY) || !defined(CONFIG_VIRT_XFER_TO_GUEST_WORK)) */
616 
617 #ifdef CONFIG_PROVE_RCU
618 /**
619  * rcu_irq_exit_check_preempt - Validate that scheduling is possible
620  */
621 void rcu_irq_exit_check_preempt(void)
622 {
623 	lockdep_assert_irqs_disabled();
624 
625 	RCU_LOCKDEP_WARN(ct_nesting() <= 0,
626 			 "RCU nesting counter underflow/zero!");
627 	RCU_LOCKDEP_WARN(ct_nmi_nesting() !=
628 			 CT_NESTING_IRQ_NONIDLE,
629 			 "Bad RCU  nmi_nesting counter\n");
630 	RCU_LOCKDEP_WARN(!rcu_is_watching_curr_cpu(),
631 			 "RCU in extended quiescent state!");
632 }
633 #endif /* #ifdef CONFIG_PROVE_RCU */
634 
635 #ifdef CONFIG_NO_HZ_FULL
636 /**
637  * __rcu_irq_enter_check_tick - Enable scheduler tick on CPU if RCU needs it.
638  *
639  * The scheduler tick is not normally enabled when CPUs enter the kernel
640  * from nohz_full userspace execution.  After all, nohz_full userspace
641  * execution is an RCU quiescent state and the time executing in the kernel
642  * is quite short.  Except of course when it isn't.  And it is not hard to
643  * cause a large system to spend tens of seconds or even minutes looping
644  * in the kernel, which can cause a number of problems, include RCU CPU
645  * stall warnings.
646  *
647  * Therefore, if a nohz_full CPU fails to report a quiescent state
648  * in a timely manner, the RCU grace-period kthread sets that CPU's
649  * ->rcu_urgent_qs flag with the expectation that the next interrupt or
650  * exception will invoke this function, which will turn on the scheduler
651  * tick, which will enable RCU to detect that CPU's quiescent states,
652  * for example, due to cond_resched() calls in CONFIG_PREEMPT=n kernels.
653  * The tick will be disabled once a quiescent state is reported for
654  * this CPU.
655  *
656  * Of course, in carefully tuned systems, there might never be an
657  * interrupt or exception.  In that case, the RCU grace-period kthread
658  * will eventually cause one to happen.  However, in less carefully
659  * controlled environments, this function allows RCU to get what it
660  * needs without creating otherwise useless interruptions.
661  */
662 void __rcu_irq_enter_check_tick(void)
663 {
664 	struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
665 
666 	// If we're here from NMI there's nothing to do.
667 	if (in_nmi())
668 		return;
669 
670 	RCU_LOCKDEP_WARN(!rcu_is_watching_curr_cpu(),
671 			 "Illegal rcu_irq_enter_check_tick() from extended quiescent state");
672 
673 	if (!tick_nohz_full_cpu(rdp->cpu) ||
674 	    !READ_ONCE(rdp->rcu_urgent_qs) ||
675 	    READ_ONCE(rdp->rcu_forced_tick)) {
676 		// RCU doesn't need nohz_full help from this CPU, or it is
677 		// already getting that help.
678 		return;
679 	}
680 
681 	// We get here only when not in an extended quiescent state and
682 	// from interrupts (as opposed to NMIs).  Therefore, (1) RCU is
683 	// already watching and (2) The fact that we are in an interrupt
684 	// handler and that the rcu_node lock is an irq-disabled lock
685 	// prevents self-deadlock.  So we can safely recheck under the lock.
686 	// Note that the nohz_full state currently cannot change.
687 	raw_spin_lock_rcu_node(rdp->mynode);
688 	if (READ_ONCE(rdp->rcu_urgent_qs) && !rdp->rcu_forced_tick) {
689 		// A nohz_full CPU is in the kernel and RCU needs a
690 		// quiescent state.  Turn on the tick!
691 		WRITE_ONCE(rdp->rcu_forced_tick, true);
692 		tick_dep_set_cpu(rdp->cpu, TICK_DEP_BIT_RCU);
693 	}
694 	raw_spin_unlock_rcu_node(rdp->mynode);
695 }
696 NOKPROBE_SYMBOL(__rcu_irq_enter_check_tick);
697 #endif /* CONFIG_NO_HZ_FULL */
698 
699 /*
700  * Check to see if any future non-offloaded RCU-related work will need
701  * to be done by the current CPU, even if none need be done immediately,
702  * returning 1 if so.  This function is part of the RCU implementation;
703  * it is -not- an exported member of the RCU API.  This is used by
704  * the idle-entry code to figure out whether it is safe to disable the
705  * scheduler-clock interrupt.
706  *
707  * Just check whether or not this CPU has non-offloaded RCU callbacks
708  * queued.
709  */
710 int rcu_needs_cpu(void)
711 {
712 	return !rcu_segcblist_empty(&this_cpu_ptr(&rcu_data)->cblist) &&
713 		!rcu_rdp_is_offloaded(this_cpu_ptr(&rcu_data));
714 }
715 
716 /*
717  * If any sort of urgency was applied to the current CPU (for example,
718  * the scheduler-clock interrupt was enabled on a nohz_full CPU) in order
719  * to get to a quiescent state, disable it.
720  */
721 static void rcu_disable_urgency_upon_qs(struct rcu_data *rdp)
722 {
723 	raw_lockdep_assert_held_rcu_node(rdp->mynode);
724 	WRITE_ONCE(rdp->rcu_urgent_qs, false);
725 	WRITE_ONCE(rdp->rcu_need_heavy_qs, false);
726 	if (tick_nohz_full_cpu(rdp->cpu) && rdp->rcu_forced_tick) {
727 		tick_dep_clear_cpu(rdp->cpu, TICK_DEP_BIT_RCU);
728 		WRITE_ONCE(rdp->rcu_forced_tick, false);
729 	}
730 }
731 
732 /**
733  * rcu_is_watching - RCU read-side critical sections permitted on current CPU?
734  *
735  * Return @true if RCU is watching the running CPU and @false otherwise.
736  * An @true return means that this CPU can safely enter RCU read-side
737  * critical sections.
738  *
739  * Although calls to rcu_is_watching() from most parts of the kernel
740  * will return @true, there are important exceptions.  For example, if the
741  * current CPU is deep within its idle loop, in kernel entry/exit code,
742  * or offline, rcu_is_watching() will return @false.
743  *
744  * Make notrace because it can be called by the internal functions of
745  * ftrace, and making this notrace removes unnecessary recursion calls.
746  */
747 notrace bool rcu_is_watching(void)
748 {
749 	bool ret;
750 
751 	preempt_disable_notrace();
752 	ret = rcu_is_watching_curr_cpu();
753 	preempt_enable_notrace();
754 	return ret;
755 }
756 EXPORT_SYMBOL_GPL(rcu_is_watching);
757 
758 /*
759  * If a holdout task is actually running, request an urgent quiescent
760  * state from its CPU.  This is unsynchronized, so migrations can cause
761  * the request to go to the wrong CPU.  Which is OK, all that will happen
762  * is that the CPU's next context switch will be a bit slower and next
763  * time around this task will generate another request.
764  */
765 void rcu_request_urgent_qs_task(struct task_struct *t)
766 {
767 	int cpu;
768 
769 	barrier();
770 	cpu = task_cpu(t);
771 	if (!task_curr(t))
772 		return; /* This task is not running on that CPU. */
773 	smp_store_release(per_cpu_ptr(&rcu_data.rcu_urgent_qs, cpu), true);
774 }
775 
776 static unsigned long seq_gpwrap_lag = ULONG_MAX / 4;
777 
778 /**
779  * rcu_set_gpwrap_lag - Set RCU GP sequence overflow lag value.
780  * @lag_gps: Set overflow lag to this many grace period worth of counters
781  * which is used by rcutorture to quickly force a gpwrap situation.
782  * @lag_gps = 0 means we reset it back to the boot-time value.
783  */
784 void rcu_set_gpwrap_lag(unsigned long lag_gps)
785 {
786 	unsigned long lag_seq_count;
787 
788 	lag_seq_count = (lag_gps == 0)
789 			? ULONG_MAX / 4
790 			: lag_gps << RCU_SEQ_CTR_SHIFT;
791 	WRITE_ONCE(seq_gpwrap_lag, lag_seq_count);
792 }
793 EXPORT_SYMBOL_GPL(rcu_set_gpwrap_lag);
794 
795 /*
796  * When trying to report a quiescent state on behalf of some other CPU,
797  * it is our responsibility to check for and handle potential overflow
798  * of the rcu_node ->gp_seq counter with respect to the rcu_data counters.
799  * After all, the CPU might be in deep idle state, and thus executing no
800  * code whatsoever.
801  */
802 static void rcu_gpnum_ovf(struct rcu_node *rnp, struct rcu_data *rdp)
803 {
804 	raw_lockdep_assert_held_rcu_node(rnp);
805 	if (ULONG_CMP_LT(rcu_seq_current(&rdp->gp_seq) + seq_gpwrap_lag,
806 			 rnp->gp_seq)) {
807 		WRITE_ONCE(rdp->gpwrap, true);
808 		WRITE_ONCE(rdp->gpwrap_count, READ_ONCE(rdp->gpwrap_count) + 1);
809 	}
810 	if (ULONG_CMP_LT(rdp->rcu_iw_gp_seq + ULONG_MAX / 4, rnp->gp_seq))
811 		rdp->rcu_iw_gp_seq = rnp->gp_seq + ULONG_MAX / 4;
812 }
813 
814 /*
815  * Snapshot the specified CPU's RCU_WATCHING counter so that we can later
816  * credit them with an implicit quiescent state.  Return 1 if this CPU
817  * is in dynticks idle mode, which is an extended quiescent state.
818  */
819 static int rcu_watching_snap_save(struct rcu_data *rdp)
820 {
821 	/*
822 	 * Full ordering between remote CPU's post idle accesses and updater's
823 	 * accesses prior to current GP (and also the started GP sequence number)
824 	 * is enforced by rcu_seq_start() implicit barrier and even further by
825 	 * smp_mb__after_unlock_lock() barriers chained all the way throughout the
826 	 * rnp locking tree since rcu_gp_init() and up to the current leaf rnp
827 	 * locking.
828 	 *
829 	 * Ordering between remote CPU's pre idle accesses and post grace period
830 	 * updater's accesses is enforced by the below acquire semantic.
831 	 */
832 	rdp->watching_snap = ct_rcu_watching_cpu_acquire(rdp->cpu);
833 	if (rcu_watching_snap_in_eqs(rdp->watching_snap)) {
834 		trace_rcu_fqs(rcu_state.name, rdp->gp_seq, rdp->cpu, TPS("dti"));
835 		rcu_gpnum_ovf(rdp->mynode, rdp);
836 		return 1;
837 	}
838 	return 0;
839 }
840 
841 #ifndef arch_irq_stat_cpu
842 #define arch_irq_stat_cpu(cpu) 0
843 #endif
844 
845 /*
846  * Returns positive if the specified CPU has passed through a quiescent state
847  * by virtue of being in or having passed through an dynticks idle state since
848  * the last call to rcu_watching_snap_save() for this same CPU, or by
849  * virtue of having been offline.
850  *
851  * Returns negative if the specified CPU needs a force resched.
852  *
853  * Returns zero otherwise.
854  */
855 static int rcu_watching_snap_recheck(struct rcu_data *rdp)
856 {
857 	unsigned long jtsq;
858 	int ret = 0;
859 	struct rcu_node *rnp = rdp->mynode;
860 
861 	/*
862 	 * If the CPU passed through or entered a dynticks idle phase with
863 	 * no active irq/NMI handlers, then we can safely pretend that the CPU
864 	 * already acknowledged the request to pass through a quiescent
865 	 * state.  Either way, that CPU cannot possibly be in an RCU
866 	 * read-side critical section that started before the beginning
867 	 * of the current RCU grace period.
868 	 */
869 	if (rcu_watching_snap_stopped_since(rdp, rdp->watching_snap)) {
870 		trace_rcu_fqs(rcu_state.name, rdp->gp_seq, rdp->cpu, TPS("dti"));
871 		rcu_gpnum_ovf(rnp, rdp);
872 		return 1;
873 	}
874 
875 	/*
876 	 * Complain if a CPU that is considered to be offline from RCU's
877 	 * perspective has not yet reported a quiescent state.  After all,
878 	 * the offline CPU should have reported a quiescent state during
879 	 * the CPU-offline process, or, failing that, by rcu_gp_init()
880 	 * if it ran concurrently with either the CPU going offline or the
881 	 * last task on a leaf rcu_node structure exiting its RCU read-side
882 	 * critical section while all CPUs corresponding to that structure
883 	 * are offline.  This added warning detects bugs in any of these
884 	 * code paths.
885 	 *
886 	 * The rcu_node structure's ->lock is held here, which excludes
887 	 * the relevant portions the CPU-hotplug code, the grace-period
888 	 * initialization code, and the rcu_read_unlock() code paths.
889 	 *
890 	 * For more detail, please refer to the "Hotplug CPU" section
891 	 * of RCU's Requirements documentation.
892 	 */
893 	if (WARN_ON_ONCE(!rcu_rdp_cpu_online(rdp))) {
894 		struct rcu_node *rnp1;
895 
896 		pr_info("%s: grp: %d-%d level: %d ->gp_seq %ld ->completedqs %ld\n",
897 			__func__, rnp->grplo, rnp->grphi, rnp->level,
898 			(long)rnp->gp_seq, (long)rnp->completedqs);
899 		for (rnp1 = rnp; rnp1; rnp1 = rnp1->parent)
900 			pr_info("%s: %d:%d ->qsmask %#lx ->qsmaskinit %#lx ->qsmaskinitnext %#lx ->rcu_gp_init_mask %#lx\n",
901 				__func__, rnp1->grplo, rnp1->grphi, rnp1->qsmask, rnp1->qsmaskinit, rnp1->qsmaskinitnext, rnp1->rcu_gp_init_mask);
902 		pr_info("%s %d: %c online: %ld(%d) offline: %ld(%d)\n",
903 			__func__, rdp->cpu, ".o"[rcu_rdp_cpu_online(rdp)],
904 			(long)rdp->rcu_onl_gp_seq, rdp->rcu_onl_gp_state,
905 			(long)rdp->rcu_ofl_gp_seq, rdp->rcu_ofl_gp_state);
906 		return 1; /* Break things loose after complaining. */
907 	}
908 
909 	/*
910 	 * A CPU running for an extended time within the kernel can
911 	 * delay RCU grace periods: (1) At age jiffies_to_sched_qs,
912 	 * set .rcu_urgent_qs, (2) At age 2*jiffies_to_sched_qs, set
913 	 * both .rcu_need_heavy_qs and .rcu_urgent_qs.  Note that the
914 	 * unsynchronized assignments to the per-CPU rcu_need_heavy_qs
915 	 * variable are safe because the assignments are repeated if this
916 	 * CPU failed to pass through a quiescent state.  This code
917 	 * also checks .jiffies_resched in case jiffies_to_sched_qs
918 	 * is set way high.
919 	 */
920 	jtsq = READ_ONCE(jiffies_to_sched_qs);
921 	if (!READ_ONCE(rdp->rcu_need_heavy_qs) &&
922 	    (time_after(jiffies, rcu_state.gp_start + jtsq * 2) ||
923 	     time_after(jiffies, rcu_state.jiffies_resched) ||
924 	     rcu_state.cbovld)) {
925 		WRITE_ONCE(rdp->rcu_need_heavy_qs, true);
926 		/* Store rcu_need_heavy_qs before rcu_urgent_qs. */
927 		smp_store_release(&rdp->rcu_urgent_qs, true);
928 	} else if (time_after(jiffies, rcu_state.gp_start + jtsq)) {
929 		WRITE_ONCE(rdp->rcu_urgent_qs, true);
930 	}
931 
932 	/*
933 	 * NO_HZ_FULL CPUs can run in-kernel without rcu_sched_clock_irq!
934 	 * The above code handles this, but only for straight cond_resched().
935 	 * And some in-kernel loops check need_resched() before calling
936 	 * cond_resched(), which defeats the above code for CPUs that are
937 	 * running in-kernel with scheduling-clock interrupts disabled.
938 	 * So hit them over the head with the resched_cpu() hammer!
939 	 */
940 	if (tick_nohz_full_cpu(rdp->cpu) &&
941 	    (time_after(jiffies, READ_ONCE(rdp->last_fqs_resched) + jtsq * 3) ||
942 	     rcu_state.cbovld)) {
943 		WRITE_ONCE(rdp->rcu_urgent_qs, true);
944 		WRITE_ONCE(rdp->last_fqs_resched, jiffies);
945 		ret = -1;
946 	}
947 
948 	/*
949 	 * If more than halfway to RCU CPU stall-warning time, invoke
950 	 * resched_cpu() more frequently to try to loosen things up a bit.
951 	 * Also check to see if the CPU is getting hammered with interrupts,
952 	 * but only once per grace period, just to keep the IPIs down to
953 	 * a dull roar.
954 	 */
955 	if (time_after(jiffies, rcu_state.jiffies_resched)) {
956 		if (time_after(jiffies,
957 			       READ_ONCE(rdp->last_fqs_resched) + jtsq)) {
958 			WRITE_ONCE(rdp->last_fqs_resched, jiffies);
959 			ret = -1;
960 		}
961 		if (IS_ENABLED(CONFIG_IRQ_WORK) &&
962 		    !rdp->rcu_iw_pending && rdp->rcu_iw_gp_seq != rnp->gp_seq &&
963 		    (rnp->ffmask & rdp->grpmask)) {
964 			rdp->rcu_iw_pending = true;
965 			rdp->rcu_iw_gp_seq = rnp->gp_seq;
966 			irq_work_queue_on(&rdp->rcu_iw, rdp->cpu);
967 		}
968 
969 		if (rcu_cpu_stall_cputime && rdp->snap_record.gp_seq != rdp->gp_seq) {
970 			int cpu = rdp->cpu;
971 			struct rcu_snap_record *rsrp;
972 
973 			rsrp = &rdp->snap_record;
974 			rsrp->cputime_irq     = kcpustat_field(CPUTIME_IRQ, cpu);
975 			rsrp->cputime_softirq = kcpustat_field(CPUTIME_SOFTIRQ, cpu);
976 			rsrp->cputime_system  = kcpustat_field(CPUTIME_SYSTEM, cpu);
977 			rsrp->nr_hardirqs = kstat_cpu_irqs_sum(cpu) + arch_irq_stat_cpu(cpu);
978 			rsrp->nr_softirqs = kstat_cpu_softirqs_sum(cpu);
979 			rsrp->nr_csw = nr_context_switches_cpu(cpu);
980 			rsrp->jiffies = jiffies;
981 			rsrp->gp_seq = rdp->gp_seq;
982 		}
983 	}
984 
985 	return ret;
986 }
987 
988 /* Trace-event wrapper function for trace_rcu_future_grace_period.  */
989 static void trace_rcu_this_gp(struct rcu_node *rnp, struct rcu_data *rdp,
990 			      unsigned long gp_seq_req, const char *s)
991 {
992 	trace_rcu_future_grace_period(rcu_state.name, READ_ONCE(rnp->gp_seq),
993 				      gp_seq_req, rnp->level,
994 				      rnp->grplo, rnp->grphi, s);
995 }
996 
997 /*
998  * rcu_start_this_gp - Request the start of a particular grace period
999  * @rnp_start: The leaf node of the CPU from which to start.
1000  * @rdp: The rcu_data corresponding to the CPU from which to start.
1001  * @gp_seq_req: The gp_seq of the grace period to start.
1002  *
1003  * Start the specified grace period, as needed to handle newly arrived
1004  * callbacks.  The required future grace periods are recorded in each
1005  * rcu_node structure's ->gp_seq_needed field.  Returns true if there
1006  * is reason to awaken the grace-period kthread.
1007  *
1008  * The caller must hold the specified rcu_node structure's ->lock, which
1009  * is why the caller is responsible for waking the grace-period kthread.
1010  *
1011  * Returns true if the GP thread needs to be awakened else false.
1012  */
1013 static bool rcu_start_this_gp(struct rcu_node *rnp_start, struct rcu_data *rdp,
1014 			      unsigned long gp_seq_req)
1015 {
1016 	bool ret = false;
1017 	struct rcu_node *rnp;
1018 
1019 	/*
1020 	 * Use funnel locking to either acquire the root rcu_node
1021 	 * structure's lock or bail out if the need for this grace period
1022 	 * has already been recorded -- or if that grace period has in
1023 	 * fact already started.  If there is already a grace period in
1024 	 * progress in a non-leaf node, no recording is needed because the
1025 	 * end of the grace period will scan the leaf rcu_node structures.
1026 	 * Note that rnp_start->lock must not be released.
1027 	 */
1028 	raw_lockdep_assert_held_rcu_node(rnp_start);
1029 	trace_rcu_this_gp(rnp_start, rdp, gp_seq_req, TPS("Startleaf"));
1030 	for (rnp = rnp_start; 1; rnp = rnp->parent) {
1031 		if (rnp != rnp_start)
1032 			raw_spin_lock_rcu_node(rnp);
1033 		if (ULONG_CMP_GE(rnp->gp_seq_needed, gp_seq_req) ||
1034 		    rcu_seq_started(&rnp->gp_seq, gp_seq_req) ||
1035 		    (rnp != rnp_start &&
1036 		     rcu_seq_state(rcu_seq_current(&rnp->gp_seq)))) {
1037 			trace_rcu_this_gp(rnp, rdp, gp_seq_req,
1038 					  TPS("Prestarted"));
1039 			goto unlock_out;
1040 		}
1041 		WRITE_ONCE(rnp->gp_seq_needed, gp_seq_req);
1042 		if (rcu_seq_state(rcu_seq_current(&rnp->gp_seq))) {
1043 			/*
1044 			 * We just marked the leaf or internal node, and a
1045 			 * grace period is in progress, which means that
1046 			 * rcu_gp_cleanup() will see the marking.  Bail to
1047 			 * reduce contention.
1048 			 */
1049 			trace_rcu_this_gp(rnp_start, rdp, gp_seq_req,
1050 					  TPS("Startedleaf"));
1051 			goto unlock_out;
1052 		}
1053 		if (rnp != rnp_start && rnp->parent != NULL)
1054 			raw_spin_unlock_rcu_node(rnp);
1055 		if (!rnp->parent)
1056 			break;  /* At root, and perhaps also leaf. */
1057 	}
1058 
1059 	/* If GP already in progress, just leave, otherwise start one. */
1060 	if (rcu_gp_in_progress()) {
1061 		trace_rcu_this_gp(rnp, rdp, gp_seq_req, TPS("Startedleafroot"));
1062 		goto unlock_out;
1063 	}
1064 	trace_rcu_this_gp(rnp, rdp, gp_seq_req, TPS("Startedroot"));
1065 	WRITE_ONCE(rcu_state.gp_flags, rcu_state.gp_flags | RCU_GP_FLAG_INIT);
1066 	WRITE_ONCE(rcu_state.gp_req_activity, jiffies);
1067 	if (!READ_ONCE(rcu_state.gp_kthread)) {
1068 		trace_rcu_this_gp(rnp, rdp, gp_seq_req, TPS("NoGPkthread"));
1069 		goto unlock_out;
1070 	}
1071 	trace_rcu_grace_period(rcu_state.name, data_race(rcu_state.gp_seq), TPS("newreq"));
1072 	ret = true;  /* Caller must wake GP kthread. */
1073 unlock_out:
1074 	/* Push furthest requested GP to leaf node and rcu_data structure. */
1075 	if (ULONG_CMP_LT(gp_seq_req, rnp->gp_seq_needed)) {
1076 		WRITE_ONCE(rnp_start->gp_seq_needed, rnp->gp_seq_needed);
1077 		WRITE_ONCE(rdp->gp_seq_needed, rnp->gp_seq_needed);
1078 	}
1079 	if (rnp != rnp_start)
1080 		raw_spin_unlock_rcu_node(rnp);
1081 	return ret;
1082 }
1083 
1084 /*
1085  * Clean up any old requests for the just-ended grace period.  Also return
1086  * whether any additional grace periods have been requested.
1087  */
1088 static bool rcu_future_gp_cleanup(struct rcu_node *rnp)
1089 {
1090 	bool needmore;
1091 	struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
1092 
1093 	needmore = ULONG_CMP_LT(rnp->gp_seq, rnp->gp_seq_needed);
1094 	if (!needmore)
1095 		rnp->gp_seq_needed = rnp->gp_seq; /* Avoid counter wrap. */
1096 	trace_rcu_this_gp(rnp, rdp, rnp->gp_seq,
1097 			  needmore ? TPS("CleanupMore") : TPS("Cleanup"));
1098 	return needmore;
1099 }
1100 
1101 /*
1102  * Awaken the grace-period kthread.  Don't do a self-awaken (unless in an
1103  * interrupt or softirq handler, in which case we just might immediately
1104  * sleep upon return, resulting in a grace-period hang), and don't bother
1105  * awakening when there is nothing for the grace-period kthread to do
1106  * (as in several CPUs raced to awaken, we lost), and finally don't try
1107  * to awaken a kthread that has not yet been created.  If all those checks
1108  * are passed, track some debug information and awaken.
1109  *
1110  * So why do the self-wakeup when in an interrupt or softirq handler
1111  * in the grace-period kthread's context?  Because the kthread might have
1112  * been interrupted just as it was going to sleep, and just after the final
1113  * pre-sleep check of the awaken condition.  In this case, a wakeup really
1114  * is required, and is therefore supplied.
1115  */
1116 static void rcu_gp_kthread_wake(void)
1117 {
1118 	struct task_struct *t = READ_ONCE(rcu_state.gp_kthread);
1119 
1120 	if ((current == t && !in_hardirq() && !in_serving_softirq()) ||
1121 	    !READ_ONCE(rcu_state.gp_flags) || !t)
1122 		return;
1123 	WRITE_ONCE(rcu_state.gp_wake_time, jiffies);
1124 	WRITE_ONCE(rcu_state.gp_wake_seq, READ_ONCE(rcu_state.gp_seq));
1125 	swake_up_one(&rcu_state.gp_wq);
1126 }
1127 
1128 /*
1129  * If there is room, assign a ->gp_seq number to any callbacks on this
1130  * CPU that have not already been assigned.  Also accelerate any callbacks
1131  * that were previously assigned a ->gp_seq number that has since proven
1132  * to be too conservative, which can happen if callbacks get assigned a
1133  * ->gp_seq number while RCU is idle, but with reference to a non-root
1134  * rcu_node structure.  This function is idempotent, so it does not hurt
1135  * to call it repeatedly.  Returns an flag saying that we should awaken
1136  * the RCU grace-period kthread.
1137  *
1138  * The caller must hold rnp->lock with interrupts disabled.
1139  */
1140 static bool rcu_accelerate_cbs(struct rcu_node *rnp, struct rcu_data *rdp)
1141 {
1142 	unsigned long gp_seq_req;
1143 	bool ret = false;
1144 
1145 	rcu_lockdep_assert_cblist_protected(rdp);
1146 	raw_lockdep_assert_held_rcu_node(rnp);
1147 
1148 	/* If no pending (not yet ready to invoke) callbacks, nothing to do. */
1149 	if (!rcu_segcblist_pend_cbs(&rdp->cblist))
1150 		return false;
1151 
1152 	trace_rcu_segcb_stats(&rdp->cblist, TPS("SegCbPreAcc"));
1153 
1154 	/*
1155 	 * Callbacks are often registered with incomplete grace-period
1156 	 * information.  Something about the fact that getting exact
1157 	 * information requires acquiring a global lock...  RCU therefore
1158 	 * makes a conservative estimate of the grace period number at which
1159 	 * a given callback will become ready to invoke.	The following
1160 	 * code checks this estimate and improves it when possible, thus
1161 	 * accelerating callback invocation to an earlier grace-period
1162 	 * number.
1163 	 */
1164 	gp_seq_req = rcu_seq_snap(&rcu_state.gp_seq);
1165 	if (rcu_segcblist_accelerate(&rdp->cblist, gp_seq_req))
1166 		ret = rcu_start_this_gp(rnp, rdp, gp_seq_req);
1167 
1168 	/* Trace depending on how much we were able to accelerate. */
1169 	if (rcu_segcblist_restempty(&rdp->cblist, RCU_WAIT_TAIL))
1170 		trace_rcu_grace_period(rcu_state.name, gp_seq_req, TPS("AccWaitCB"));
1171 	else
1172 		trace_rcu_grace_period(rcu_state.name, gp_seq_req, TPS("AccReadyCB"));
1173 
1174 	trace_rcu_segcb_stats(&rdp->cblist, TPS("SegCbPostAcc"));
1175 
1176 	return ret;
1177 }
1178 
1179 /*
1180  * Similar to rcu_accelerate_cbs(), but does not require that the leaf
1181  * rcu_node structure's ->lock be held.  It consults the cached value
1182  * of ->gp_seq_needed in the rcu_data structure, and if that indicates
1183  * that a new grace-period request be made, invokes rcu_accelerate_cbs()
1184  * while holding the leaf rcu_node structure's ->lock.
1185  */
1186 static void rcu_accelerate_cbs_unlocked(struct rcu_node *rnp,
1187 					struct rcu_data *rdp)
1188 {
1189 	unsigned long c;
1190 	bool needwake;
1191 
1192 	rcu_lockdep_assert_cblist_protected(rdp);
1193 	c = rcu_seq_snap(&rcu_state.gp_seq);
1194 	if (!READ_ONCE(rdp->gpwrap) && ULONG_CMP_GE(rdp->gp_seq_needed, c)) {
1195 		/* Old request still live, so mark recent callbacks. */
1196 		(void)rcu_segcblist_accelerate(&rdp->cblist, c);
1197 		return;
1198 	}
1199 	raw_spin_lock_rcu_node(rnp); /* irqs already disabled. */
1200 	needwake = rcu_accelerate_cbs(rnp, rdp);
1201 	raw_spin_unlock_rcu_node(rnp); /* irqs remain disabled. */
1202 	if (needwake)
1203 		rcu_gp_kthread_wake();
1204 }
1205 
1206 /*
1207  * Move any callbacks whose grace period has completed to the
1208  * RCU_DONE_TAIL sublist, then compact the remaining sublists and
1209  * assign ->gp_seq numbers to any callbacks in the RCU_NEXT_TAIL
1210  * sublist.  This function is idempotent, so it does not hurt to
1211  * invoke it repeatedly.  As long as it is not invoked -too- often...
1212  * Returns true if the RCU grace-period kthread needs to be awakened.
1213  *
1214  * The caller must hold rnp->lock with interrupts disabled.
1215  */
1216 static bool rcu_advance_cbs(struct rcu_node *rnp, struct rcu_data *rdp)
1217 {
1218 	rcu_lockdep_assert_cblist_protected(rdp);
1219 	raw_lockdep_assert_held_rcu_node(rnp);
1220 
1221 	/* If no pending (not yet ready to invoke) callbacks, nothing to do. */
1222 	if (!rcu_segcblist_pend_cbs(&rdp->cblist))
1223 		return false;
1224 
1225 	/*
1226 	 * Find all callbacks whose ->gp_seq numbers indicate that they
1227 	 * are ready to invoke, and put them into the RCU_DONE_TAIL sublist.
1228 	 */
1229 	rcu_segcblist_advance(&rdp->cblist, rnp->gp_seq);
1230 
1231 	/* Classify any remaining callbacks. */
1232 	return rcu_accelerate_cbs(rnp, rdp);
1233 }
1234 
1235 /*
1236  * Move and classify callbacks, but only if doing so won't require
1237  * that the RCU grace-period kthread be awakened.
1238  */
1239 static void __maybe_unused rcu_advance_cbs_nowake(struct rcu_node *rnp,
1240 						  struct rcu_data *rdp)
1241 {
1242 	rcu_lockdep_assert_cblist_protected(rdp);
1243 	if (!rcu_seq_state(rcu_seq_current(&rnp->gp_seq)) || !raw_spin_trylock_rcu_node(rnp))
1244 		return;
1245 	// The grace period cannot end while we hold the rcu_node lock.
1246 	if (rcu_seq_state(rcu_seq_current(&rnp->gp_seq)))
1247 		WARN_ON_ONCE(rcu_advance_cbs(rnp, rdp));
1248 	raw_spin_unlock_rcu_node(rnp);
1249 }
1250 
1251 /*
1252  * In CONFIG_RCU_STRICT_GRACE_PERIOD=y kernels, attempt to generate a
1253  * quiescent state.  This is intended to be invoked when the CPU notices
1254  * a new grace period.
1255  */
1256 static void rcu_strict_gp_check_qs(void)
1257 {
1258 	if (IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD)) {
1259 		rcu_read_lock();
1260 		rcu_read_unlock();
1261 	}
1262 }
1263 
1264 /*
1265  * Update CPU-local rcu_data state to record the beginnings and ends of
1266  * grace periods.  The caller must hold the ->lock of the leaf rcu_node
1267  * structure corresponding to the current CPU, and must have irqs disabled.
1268  * Returns true if the grace-period kthread needs to be awakened.
1269  */
1270 static bool __note_gp_changes(struct rcu_node *rnp, struct rcu_data *rdp)
1271 {
1272 	bool ret = false;
1273 	bool need_qs;
1274 	const bool offloaded = rcu_rdp_is_offloaded(rdp);
1275 
1276 	raw_lockdep_assert_held_rcu_node(rnp);
1277 
1278 	if (rdp->gp_seq == rnp->gp_seq)
1279 		return false; /* Nothing to do. */
1280 
1281 	/* Handle the ends of any preceding grace periods first. */
1282 	if (rcu_seq_completed_gp(rdp->gp_seq, rnp->gp_seq) ||
1283 	    unlikely(rdp->gpwrap)) {
1284 		if (!offloaded)
1285 			ret = rcu_advance_cbs(rnp, rdp); /* Advance CBs. */
1286 		rdp->core_needs_qs = false;
1287 		trace_rcu_grace_period(rcu_state.name, rdp->gp_seq, TPS("cpuend"));
1288 	} else {
1289 		if (!offloaded)
1290 			ret = rcu_accelerate_cbs(rnp, rdp); /* Recent CBs. */
1291 		if (rdp->core_needs_qs)
1292 			rdp->core_needs_qs = !!(rnp->qsmask & rdp->grpmask);
1293 	}
1294 
1295 	/* Now handle the beginnings of any new-to-this-CPU grace periods. */
1296 	if (rcu_seq_new_gp(rdp->gp_seq, rnp->gp_seq) ||
1297 	    unlikely(rdp->gpwrap)) {
1298 		/*
1299 		 * If the current grace period is waiting for this CPU,
1300 		 * set up to detect a quiescent state, otherwise don't
1301 		 * go looking for one.
1302 		 */
1303 		trace_rcu_grace_period(rcu_state.name, rnp->gp_seq, TPS("cpustart"));
1304 		need_qs = !!(rnp->qsmask & rdp->grpmask);
1305 		rdp->cpu_no_qs.b.norm = need_qs;
1306 		rdp->core_needs_qs = need_qs;
1307 		zero_cpu_stall_ticks(rdp);
1308 	}
1309 	rdp->gp_seq = rnp->gp_seq;  /* Remember new grace-period state. */
1310 	if (ULONG_CMP_LT(rdp->gp_seq_needed, rnp->gp_seq_needed) || rdp->gpwrap)
1311 		WRITE_ONCE(rdp->gp_seq_needed, rnp->gp_seq_needed);
1312 	if (IS_ENABLED(CONFIG_PROVE_RCU) && rdp->gpwrap)
1313 		WRITE_ONCE(rdp->last_sched_clock, jiffies);
1314 	WRITE_ONCE(rdp->gpwrap, false);
1315 	rcu_gpnum_ovf(rnp, rdp);
1316 	return ret;
1317 }
1318 
1319 static void note_gp_changes(struct rcu_data *rdp)
1320 {
1321 	unsigned long flags;
1322 	bool needwake;
1323 	struct rcu_node *rnp;
1324 
1325 	local_irq_save(flags);
1326 	rnp = rdp->mynode;
1327 	if ((rdp->gp_seq == rcu_seq_current(&rnp->gp_seq) &&
1328 	     !unlikely(READ_ONCE(rdp->gpwrap))) || /* w/out lock. */
1329 	    !raw_spin_trylock_rcu_node(rnp)) { /* irqs already off, so later. */
1330 		local_irq_restore(flags);
1331 		return;
1332 	}
1333 	needwake = __note_gp_changes(rnp, rdp);
1334 	raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1335 	rcu_strict_gp_check_qs();
1336 	if (needwake)
1337 		rcu_gp_kthread_wake();
1338 }
1339 
1340 static atomic_t *rcu_gp_slow_suppress;
1341 
1342 /* Register a counter to suppress debugging grace-period delays. */
1343 void rcu_gp_slow_register(atomic_t *rgssp)
1344 {
1345 	WARN_ON_ONCE(rcu_gp_slow_suppress);
1346 
1347 	WRITE_ONCE(rcu_gp_slow_suppress, rgssp);
1348 }
1349 EXPORT_SYMBOL_GPL(rcu_gp_slow_register);
1350 
1351 /* Unregister a counter, with NULL for not caring which. */
1352 void rcu_gp_slow_unregister(atomic_t *rgssp)
1353 {
1354 	WARN_ON_ONCE(rgssp && rgssp != rcu_gp_slow_suppress && rcu_gp_slow_suppress != NULL);
1355 
1356 	WRITE_ONCE(rcu_gp_slow_suppress, NULL);
1357 }
1358 EXPORT_SYMBOL_GPL(rcu_gp_slow_unregister);
1359 
1360 static bool rcu_gp_slow_is_suppressed(void)
1361 {
1362 	atomic_t *rgssp = READ_ONCE(rcu_gp_slow_suppress);
1363 
1364 	return rgssp && atomic_read(rgssp);
1365 }
1366 
1367 static void rcu_gp_slow(int delay)
1368 {
1369 	if (!rcu_gp_slow_is_suppressed() && delay > 0 &&
1370 	    !(rcu_seq_ctr(rcu_state.gp_seq) % (rcu_num_nodes * PER_RCU_NODE_PERIOD * delay)))
1371 		schedule_timeout_idle(delay);
1372 }
1373 
1374 static unsigned long sleep_duration;
1375 
1376 /* Allow rcutorture to stall the grace-period kthread. */
1377 void rcu_gp_set_torture_wait(int duration)
1378 {
1379 	if (IS_ENABLED(CONFIG_RCU_TORTURE_TEST) && duration > 0)
1380 		WRITE_ONCE(sleep_duration, duration);
1381 }
1382 EXPORT_SYMBOL_GPL(rcu_gp_set_torture_wait);
1383 
1384 /* Actually implement the aforementioned wait. */
1385 static void rcu_gp_torture_wait(void)
1386 {
1387 	unsigned long duration;
1388 
1389 	if (!IS_ENABLED(CONFIG_RCU_TORTURE_TEST))
1390 		return;
1391 	duration = xchg(&sleep_duration, 0UL);
1392 	if (duration > 0) {
1393 		pr_alert("%s: Waiting %lu jiffies\n", __func__, duration);
1394 		schedule_timeout_idle(duration);
1395 		pr_alert("%s: Wait complete\n", __func__);
1396 	}
1397 }
1398 
1399 /*
1400  * Handler for on_each_cpu() to invoke the target CPU's RCU core
1401  * processing.
1402  */
1403 static void rcu_strict_gp_boundary(void *unused)
1404 {
1405 	invoke_rcu_core();
1406 }
1407 
1408 // Make the polled API aware of the beginning of a grace period.
1409 static void rcu_poll_gp_seq_start(unsigned long *snap)
1410 {
1411 	struct rcu_node *rnp = rcu_get_root();
1412 
1413 	if (rcu_scheduler_active != RCU_SCHEDULER_INACTIVE)
1414 		raw_lockdep_assert_held_rcu_node(rnp);
1415 
1416 	// If RCU was idle, note beginning of GP.
1417 	if (!rcu_seq_state(rcu_state.gp_seq_polled))
1418 		rcu_seq_start(&rcu_state.gp_seq_polled);
1419 
1420 	// Either way, record current state.
1421 	*snap = rcu_state.gp_seq_polled;
1422 }
1423 
1424 // Make the polled API aware of the end of a grace period.
1425 static void rcu_poll_gp_seq_end(unsigned long *snap)
1426 {
1427 	struct rcu_node *rnp = rcu_get_root();
1428 
1429 	if (rcu_scheduler_active != RCU_SCHEDULER_INACTIVE)
1430 		raw_lockdep_assert_held_rcu_node(rnp);
1431 
1432 	// If the previously noted GP is still in effect, record the
1433 	// end of that GP.  Either way, zero counter to avoid counter-wrap
1434 	// problems.
1435 	if (*snap && *snap == rcu_state.gp_seq_polled) {
1436 		rcu_seq_end(&rcu_state.gp_seq_polled);
1437 		rcu_state.gp_seq_polled_snap = 0;
1438 		rcu_state.gp_seq_polled_exp_snap = 0;
1439 	} else {
1440 		*snap = 0;
1441 	}
1442 }
1443 
1444 // Make the polled API aware of the beginning of a grace period, but
1445 // where caller does not hold the root rcu_node structure's lock.
1446 static void rcu_poll_gp_seq_start_unlocked(unsigned long *snap)
1447 {
1448 	unsigned long flags;
1449 	struct rcu_node *rnp = rcu_get_root();
1450 
1451 	if (rcu_init_invoked()) {
1452 		if (rcu_scheduler_active != RCU_SCHEDULER_INACTIVE)
1453 			lockdep_assert_irqs_enabled();
1454 		raw_spin_lock_irqsave_rcu_node(rnp, flags);
1455 	}
1456 	rcu_poll_gp_seq_start(snap);
1457 	if (rcu_init_invoked())
1458 		raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1459 }
1460 
1461 // Make the polled API aware of the end of a grace period, but where
1462 // caller does not hold the root rcu_node structure's lock.
1463 static void rcu_poll_gp_seq_end_unlocked(unsigned long *snap)
1464 {
1465 	unsigned long flags;
1466 	struct rcu_node *rnp = rcu_get_root();
1467 
1468 	if (rcu_init_invoked()) {
1469 		if (rcu_scheduler_active != RCU_SCHEDULER_INACTIVE)
1470 			lockdep_assert_irqs_enabled();
1471 		raw_spin_lock_irqsave_rcu_node(rnp, flags);
1472 	}
1473 	rcu_poll_gp_seq_end(snap);
1474 	if (rcu_init_invoked())
1475 		raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1476 }
1477 
1478 /*
1479  * There is a single llist, which is used for handling
1480  * synchronize_rcu() users' enqueued rcu_synchronize nodes.
1481  * Within this llist, there are two tail pointers:
1482  *
1483  * wait tail: Tracks the set of nodes, which need to
1484  *            wait for the current GP to complete.
1485  * done tail: Tracks the set of nodes, for which grace
1486  *            period has elapsed. These nodes processing
1487  *            will be done as part of the cleanup work
1488  *            execution by a kworker.
1489  *
1490  * At every grace period init, a new wait node is added
1491  * to the llist. This wait node is used as wait tail
1492  * for this new grace period. Given that there are a fixed
1493  * number of wait nodes, if all wait nodes are in use
1494  * (which can happen when kworker callback processing
1495  * is delayed) and additional grace period is requested.
1496  * This means, a system is slow in processing callbacks.
1497  *
1498  * TODO: If a slow processing is detected, a first node
1499  * in the llist should be used as a wait-tail for this
1500  * grace period, therefore users which should wait due
1501  * to a slow process are handled by _this_ grace period
1502  * and not next.
1503  *
1504  * Below is an illustration of how the done and wait
1505  * tail pointers move from one set of rcu_synchronize nodes
1506  * to the other, as grace periods start and finish and
1507  * nodes are processed by kworker.
1508  *
1509  *
1510  * a. Initial llist callbacks list:
1511  *
1512  * +----------+           +--------+          +-------+
1513  * |          |           |        |          |       |
1514  * |   head   |---------> |   cb2  |--------->| cb1   |
1515  * |          |           |        |          |       |
1516  * +----------+           +--------+          +-------+
1517  *
1518  *
1519  *
1520  * b. New GP1 Start:
1521  *
1522  *                    WAIT TAIL
1523  *                      |
1524  *                      |
1525  *                      v
1526  * +----------+     +--------+      +--------+        +-------+
1527  * |          |     |        |      |        |        |       |
1528  * |   head   ------> wait   |------>   cb2  |------> |  cb1  |
1529  * |          |     | head1  |      |        |        |       |
1530  * +----------+     +--------+      +--------+        +-------+
1531  *
1532  *
1533  *
1534  * c. GP completion:
1535  *
1536  * WAIT_TAIL == DONE_TAIL
1537  *
1538  *                   DONE TAIL
1539  *                     |
1540  *                     |
1541  *                     v
1542  * +----------+     +--------+      +--------+        +-------+
1543  * |          |     |        |      |        |        |       |
1544  * |   head   ------> wait   |------>   cb2  |------> |  cb1  |
1545  * |          |     | head1  |      |        |        |       |
1546  * +----------+     +--------+      +--------+        +-------+
1547  *
1548  *
1549  *
1550  * d. New callbacks and GP2 start:
1551  *
1552  *                    WAIT TAIL                          DONE TAIL
1553  *                      |                                 |
1554  *                      |                                 |
1555  *                      v                                 v
1556  * +----------+     +------+    +------+    +------+    +-----+    +-----+    +-----+
1557  * |          |     |      |    |      |    |      |    |     |    |     |    |     |
1558  * |   head   ------> wait |--->|  cb4 |--->| cb3  |--->|wait |--->| cb2 |--->| cb1 |
1559  * |          |     | head2|    |      |    |      |    |head1|    |     |    |     |
1560  * +----------+     +------+    +------+    +------+    +-----+    +-----+    +-----+
1561  *
1562  *
1563  *
1564  * e. GP2 completion:
1565  *
1566  * WAIT_TAIL == DONE_TAIL
1567  *                   DONE TAIL
1568  *                      |
1569  *                      |
1570  *                      v
1571  * +----------+     +------+    +------+    +------+    +-----+    +-----+    +-----+
1572  * |          |     |      |    |      |    |      |    |     |    |     |    |     |
1573  * |   head   ------> wait |--->|  cb4 |--->| cb3  |--->|wait |--->| cb2 |--->| cb1 |
1574  * |          |     | head2|    |      |    |      |    |head1|    |     |    |     |
1575  * +----------+     +------+    +------+    +------+    +-----+    +-----+    +-----+
1576  *
1577  *
1578  * While the llist state transitions from d to e, a kworker
1579  * can start executing rcu_sr_normal_gp_cleanup_work() and
1580  * can observe either the old done tail (@c) or the new
1581  * done tail (@e). So, done tail updates and reads need
1582  * to use the rel-acq semantics. If the concurrent kworker
1583  * observes the old done tail, the newly queued work
1584  * execution will process the updated done tail. If the
1585  * concurrent kworker observes the new done tail, then
1586  * the newly queued work will skip processing the done
1587  * tail, as workqueue semantics guarantees that the new
1588  * work is executed only after the previous one completes.
1589  *
1590  * f. kworker callbacks processing complete:
1591  *
1592  *
1593  *                   DONE TAIL
1594  *                     |
1595  *                     |
1596  *                     v
1597  * +----------+     +--------+
1598  * |          |     |        |
1599  * |   head   ------> wait   |
1600  * |          |     | head2  |
1601  * +----------+     +--------+
1602  *
1603  */
1604 static bool rcu_sr_is_wait_head(struct llist_node *node)
1605 {
1606 	return &(rcu_state.srs_wait_nodes)[0].node <= node &&
1607 		node <= &(rcu_state.srs_wait_nodes)[SR_NORMAL_GP_WAIT_HEAD_MAX - 1].node;
1608 }
1609 
1610 static struct llist_node *rcu_sr_get_wait_head(void)
1611 {
1612 	struct sr_wait_node *sr_wn;
1613 	int i;
1614 
1615 	for (i = 0; i < SR_NORMAL_GP_WAIT_HEAD_MAX; i++) {
1616 		sr_wn = &(rcu_state.srs_wait_nodes)[i];
1617 
1618 		if (!atomic_cmpxchg_acquire(&sr_wn->inuse, 0, 1))
1619 			return &sr_wn->node;
1620 	}
1621 
1622 	return NULL;
1623 }
1624 
1625 static void rcu_sr_put_wait_head(struct llist_node *node)
1626 {
1627 	struct sr_wait_node *sr_wn = container_of(node, struct sr_wait_node, node);
1628 
1629 	atomic_set_release(&sr_wn->inuse, 0);
1630 }
1631 
1632 static int rcu_normal_wake_from_gp = 1;
1633 module_param(rcu_normal_wake_from_gp, int, 0644);
1634 static struct workqueue_struct *sync_wq;
1635 
1636 #define RCU_SR_NORMAL_LATCH_THR 64
1637 
1638 /* Number of in-flight synchronize_rcu() calls queued on srs_next. */
1639 static atomic_long_t rcu_sr_normal_count;
1640 static int rcu_sr_normal_latched; /* 0/1 */
1641 
1642 static void rcu_sr_normal_complete(struct llist_node *node)
1643 {
1644 	struct rcu_synchronize *rs = container_of(
1645 		(struct rcu_head *) node, struct rcu_synchronize, head);
1646 	long nr;
1647 
1648 	WARN_ONCE(IS_ENABLED(CONFIG_PROVE_RCU) &&
1649 		!poll_state_synchronize_rcu_full(&rs->oldstate),
1650 		"A full grace period is not passed yet!\n");
1651 
1652 	/* Finally. */
1653 	complete(&rs->completion);
1654 	nr = atomic_long_dec_return(&rcu_sr_normal_count);
1655 	WARN_ON_ONCE(nr < 0);
1656 
1657 	/*
1658 	 * Unlatch: switch back to normal path when fully
1659 	 * drained and if it has been latched.
1660 	 */
1661 	if (nr == 0)
1662 		(void)cmpxchg_relaxed(&rcu_sr_normal_latched, 1, 0);
1663 }
1664 
1665 static void rcu_sr_normal_gp_cleanup_work(struct work_struct *work)
1666 {
1667 	struct llist_node *done, *rcu, *next, *head;
1668 
1669 	/*
1670 	 * This work execution can potentially execute
1671 	 * while a new done tail is being updated by
1672 	 * grace period kthread in rcu_sr_normal_gp_cleanup().
1673 	 * So, read and updates of done tail need to
1674 	 * follow acq-rel semantics.
1675 	 *
1676 	 * Given that wq semantics guarantees that a single work
1677 	 * cannot execute concurrently by multiple kworkers,
1678 	 * the done tail list manipulations are protected here.
1679 	 */
1680 	done = smp_load_acquire(&rcu_state.srs_done_tail);
1681 	if (WARN_ON_ONCE(!done))
1682 		return;
1683 
1684 	WARN_ON_ONCE(!rcu_sr_is_wait_head(done));
1685 	head = done->next;
1686 	done->next = NULL;
1687 
1688 	/*
1689 	 * The dummy node, which is pointed to by the
1690 	 * done tail which is acq-read above is not removed
1691 	 * here.  This allows lockless additions of new
1692 	 * rcu_synchronize nodes in rcu_sr_normal_add_req(),
1693 	 * while the cleanup work executes. The dummy
1694 	 * nodes is removed, in next round of cleanup
1695 	 * work execution.
1696 	 */
1697 	llist_for_each_safe(rcu, next, head) {
1698 		if (!rcu_sr_is_wait_head(rcu)) {
1699 			rcu_sr_normal_complete(rcu);
1700 			continue;
1701 		}
1702 
1703 		rcu_sr_put_wait_head(rcu);
1704 	}
1705 
1706 	/* Order list manipulations with atomic access. */
1707 	atomic_dec_return_release(&rcu_state.srs_cleanups_pending);
1708 }
1709 
1710 /*
1711  * Helper function for rcu_gp_cleanup().
1712  */
1713 static void rcu_sr_normal_gp_cleanup(void)
1714 {
1715 	struct llist_node *wait_tail, *next = NULL, *rcu = NULL;
1716 	int done = 0;
1717 
1718 	wait_tail = rcu_state.srs_wait_tail;
1719 	if (wait_tail == NULL)
1720 		return;
1721 
1722 	rcu_state.srs_wait_tail = NULL;
1723 	ASSERT_EXCLUSIVE_WRITER(rcu_state.srs_wait_tail);
1724 	WARN_ON_ONCE(!rcu_sr_is_wait_head(wait_tail));
1725 
1726 	/*
1727 	 * Process (a) and (d) cases. See an illustration.
1728 	 */
1729 	llist_for_each_safe(rcu, next, wait_tail->next) {
1730 		if (rcu_sr_is_wait_head(rcu))
1731 			break;
1732 
1733 		rcu_sr_normal_complete(rcu);
1734 		// It can be last, update a next on this step.
1735 		wait_tail->next = next;
1736 
1737 		if (++done == SR_MAX_USERS_WAKE_FROM_GP)
1738 			break;
1739 	}
1740 
1741 	/*
1742 	 * Fast path, no more users to process except putting the second last
1743 	 * wait head if no inflight-workers. If there are in-flight workers,
1744 	 * they will remove the last wait head.
1745 	 *
1746 	 * Note that the ACQUIRE orders atomic access with list manipulation.
1747 	 */
1748 	if (wait_tail->next && wait_tail->next->next == NULL &&
1749 	    rcu_sr_is_wait_head(wait_tail->next) &&
1750 	    !atomic_read_acquire(&rcu_state.srs_cleanups_pending)) {
1751 		rcu_sr_put_wait_head(wait_tail->next);
1752 		wait_tail->next = NULL;
1753 	}
1754 
1755 	/* Concurrent sr_normal_gp_cleanup work might observe this update. */
1756 	ASSERT_EXCLUSIVE_WRITER(rcu_state.srs_done_tail);
1757 	smp_store_release(&rcu_state.srs_done_tail, wait_tail);
1758 
1759 	/*
1760 	 * We schedule a work in order to perform a final processing
1761 	 * of outstanding users(if still left) and releasing wait-heads
1762 	 * added by rcu_sr_normal_gp_init() call.
1763 	 */
1764 	if (wait_tail->next) {
1765 		atomic_inc(&rcu_state.srs_cleanups_pending);
1766 		if (!queue_work(sync_wq, &rcu_state.srs_cleanup_work))
1767 			atomic_dec(&rcu_state.srs_cleanups_pending);
1768 	}
1769 }
1770 
1771 /*
1772  * Helper function for rcu_gp_init().
1773  */
1774 static bool rcu_sr_normal_gp_init(void)
1775 {
1776 	struct llist_node *first;
1777 	struct llist_node *wait_head;
1778 	bool start_new_poll = false;
1779 
1780 	first = READ_ONCE(rcu_state.srs_next.first);
1781 	if (!first || rcu_sr_is_wait_head(first))
1782 		return start_new_poll;
1783 
1784 	wait_head = rcu_sr_get_wait_head();
1785 	if (!wait_head) {
1786 		// Kick another GP to retry.
1787 		start_new_poll = true;
1788 		return start_new_poll;
1789 	}
1790 
1791 	/* Inject a wait-dummy-node. */
1792 	llist_add(wait_head, &rcu_state.srs_next);
1793 
1794 	/*
1795 	 * A waiting list of rcu_synchronize nodes should be empty on
1796 	 * this step, since a GP-kthread, rcu_gp_init() -> gp_cleanup(),
1797 	 * rolls it over. If not, it is a BUG, warn a user.
1798 	 */
1799 	WARN_ON_ONCE(rcu_state.srs_wait_tail != NULL);
1800 	rcu_state.srs_wait_tail = wait_head;
1801 	ASSERT_EXCLUSIVE_WRITER(rcu_state.srs_wait_tail);
1802 
1803 	return start_new_poll;
1804 }
1805 
1806 static void rcu_sr_normal_add_req(struct rcu_synchronize *rs)
1807 {
1808 	/*
1809 	 * Increment before publish to avoid a complete
1810 	 * vs enqueue race on latch.
1811 	 */
1812 	long nr = atomic_long_inc_return(&rcu_sr_normal_count);
1813 
1814 	/*
1815 	 * Latch when threshold is reached. Checking for an exact match
1816 	 * restricts cmpxchg() to a single context.
1817 	 *
1818 	 * This latch is intentionally relaxed and best-effort. Concurrent
1819 	 * set/clear can race and temporarily lose the latch, which is OK
1820 	 * because it only selects between the fast and fallback paths.
1821 	 */
1822 	if (nr == RCU_SR_NORMAL_LATCH_THR)
1823 		(void)cmpxchg_relaxed(&rcu_sr_normal_latched, 0, 1);
1824 
1825 	/* Publish for the GP kthread/worker. */
1826 	llist_add((struct llist_node *) &rs->head, &rcu_state.srs_next);
1827 }
1828 
1829 /*
1830  * Initialize a new grace period.  Return false if no grace period required.
1831  */
1832 static noinline_for_stack bool rcu_gp_init(void)
1833 {
1834 	unsigned long flags;
1835 	unsigned long oldmask;
1836 	unsigned long mask;
1837 	struct rcu_data *rdp;
1838 	struct rcu_node *rnp = rcu_get_root();
1839 	bool start_new_poll;
1840 	unsigned long old_gp_seq;
1841 
1842 	WRITE_ONCE(rcu_state.gp_activity, jiffies);
1843 	raw_spin_lock_irq_rcu_node(rnp);
1844 	if (!rcu_state.gp_flags) {
1845 		/* Spurious wakeup, tell caller to go back to sleep.  */
1846 		raw_spin_unlock_irq_rcu_node(rnp);
1847 		return false;
1848 	}
1849 	WRITE_ONCE(rcu_state.gp_flags, 0); /* Clear all flags: New GP. */
1850 
1851 	if (WARN_ON_ONCE(rcu_gp_in_progress())) {
1852 		/*
1853 		 * Grace period already in progress, don't start another.
1854 		 * Not supposed to be able to happen.
1855 		 */
1856 		raw_spin_unlock_irq_rcu_node(rnp);
1857 		return false;
1858 	}
1859 
1860 	/* Advance to a new grace period and initialize state. */
1861 	record_gp_stall_check_time();
1862 	/*
1863 	 * A new wait segment must be started before gp_seq advanced, so
1864 	 * that previous gp waiters won't observe the new gp_seq.
1865 	 */
1866 	start_new_poll = rcu_sr_normal_gp_init();
1867 	/* Record GP times before starting GP, hence rcu_seq_start(). */
1868 	old_gp_seq = rcu_state.gp_seq;
1869 	/*
1870 	 * Critical ordering: rcu_seq_start() must happen BEFORE the CPU hotplug
1871 	 * scan below. Otherwise we risk a race where a newly onlining CPU could
1872 	 * be missed by the current grace period, potentially leading to
1873 	 * use-after-free errors. For a detailed explanation of this race, see
1874 	 * Documentation/RCU/Design/Requirements/Requirements.rst in the
1875 	 * "Hotplug CPU" section.
1876 	 *
1877 	 * Also note that the root rnp's gp_seq is kept separate from, and lags,
1878 	 * the rcu_state's gp_seq, for a reason. See the Quick-Quiz on
1879 	 * Single-node systems for more details (in Data-Structures.rst).
1880 	 */
1881 	rcu_seq_start(&rcu_state.gp_seq);
1882 	/* Ensure that rcu_seq_done_exact() guardband doesn't give false positives. */
1883 	WARN_ON_ONCE(IS_ENABLED(CONFIG_PROVE_RCU) &&
1884 		     rcu_seq_done_exact(&old_gp_seq, rcu_seq_snap(&rcu_state.gp_seq)));
1885 
1886 	ASSERT_EXCLUSIVE_WRITER(rcu_state.gp_seq);
1887 	trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq, TPS("start"));
1888 	rcu_poll_gp_seq_start(&rcu_state.gp_seq_polled_snap);
1889 	raw_spin_unlock_irq_rcu_node(rnp);
1890 
1891 	/*
1892 	 * The "start_new_poll" is set to true, only when this GP is not able
1893 	 * to handle anything and there are outstanding users. It happens when
1894 	 * the rcu_sr_normal_gp_init() function was not able to insert a dummy
1895 	 * separator to the llist, because there were no left any dummy-nodes.
1896 	 *
1897 	 * Number of dummy-nodes is fixed, it could be that we are run out of
1898 	 * them, if so we start a new pool request to repeat a try. It is rare
1899 	 * and it means that a system is doing a slow processing of callbacks.
1900 	 */
1901 	if (start_new_poll)
1902 		(void) start_poll_synchronize_rcu();
1903 
1904 	/*
1905 	 * Apply per-leaf buffered online and offline operations to
1906 	 * the rcu_node tree. Note that this new grace period need not
1907 	 * wait for subsequent online CPUs, and that RCU hooks in the CPU
1908 	 * offlining path, when combined with checks in this function,
1909 	 * will handle CPUs that are currently going offline or that will
1910 	 * go offline later.  Please also refer to "Hotplug CPU" section
1911 	 * of RCU's Requirements documentation.
1912 	 */
1913 	WRITE_ONCE(rcu_state.gp_state, RCU_GP_ONOFF);
1914 	/* Exclude CPU hotplug operations. */
1915 	rcu_for_each_leaf_node(rnp) {
1916 		local_irq_disable();
1917 		/*
1918 		 * Serialize with CPU offline. See Requirements.rst > Hotplug CPU >
1919 		 * Concurrent Quiescent State Reporting for Offline CPUs.
1920 		 */
1921 		arch_spin_lock(&rcu_state.ofl_lock);
1922 		raw_spin_lock_rcu_node(rnp);
1923 		if (rnp->qsmaskinit == rnp->qsmaskinitnext &&
1924 		    !rnp->wait_blkd_tasks) {
1925 			/* Nothing to do on this leaf rcu_node structure. */
1926 			raw_spin_unlock_rcu_node(rnp);
1927 			arch_spin_unlock(&rcu_state.ofl_lock);
1928 			local_irq_enable();
1929 			continue;
1930 		}
1931 
1932 		/* Record old state, apply changes to ->qsmaskinit field. */
1933 		oldmask = rnp->qsmaskinit;
1934 		rnp->qsmaskinit = rnp->qsmaskinitnext;
1935 
1936 		/* If zero-ness of ->qsmaskinit changed, propagate up tree. */
1937 		if (!oldmask != !rnp->qsmaskinit) {
1938 			if (!oldmask) { /* First online CPU for rcu_node. */
1939 				if (!rnp->wait_blkd_tasks) /* Ever offline? */
1940 					rcu_init_new_rnp(rnp);
1941 			} else if (rcu_preempt_has_tasks(rnp)) {
1942 				rnp->wait_blkd_tasks = true; /* blocked tasks */
1943 			} else { /* Last offline CPU and can propagate. */
1944 				rcu_cleanup_dead_rnp(rnp);
1945 			}
1946 		}
1947 
1948 		/*
1949 		 * If all waited-on tasks from prior grace period are
1950 		 * done, and if all this rcu_node structure's CPUs are
1951 		 * still offline, propagate up the rcu_node tree and
1952 		 * clear ->wait_blkd_tasks.  Otherwise, if one of this
1953 		 * rcu_node structure's CPUs has since come back online,
1954 		 * simply clear ->wait_blkd_tasks.
1955 		 */
1956 		if (rnp->wait_blkd_tasks &&
1957 		    (!rcu_preempt_has_tasks(rnp) || rnp->qsmaskinit)) {
1958 			rnp->wait_blkd_tasks = false;
1959 			if (!rnp->qsmaskinit)
1960 				rcu_cleanup_dead_rnp(rnp);
1961 		}
1962 
1963 		raw_spin_unlock_rcu_node(rnp);
1964 		arch_spin_unlock(&rcu_state.ofl_lock);
1965 		local_irq_enable();
1966 	}
1967 	rcu_gp_slow(gp_preinit_delay); /* Races with CPU hotplug. */
1968 
1969 	/*
1970 	 * Set the quiescent-state-needed bits in all the rcu_node
1971 	 * structures for all currently online CPUs in breadth-first
1972 	 * order, starting from the root rcu_node structure, relying on the
1973 	 * layout of the tree within the rcu_state.node[] array.  Note that
1974 	 * other CPUs will access only the leaves of the hierarchy, thus
1975 	 * seeing that no grace period is in progress, at least until the
1976 	 * corresponding leaf node has been initialized.
1977 	 *
1978 	 * The grace period cannot complete until the initialization
1979 	 * process finishes, because this kthread handles both.
1980 	 */
1981 	WRITE_ONCE(rcu_state.gp_state, RCU_GP_INIT);
1982 	rcu_for_each_node_breadth_first(rnp) {
1983 		rcu_gp_slow(gp_init_delay);
1984 		raw_spin_lock_irqsave_rcu_node(rnp, flags);
1985 		rdp = this_cpu_ptr(&rcu_data);
1986 		rcu_preempt_check_blocked_tasks(rnp);
1987 		rnp->qsmask = rnp->qsmaskinit;
1988 		WRITE_ONCE(rnp->gp_seq, rcu_state.gp_seq);
1989 		if (rnp == rdp->mynode)
1990 			(void)__note_gp_changes(rnp, rdp);
1991 		rcu_preempt_boost_start_gp(rnp);
1992 		trace_rcu_grace_period_init(rcu_state.name, rnp->gp_seq,
1993 					    rnp->level, rnp->grplo,
1994 					    rnp->grphi, rnp->qsmask);
1995 		/*
1996 		 * Quiescent states for tasks on any now-offline CPUs. Since we
1997 		 * released the ofl and rnp lock before this loop, CPUs might
1998 		 * have gone offline and we have to report QS on their behalf.
1999 		 * See Requirements.rst > Hotplug CPU > Concurrent QS Reporting.
2000 		 */
2001 		mask = rnp->qsmask & ~rnp->qsmaskinitnext;
2002 		rnp->rcu_gp_init_mask = mask;
2003 		if ((mask || rnp->wait_blkd_tasks) && rcu_is_leaf_node(rnp))
2004 			rcu_report_qs_rnp(mask, rnp, rnp->gp_seq, flags);
2005 		else
2006 			raw_spin_unlock_irq_rcu_node(rnp);
2007 		cond_resched_tasks_rcu_qs();
2008 		WRITE_ONCE(rcu_state.gp_activity, jiffies);
2009 	}
2010 
2011 	// If strict, make all CPUs aware of new grace period.
2012 	if (IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD))
2013 		on_each_cpu(rcu_strict_gp_boundary, NULL, 0);
2014 
2015 	/*
2016 	 * Immediately report QS for the GP kthread's CPU. The GP kthread
2017 	 * cannot be in an RCU read-side critical section while running
2018 	 * the FQS scan. This eliminates the need for a second FQS wait
2019 	 * when all CPUs are idle.
2020 	 */
2021 	preempt_disable();
2022 	rcu_qs();
2023 	rcu_report_qs_rdp(this_cpu_ptr(&rcu_data));
2024 	preempt_enable();
2025 
2026 	return true;
2027 }
2028 
2029 /*
2030  * Helper function for swait_event_idle_exclusive() wakeup at force-quiescent-state
2031  * time.
2032  */
2033 static bool rcu_gp_fqs_check_wake(int *gfp)
2034 {
2035 	struct rcu_node *rnp = rcu_get_root();
2036 
2037 	// If under overload conditions, force an immediate FQS scan.
2038 	if (*gfp & RCU_GP_FLAG_OVLD)
2039 		return true;
2040 
2041 	// Someone like call_rcu() requested a force-quiescent-state scan.
2042 	*gfp = READ_ONCE(rcu_state.gp_flags);
2043 	if (*gfp & RCU_GP_FLAG_FQS)
2044 		return true;
2045 
2046 	// The current grace period has completed.
2047 	if (!READ_ONCE(rnp->qsmask) && !rcu_preempt_blocked_readers_cgp(rnp))
2048 		return true;
2049 
2050 	return false;
2051 }
2052 
2053 /*
2054  * Do one round of quiescent-state forcing.
2055  */
2056 static void rcu_gp_fqs(bool first_time)
2057 {
2058 	int nr_fqs = READ_ONCE(rcu_state.nr_fqs_jiffies_stall);
2059 	struct rcu_node *rnp = rcu_get_root();
2060 
2061 	WRITE_ONCE(rcu_state.gp_activity, jiffies);
2062 	WRITE_ONCE(rcu_state.n_force_qs, rcu_state.n_force_qs + 1);
2063 
2064 	WARN_ON_ONCE(nr_fqs > 3);
2065 	/* Only countdown nr_fqs for stall purposes if jiffies moves. */
2066 	if (nr_fqs) {
2067 		if (nr_fqs == 1) {
2068 			WRITE_ONCE(rcu_state.jiffies_stall,
2069 				   jiffies + rcu_jiffies_till_stall_check());
2070 		}
2071 		WRITE_ONCE(rcu_state.nr_fqs_jiffies_stall, --nr_fqs);
2072 	}
2073 
2074 	if (first_time) {
2075 		/* Collect dyntick-idle snapshots. */
2076 		force_qs_rnp(rcu_watching_snap_save);
2077 	} else {
2078 		/* Handle dyntick-idle and offline CPUs. */
2079 		force_qs_rnp(rcu_watching_snap_recheck);
2080 	}
2081 	/* Clear flag to prevent immediate re-entry. */
2082 	if (READ_ONCE(rcu_state.gp_flags) & RCU_GP_FLAG_FQS) {
2083 		raw_spin_lock_irq_rcu_node(rnp);
2084 		WRITE_ONCE(rcu_state.gp_flags, rcu_state.gp_flags & ~RCU_GP_FLAG_FQS);
2085 		raw_spin_unlock_irq_rcu_node(rnp);
2086 	}
2087 }
2088 
2089 /*
2090  * Loop doing repeated quiescent-state forcing until the grace period ends.
2091  */
2092 static noinline_for_stack void rcu_gp_fqs_loop(void)
2093 {
2094 	bool first_gp_fqs = true;
2095 	int gf = 0;
2096 	unsigned long j;
2097 	int ret;
2098 	struct rcu_node *rnp = rcu_get_root();
2099 
2100 	j = READ_ONCE(jiffies_till_first_fqs);
2101 	if (rcu_state.cbovld)
2102 		gf = RCU_GP_FLAG_OVLD;
2103 	ret = 0;
2104 	for (;;) {
2105 		if (rcu_state.cbovld) {
2106 			j = (j + 2) / 3;
2107 			if (j <= 0)
2108 				j = 1;
2109 		}
2110 		if (!ret || time_before(jiffies + j, rcu_state.jiffies_force_qs)) {
2111 			WRITE_ONCE(rcu_state.jiffies_force_qs, jiffies + j);
2112 			/*
2113 			 * jiffies_force_qs before RCU_GP_WAIT_FQS state
2114 			 * update; required for stall checks.
2115 			 */
2116 			smp_wmb();
2117 			WRITE_ONCE(rcu_state.jiffies_kick_kthreads,
2118 				   jiffies + (j ? 3 * j : 2));
2119 		}
2120 		trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
2121 				       TPS("fqswait"));
2122 		WRITE_ONCE(rcu_state.gp_state, RCU_GP_WAIT_FQS);
2123 		(void)swait_event_idle_timeout_exclusive(rcu_state.gp_wq,
2124 				 rcu_gp_fqs_check_wake(&gf), j);
2125 		rcu_gp_torture_wait();
2126 		WRITE_ONCE(rcu_state.gp_state, RCU_GP_DOING_FQS);
2127 		/* Locking provides needed memory barriers. */
2128 		/*
2129 		 * Exit the loop if the root rcu_node structure indicates that the grace period
2130 		 * has ended, leave the loop.  The rcu_preempt_blocked_readers_cgp(rnp) check
2131 		 * is required only for single-node rcu_node trees because readers blocking
2132 		 * the current grace period are queued only on leaf rcu_node structures.
2133 		 * For multi-node trees, checking the root node's ->qsmask suffices, because a
2134 		 * given root node's ->qsmask bit is cleared only when all CPUs and tasks from
2135 		 * the corresponding leaf nodes have passed through their quiescent state.
2136 		 */
2137 		if (!READ_ONCE(rnp->qsmask) &&
2138 		    !rcu_preempt_blocked_readers_cgp(rnp))
2139 			break;
2140 		/* If time for quiescent-state forcing, do it. */
2141 		if (!time_after(rcu_state.jiffies_force_qs, jiffies) ||
2142 		    (gf & (RCU_GP_FLAG_FQS | RCU_GP_FLAG_OVLD))) {
2143 			trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
2144 					       TPS("fqsstart"));
2145 			rcu_gp_fqs(first_gp_fqs);
2146 			gf = 0;
2147 			if (first_gp_fqs) {
2148 				first_gp_fqs = false;
2149 				gf = rcu_state.cbovld ? RCU_GP_FLAG_OVLD : 0;
2150 			}
2151 			trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
2152 					       TPS("fqsend"));
2153 			cond_resched_tasks_rcu_qs();
2154 			WRITE_ONCE(rcu_state.gp_activity, jiffies);
2155 			ret = 0; /* Force full wait till next FQS. */
2156 			j = READ_ONCE(jiffies_till_next_fqs);
2157 		} else {
2158 			/* Deal with stray signal. */
2159 			cond_resched_tasks_rcu_qs();
2160 			WRITE_ONCE(rcu_state.gp_activity, jiffies);
2161 			WARN_ON(signal_pending(current));
2162 			trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
2163 					       TPS("fqswaitsig"));
2164 			ret = 1; /* Keep old FQS timing. */
2165 			j = jiffies;
2166 			if (time_after(jiffies, rcu_state.jiffies_force_qs))
2167 				j = 1;
2168 			else
2169 				j = rcu_state.jiffies_force_qs - j;
2170 			gf = 0;
2171 		}
2172 	}
2173 }
2174 
2175 /*
2176  * Clean up after the old grace period.
2177  */
2178 static noinline void rcu_gp_cleanup(void)
2179 {
2180 	int cpu;
2181 	bool needgp = false;
2182 	unsigned long gp_duration;
2183 	unsigned long new_gp_seq;
2184 	bool offloaded;
2185 	struct rcu_data *rdp;
2186 	struct rcu_node *rnp = rcu_get_root();
2187 	struct swait_queue_head *sq;
2188 
2189 	WRITE_ONCE(rcu_state.gp_activity, jiffies);
2190 	raw_spin_lock_irq_rcu_node(rnp);
2191 	rcu_state.gp_end = jiffies;
2192 	gp_duration = rcu_state.gp_end - rcu_state.gp_start;
2193 	if (gp_duration > rcu_state.gp_max)
2194 		rcu_state.gp_max = gp_duration;
2195 
2196 	/*
2197 	 * We know the grace period is complete, but to everyone else
2198 	 * it appears to still be ongoing.  But it is also the case
2199 	 * that to everyone else it looks like there is nothing that
2200 	 * they can do to advance the grace period.  It is therefore
2201 	 * safe for us to drop the lock in order to mark the grace
2202 	 * period as completed in all of the rcu_node structures.
2203 	 */
2204 	rcu_poll_gp_seq_end(&rcu_state.gp_seq_polled_snap);
2205 	raw_spin_unlock_irq_rcu_node(rnp);
2206 
2207 	/*
2208 	 * Propagate new ->gp_seq value to rcu_node structures so that
2209 	 * other CPUs don't have to wait until the start of the next grace
2210 	 * period to process their callbacks.  This also avoids some nasty
2211 	 * RCU grace-period initialization races by forcing the end of
2212 	 * the current grace period to be completely recorded in all of
2213 	 * the rcu_node structures before the beginning of the next grace
2214 	 * period is recorded in any of the rcu_node structures.
2215 	 */
2216 	new_gp_seq = rcu_state.gp_seq;
2217 	rcu_seq_end(&new_gp_seq);
2218 	rcu_for_each_node_breadth_first(rnp) {
2219 		raw_spin_lock_irq_rcu_node(rnp);
2220 		if (WARN_ON_ONCE(rcu_preempt_blocked_readers_cgp(rnp)))
2221 			dump_blkd_tasks(rnp, 10);
2222 		WARN_ON_ONCE(rnp->qsmask);
2223 		WRITE_ONCE(rnp->gp_seq, new_gp_seq);
2224 		if (!rnp->parent)
2225 			smp_mb(); // Order against failing poll_state_synchronize_rcu_full().
2226 		rdp = this_cpu_ptr(&rcu_data);
2227 		if (rnp == rdp->mynode)
2228 			needgp = __note_gp_changes(rnp, rdp) || needgp;
2229 		/* smp_mb() provided by prior unlock-lock pair. */
2230 		needgp = rcu_future_gp_cleanup(rnp) || needgp;
2231 		// Reset overload indication for CPUs no longer overloaded
2232 		if (rcu_is_leaf_node(rnp))
2233 			for_each_leaf_node_cpu_mask(rnp, cpu, rnp->cbovldmask) {
2234 				rdp = per_cpu_ptr(&rcu_data, cpu);
2235 				check_cb_ovld_locked(rdp, rnp);
2236 			}
2237 		sq = rcu_nocb_gp_get(rnp);
2238 		raw_spin_unlock_irq_rcu_node(rnp);
2239 		rcu_nocb_gp_cleanup(sq);
2240 		cond_resched_tasks_rcu_qs();
2241 		WRITE_ONCE(rcu_state.gp_activity, jiffies);
2242 		rcu_gp_slow(gp_cleanup_delay);
2243 	}
2244 	rnp = rcu_get_root();
2245 	raw_spin_lock_irq_rcu_node(rnp); /* GP before ->gp_seq update. */
2246 
2247 	/* Declare grace period done, trace first to use old GP number. */
2248 	trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq, TPS("end"));
2249 	rcu_seq_end(&rcu_state.gp_seq);
2250 	ASSERT_EXCLUSIVE_WRITER(rcu_state.gp_seq);
2251 	WRITE_ONCE(rcu_state.gp_state, RCU_GP_IDLE);
2252 	/* Check for GP requests since above loop. */
2253 	rdp = this_cpu_ptr(&rcu_data);
2254 	if (!needgp && ULONG_CMP_LT(rnp->gp_seq, rnp->gp_seq_needed)) {
2255 		trace_rcu_this_gp(rnp, rdp, rnp->gp_seq_needed,
2256 				  TPS("CleanupMore"));
2257 		needgp = true;
2258 	}
2259 	/* Advance CBs to reduce false positives below. */
2260 	offloaded = rcu_rdp_is_offloaded(rdp);
2261 	if ((offloaded || !rcu_accelerate_cbs(rnp, rdp)) && needgp) {
2262 
2263 		// We get here if a grace period was needed (“needgp”)
2264 		// and the above call to rcu_accelerate_cbs() did not set
2265 		// the RCU_GP_FLAG_INIT bit in ->gp_state (which records
2266 		// the need for another grace period).  The purpose
2267 		// of the “offloaded” check is to avoid invoking
2268 		// rcu_accelerate_cbs() on an offloaded CPU because we do not
2269 		// hold the ->nocb_lock needed to safely access an offloaded
2270 		// ->cblist.  We do not want to acquire that lock because
2271 		// it can be heavily contended during callback floods.
2272 
2273 		WRITE_ONCE(rcu_state.gp_flags, RCU_GP_FLAG_INIT);
2274 		WRITE_ONCE(rcu_state.gp_req_activity, jiffies);
2275 		trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq, TPS("newreq"));
2276 	} else {
2277 
2278 		// We get here either if there is no need for an
2279 		// additional grace period or if rcu_accelerate_cbs() has
2280 		// already set the RCU_GP_FLAG_INIT bit in ->gp_flags. 
2281 		// So all we need to do is to clear all of the other
2282 		// ->gp_flags bits.
2283 
2284 		WRITE_ONCE(rcu_state.gp_flags, rcu_state.gp_flags & RCU_GP_FLAG_INIT);
2285 	}
2286 	raw_spin_unlock_irq_rcu_node(rnp);
2287 
2288 	// Make synchronize_rcu() users aware of the end of old grace period.
2289 	rcu_sr_normal_gp_cleanup();
2290 
2291 	// If strict, make all CPUs aware of the end of the old grace period.
2292 	if (IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD))
2293 		on_each_cpu(rcu_strict_gp_boundary, NULL, 0);
2294 }
2295 
2296 /*
2297  * Body of kthread that handles grace periods.
2298  */
2299 static int __noreturn rcu_gp_kthread(void *unused)
2300 {
2301 	rcu_bind_gp_kthread();
2302 	for (;;) {
2303 
2304 		/* Handle grace-period start. */
2305 		for (;;) {
2306 			trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
2307 					       TPS("reqwait"));
2308 			WRITE_ONCE(rcu_state.gp_state, RCU_GP_WAIT_GPS);
2309 			swait_event_idle_exclusive(rcu_state.gp_wq,
2310 					 READ_ONCE(rcu_state.gp_flags) &
2311 					 RCU_GP_FLAG_INIT);
2312 			rcu_gp_torture_wait();
2313 			WRITE_ONCE(rcu_state.gp_state, RCU_GP_DONE_GPS);
2314 			/* Locking provides needed memory barrier. */
2315 			if (rcu_gp_init())
2316 				break;
2317 			cond_resched_tasks_rcu_qs();
2318 			WRITE_ONCE(rcu_state.gp_activity, jiffies);
2319 			WARN_ON(signal_pending(current));
2320 			trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
2321 					       TPS("reqwaitsig"));
2322 		}
2323 
2324 		/* Handle quiescent-state forcing. */
2325 		rcu_gp_fqs_loop();
2326 
2327 		/* Handle grace-period end. */
2328 		WRITE_ONCE(rcu_state.gp_state, RCU_GP_CLEANUP);
2329 		rcu_gp_cleanup();
2330 		WRITE_ONCE(rcu_state.gp_state, RCU_GP_CLEANED);
2331 	}
2332 }
2333 
2334 /*
2335  * Report a full set of quiescent states to the rcu_state data structure.
2336  * Invoke rcu_gp_kthread_wake() to awaken the grace-period kthread if
2337  * another grace period is required.  Whether we wake the grace-period
2338  * kthread or it awakens itself for the next round of quiescent-state
2339  * forcing, that kthread will clean up after the just-completed grace
2340  * period.  Note that the caller must hold rnp->lock, which is released
2341  * before return.
2342  */
2343 static void rcu_report_qs_rsp(unsigned long flags)
2344 	__releases(rcu_get_root()->lock)
2345 {
2346 	raw_lockdep_assert_held_rcu_node(rcu_get_root());
2347 	WARN_ON_ONCE(!rcu_gp_in_progress());
2348 	WRITE_ONCE(rcu_state.gp_flags, rcu_state.gp_flags | RCU_GP_FLAG_FQS);
2349 	raw_spin_unlock_irqrestore_rcu_node(rcu_get_root(), flags);
2350 	rcu_gp_kthread_wake();
2351 }
2352 
2353 /*
2354  * Similar to rcu_report_qs_rdp(), for which it is a helper function.
2355  * Allows quiescent states for a group of CPUs to be reported at one go
2356  * to the specified rcu_node structure, though all the CPUs in the group
2357  * must be represented by the same rcu_node structure (which need not be a
2358  * leaf rcu_node structure, though it often will be).  The gps parameter
2359  * is the grace-period snapshot, which means that the quiescent states
2360  * are valid only if rnp->gp_seq is equal to gps.  That structure's lock
2361  * must be held upon entry, and it is released before return.
2362  *
2363  * As a special case, if mask is zero, the bit-already-cleared check is
2364  * disabled.  This allows propagating quiescent state due to resumed tasks
2365  * during grace-period initialization.
2366  */
2367 static void rcu_report_qs_rnp(unsigned long mask, struct rcu_node *rnp,
2368 			      unsigned long gps, unsigned long flags)
2369 	__releases(rnp->lock)
2370 {
2371 	unsigned long oldmask = 0;
2372 	struct rcu_node *rnp_c;
2373 
2374 	raw_lockdep_assert_held_rcu_node(rnp);
2375 
2376 	/* Walk up the rcu_node hierarchy. */
2377 	for (;;) {
2378 		if ((!(rnp->qsmask & mask) && mask) || rnp->gp_seq != gps) {
2379 
2380 			/*
2381 			 * Our bit has already been cleared, or the
2382 			 * relevant grace period is already over, so done.
2383 			 */
2384 			raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2385 			return;
2386 		}
2387 		WARN_ON_ONCE(oldmask); /* Any child must be all zeroed! */
2388 		WARN_ON_ONCE(!rcu_is_leaf_node(rnp) &&
2389 			     rcu_preempt_blocked_readers_cgp(rnp));
2390 		WRITE_ONCE(rnp->qsmask, rnp->qsmask & ~mask);
2391 		trace_rcu_quiescent_state_report(rcu_state.name, rnp->gp_seq,
2392 						 mask, rnp->qsmask, rnp->level,
2393 						 rnp->grplo, rnp->grphi,
2394 						 !!rnp->gp_tasks);
2395 		if (rnp->qsmask != 0 || rcu_preempt_blocked_readers_cgp(rnp)) {
2396 
2397 			/* Other bits still set at this level, so done. */
2398 			raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2399 			return;
2400 		}
2401 		rnp->completedqs = rnp->gp_seq;
2402 		mask = rnp->grpmask;
2403 		if (rnp->parent == NULL) {
2404 
2405 			/* No more levels.  Exit loop holding root lock. */
2406 
2407 			break;
2408 		}
2409 		raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2410 		rnp_c = rnp;
2411 		rnp = rnp->parent;
2412 		raw_spin_lock_irqsave_rcu_node(rnp, flags);
2413 		oldmask = READ_ONCE(rnp_c->qsmask);
2414 	}
2415 
2416 	/*
2417 	 * Get here if we are the last CPU to pass through a quiescent
2418 	 * state for this grace period.  Invoke rcu_report_qs_rsp()
2419 	 * to clean up and start the next grace period if one is needed.
2420 	 */
2421 	rcu_report_qs_rsp(flags); /* releases rnp->lock. */
2422 }
2423 
2424 /*
2425  * Record a quiescent state for all tasks that were previously queued
2426  * on the specified rcu_node structure and that were blocking the current
2427  * RCU grace period.  The caller must hold the corresponding rnp->lock with
2428  * irqs disabled, and this lock is released upon return, but irqs remain
2429  * disabled.
2430  */
2431 static void __maybe_unused
2432 rcu_report_unblock_qs_rnp(struct rcu_node *rnp, unsigned long flags)
2433 	__releases(rnp->lock)
2434 {
2435 	unsigned long gps;
2436 	unsigned long mask;
2437 	struct rcu_node *rnp_p;
2438 
2439 	raw_lockdep_assert_held_rcu_node(rnp);
2440 	if (WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT_RCU)) ||
2441 	    WARN_ON_ONCE(rcu_preempt_blocked_readers_cgp(rnp)) ||
2442 	    rnp->qsmask != 0) {
2443 		raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2444 		return;  /* Still need more quiescent states! */
2445 	}
2446 
2447 	rnp->completedqs = rnp->gp_seq;
2448 	rnp_p = rnp->parent;
2449 	if (rnp_p == NULL) {
2450 		/*
2451 		 * Only one rcu_node structure in the tree, so don't
2452 		 * try to report up to its nonexistent parent!
2453 		 */
2454 		rcu_report_qs_rsp(flags);
2455 		return;
2456 	}
2457 
2458 	/* Report up the rest of the hierarchy, tracking current ->gp_seq. */
2459 	gps = rnp->gp_seq;
2460 	mask = rnp->grpmask;
2461 	raw_spin_unlock_rcu_node(rnp);	/* irqs remain disabled. */
2462 	raw_spin_lock_rcu_node(rnp_p);	/* irqs already disabled. */
2463 	rcu_report_qs_rnp(mask, rnp_p, gps, flags);
2464 }
2465 
2466 /*
2467  * Record a quiescent state for the specified CPU to that CPU's rcu_data
2468  * structure.  This must be called from the specified CPU.
2469  */
2470 static void
2471 rcu_report_qs_rdp(struct rcu_data *rdp)
2472 {
2473 	unsigned long flags;
2474 	unsigned long mask;
2475 	struct rcu_node *rnp;
2476 
2477 	WARN_ON_ONCE(rdp->cpu != smp_processor_id());
2478 	rnp = rdp->mynode;
2479 	raw_spin_lock_irqsave_rcu_node(rnp, flags);
2480 	if (rdp->cpu_no_qs.b.norm || rdp->gp_seq != rnp->gp_seq ||
2481 	    rdp->gpwrap) {
2482 
2483 		/*
2484 		 * The grace period in which this quiescent state was
2485 		 * recorded has ended, so don't report it upwards.
2486 		 * We will instead need a new quiescent state that lies
2487 		 * within the current grace period.
2488 		 */
2489 		rdp->cpu_no_qs.b.norm = true;	/* need qs for new gp. */
2490 		raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2491 		return;
2492 	}
2493 	mask = rdp->grpmask;
2494 	rdp->core_needs_qs = false;
2495 	if ((rnp->qsmask & mask) == 0) {
2496 		raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2497 	} else {
2498 		/*
2499 		 * This GP can't end until cpu checks in, so all of our
2500 		 * callbacks can be processed during the next GP.
2501 		 *
2502 		 * NOCB kthreads have their own way to deal with that...
2503 		 */
2504 		if (!rcu_rdp_is_offloaded(rdp)) {
2505 			/*
2506 			 * The current GP has not yet ended, so it
2507 			 * should not be possible for rcu_accelerate_cbs()
2508 			 * to return true.  So complain, but don't awaken.
2509 			 */
2510 			WARN_ON_ONCE(rcu_accelerate_cbs(rnp, rdp));
2511 		}
2512 
2513 		rcu_disable_urgency_upon_qs(rdp);
2514 		rcu_report_qs_rnp(mask, rnp, rnp->gp_seq, flags);
2515 		/* ^^^ Released rnp->lock */
2516 	}
2517 }
2518 
2519 /*
2520  * Check to see if there is a new grace period of which this CPU
2521  * is not yet aware, and if so, set up local rcu_data state for it.
2522  * Otherwise, see if this CPU has just passed through its first
2523  * quiescent state for this grace period, and record that fact if so.
2524  */
2525 static void
2526 rcu_check_quiescent_state(struct rcu_data *rdp)
2527 {
2528 	/* Check for grace-period ends and beginnings. */
2529 	note_gp_changes(rdp);
2530 
2531 	/*
2532 	 * Does this CPU still need to do its part for current grace period?
2533 	 * If no, return and let the other CPUs do their part as well.
2534 	 */
2535 	if (!rdp->core_needs_qs)
2536 		return;
2537 
2538 	/*
2539 	 * Was there a quiescent state since the beginning of the grace
2540 	 * period? If no, then exit and wait for the next call.
2541 	 */
2542 	if (rdp->cpu_no_qs.b.norm)
2543 		return;
2544 
2545 	/*
2546 	 * Tell RCU we are done (but rcu_report_qs_rdp() will be the
2547 	 * judge of that).
2548 	 */
2549 	rcu_report_qs_rdp(rdp);
2550 }
2551 
2552 /* Return true if callback-invocation time limit exceeded. */
2553 static bool rcu_do_batch_check_time(long count, long tlimit,
2554 				    bool jlimit_check, unsigned long jlimit)
2555 {
2556 	// Invoke local_clock() only once per 32 consecutive callbacks.
2557 	return unlikely(tlimit) &&
2558 	       (!likely(count & 31) ||
2559 		(IS_ENABLED(CONFIG_RCU_DOUBLE_CHECK_CB_TIME) &&
2560 		 jlimit_check && time_after(jiffies, jlimit))) &&
2561 	       local_clock() >= tlimit;
2562 }
2563 
2564 /*
2565  * Invoke any RCU callbacks that have made it to the end of their grace
2566  * period.  Throttle as specified by rdp->blimit.
2567  */
2568 static void rcu_do_batch(struct rcu_data *rdp)
2569 {
2570 	long bl;
2571 	long count = 0;
2572 	int div;
2573 	bool __maybe_unused empty;
2574 	unsigned long flags;
2575 	unsigned long jlimit;
2576 	bool jlimit_check = false;
2577 	long pending;
2578 	struct rcu_cblist rcl = RCU_CBLIST_INITIALIZER(rcl);
2579 	struct rcu_head *rhp;
2580 	long tlimit = 0;
2581 
2582 	/* If no callbacks are ready, just return. */
2583 	if (!rcu_segcblist_ready_cbs(&rdp->cblist)) {
2584 		trace_rcu_batch_start(rcu_state.name,
2585 				      rcu_segcblist_n_cbs(&rdp->cblist), 0);
2586 		trace_rcu_batch_end(rcu_state.name, 0,
2587 				    !rcu_segcblist_empty(&rdp->cblist),
2588 				    need_resched(), is_idle_task(current),
2589 				    rcu_is_callbacks_kthread(rdp));
2590 		return;
2591 	}
2592 
2593 	/*
2594 	 * Extract the list of ready callbacks, disabling IRQs to prevent
2595 	 * races with call_rcu() from interrupt handlers.  Leave the
2596 	 * callback counts, as rcu_barrier() needs to be conservative.
2597 	 *
2598 	 * Callbacks execution is fully ordered against preceding grace period
2599 	 * completion (materialized by rnp->gp_seq update) thanks to the
2600 	 * smp_mb__after_unlock_lock() upon node locking required for callbacks
2601 	 * advancing. In NOCB mode this ordering is then further relayed through
2602 	 * the nocb locking that protects both callbacks advancing and extraction.
2603 	 */
2604 	rcu_nocb_lock_irqsave(rdp, flags);
2605 	WARN_ON_ONCE(cpu_is_offline(smp_processor_id()));
2606 	pending = rcu_segcblist_get_seglen(&rdp->cblist, RCU_DONE_TAIL);
2607 	div = READ_ONCE(rcu_divisor);
2608 	div = div < 0 ? 7 : div > sizeof(long) * 8 - 2 ? sizeof(long) * 8 - 2 : div;
2609 	bl = max(rdp->blimit, pending >> div);
2610 	if ((in_serving_softirq() || rdp->rcu_cpu_kthread_status == RCU_KTHREAD_RUNNING) &&
2611 	    (IS_ENABLED(CONFIG_RCU_DOUBLE_CHECK_CB_TIME) || unlikely(bl > 100))) {
2612 		const long npj = NSEC_PER_SEC / HZ;
2613 		long rrn = READ_ONCE(rcu_resched_ns);
2614 
2615 		rrn = clamp(rrn, NSEC_PER_MSEC, NSEC_PER_SEC);
2616 		tlimit = local_clock() + rrn;
2617 		jlimit = jiffies + (rrn + npj + 1) / npj;
2618 		jlimit_check = true;
2619 	}
2620 	trace_rcu_batch_start(rcu_state.name,
2621 			      rcu_segcblist_n_cbs(&rdp->cblist), bl);
2622 	rcu_segcblist_extract_done_cbs(&rdp->cblist, &rcl);
2623 	if (rcu_rdp_is_offloaded(rdp))
2624 		rdp->qlen_last_fqs_check = rcu_segcblist_n_cbs(&rdp->cblist);
2625 
2626 	trace_rcu_segcb_stats(&rdp->cblist, TPS("SegCbDequeued"));
2627 	rcu_nocb_unlock_irqrestore(rdp, flags);
2628 
2629 	/* Invoke callbacks. */
2630 	tick_dep_set_task(current, TICK_DEP_BIT_RCU);
2631 	rhp = rcu_cblist_dequeue(&rcl);
2632 
2633 	for (; rhp; rhp = rcu_cblist_dequeue(&rcl)) {
2634 		rcu_callback_t f;
2635 
2636 		count++;
2637 		debug_rcu_head_unqueue(rhp);
2638 
2639 		rcu_lock_acquire(&rcu_callback_map);
2640 		trace_rcu_invoke_callback(rcu_state.name, rhp);
2641 
2642 		f = rhp->func;
2643 		debug_rcu_head_callback(rhp);
2644 		WRITE_ONCE(rhp->func, (rcu_callback_t)0L);
2645 		f(rhp);
2646 
2647 		rcu_lock_release(&rcu_callback_map);
2648 
2649 		/*
2650 		 * Stop only if limit reached and CPU has something to do.
2651 		 */
2652 		if (in_serving_softirq()) {
2653 			if (count >= bl && (need_resched() || !is_idle_task(current)))
2654 				break;
2655 			/*
2656 			 * Make sure we don't spend too much time here and deprive other
2657 			 * softirq vectors of CPU cycles.
2658 			 */
2659 			if (rcu_do_batch_check_time(count, tlimit, jlimit_check, jlimit))
2660 				break;
2661 		} else {
2662 			// In rcuc/rcuoc context, so no worries about
2663 			// depriving other softirq vectors of CPU cycles.
2664 			local_bh_enable();
2665 			lockdep_assert_irqs_enabled();
2666 			cond_resched_tasks_rcu_qs();
2667 			lockdep_assert_irqs_enabled();
2668 			local_bh_disable();
2669 			// But rcuc kthreads can delay quiescent-state
2670 			// reporting, so check time limits for them.
2671 			if (rdp->rcu_cpu_kthread_status == RCU_KTHREAD_RUNNING &&
2672 			    rcu_do_batch_check_time(count, tlimit, jlimit_check, jlimit)) {
2673 				rdp->rcu_cpu_has_work = 1;
2674 				break;
2675 			}
2676 		}
2677 	}
2678 
2679 	rcu_nocb_lock_irqsave(rdp, flags);
2680 	rdp->n_cbs_invoked += count;
2681 	trace_rcu_batch_end(rcu_state.name, count, !!rcl.head, need_resched(),
2682 			    is_idle_task(current), rcu_is_callbacks_kthread(rdp));
2683 
2684 	/* Update counts and requeue any remaining callbacks. */
2685 	rcu_segcblist_insert_done_cbs(&rdp->cblist, &rcl);
2686 	rcu_segcblist_add_len(&rdp->cblist, -count);
2687 
2688 	/* Reinstate batch limit if we have worked down the excess. */
2689 	count = rcu_segcblist_n_cbs(&rdp->cblist);
2690 	if (rdp->blimit >= DEFAULT_MAX_RCU_BLIMIT && count <= qlowmark)
2691 		rdp->blimit = blimit;
2692 
2693 	/* Reset ->qlen_last_fqs_check trigger if enough CBs have drained. */
2694 	if (count == 0 && rdp->qlen_last_fqs_check != 0) {
2695 		rdp->qlen_last_fqs_check = 0;
2696 		rdp->n_force_qs_snap = READ_ONCE(rcu_state.n_force_qs);
2697 	} else if (count < rdp->qlen_last_fqs_check - qhimark)
2698 		rdp->qlen_last_fqs_check = count;
2699 
2700 	/*
2701 	 * The following usually indicates a double call_rcu().  To track
2702 	 * this down, try building with CONFIG_DEBUG_OBJECTS_RCU_HEAD=y.
2703 	 */
2704 	empty = rcu_segcblist_empty(&rdp->cblist);
2705 	WARN_ON_ONCE(count == 0 && !empty);
2706 	WARN_ON_ONCE(!IS_ENABLED(CONFIG_RCU_NOCB_CPU) &&
2707 		     count != 0 && empty);
2708 	WARN_ON_ONCE(count == 0 && rcu_segcblist_n_segment_cbs(&rdp->cblist) != 0);
2709 	WARN_ON_ONCE(!empty && rcu_segcblist_n_segment_cbs(&rdp->cblist) == 0);
2710 
2711 	rcu_nocb_unlock_irqrestore(rdp, flags);
2712 
2713 	tick_dep_clear_task(current, TICK_DEP_BIT_RCU);
2714 }
2715 
2716 /*
2717  * This function is invoked from each scheduling-clock interrupt,
2718  * and checks to see if this CPU is in a non-context-switch quiescent
2719  * state, for example, user mode or idle loop.  It also schedules RCU
2720  * core processing.  If the current grace period has gone on too long,
2721  * it will ask the scheduler to manufacture a context switch for the sole
2722  * purpose of providing the needed quiescent state.
2723  */
2724 void rcu_sched_clock_irq(int user)
2725 {
2726 	unsigned long j;
2727 
2728 	if (IS_ENABLED(CONFIG_PROVE_RCU)) {
2729 		j = jiffies;
2730 		WARN_ON_ONCE(time_before(j, __this_cpu_read(rcu_data.last_sched_clock)));
2731 		__this_cpu_write(rcu_data.last_sched_clock, j);
2732 	}
2733 	trace_rcu_utilization(TPS("Start scheduler-tick"));
2734 	lockdep_assert_irqs_disabled();
2735 	raw_cpu_inc(rcu_data.ticks_this_gp);
2736 	/* The load-acquire pairs with the store-release setting to true. */
2737 	if (smp_load_acquire(this_cpu_ptr(&rcu_data.rcu_urgent_qs))) {
2738 		/* Idle and userspace execution already are quiescent states. */
2739 		if (!rcu_is_cpu_rrupt_from_idle() && !user)
2740 			set_need_resched_current();
2741 		__this_cpu_write(rcu_data.rcu_urgent_qs, false);
2742 	}
2743 	rcu_flavor_sched_clock_irq(user);
2744 	if (rcu_pending(user))
2745 		invoke_rcu_core();
2746 	if (user || rcu_is_cpu_rrupt_from_idle())
2747 		rcu_note_voluntary_context_switch(current);
2748 	lockdep_assert_irqs_disabled();
2749 
2750 	trace_rcu_utilization(TPS("End scheduler-tick"));
2751 }
2752 
2753 /*
2754  * Scan the leaf rcu_node structures.  For each structure on which all
2755  * CPUs have reported a quiescent state and on which there are tasks
2756  * blocking the current grace period, initiate RCU priority boosting.
2757  * Otherwise, invoke the specified function to check dyntick state for
2758  * each CPU that has not yet reported a quiescent state.
2759  */
2760 static void force_qs_rnp(int (*f)(struct rcu_data *rdp))
2761 {
2762 	int cpu;
2763 	unsigned long flags;
2764 	struct rcu_node *rnp;
2765 
2766 	rcu_state.cbovld = rcu_state.cbovldnext;
2767 	rcu_state.cbovldnext = false;
2768 	rcu_for_each_leaf_node(rnp) {
2769 		unsigned long mask = 0;
2770 		unsigned long rsmask = 0;
2771 
2772 		cond_resched_tasks_rcu_qs();
2773 		raw_spin_lock_irqsave_rcu_node(rnp, flags);
2774 		rcu_state.cbovldnext |= !!rnp->cbovldmask;
2775 		if (rnp->qsmask == 0) {
2776 			if (rcu_preempt_blocked_readers_cgp(rnp)) {
2777 				/*
2778 				 * No point in scanning bits because they
2779 				 * are all zero.  But we might need to
2780 				 * priority-boost blocked readers.
2781 				 */
2782 				rcu_initiate_boost(rnp, flags);
2783 				/* rcu_initiate_boost() releases rnp->lock */
2784 				continue;
2785 			}
2786 			raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2787 			continue;
2788 		}
2789 		for_each_leaf_node_cpu_mask(rnp, cpu, rnp->qsmask) {
2790 			struct rcu_data *rdp;
2791 			int ret;
2792 
2793 			rdp = per_cpu_ptr(&rcu_data, cpu);
2794 			ret = f(rdp);
2795 			if (ret > 0) {
2796 				mask |= rdp->grpmask;
2797 				rcu_disable_urgency_upon_qs(rdp);
2798 			}
2799 			if (ret < 0)
2800 				rsmask |= rdp->grpmask;
2801 		}
2802 		if (mask != 0) {
2803 			/* Idle/offline CPUs, report (releases rnp->lock). */
2804 			rcu_report_qs_rnp(mask, rnp, rnp->gp_seq, flags);
2805 		} else {
2806 			/* Nothing to do here, so just drop the lock. */
2807 			raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2808 		}
2809 
2810 		for_each_leaf_node_cpu_mask(rnp, cpu, rsmask)
2811 			resched_cpu(cpu);
2812 	}
2813 }
2814 
2815 /*
2816  * Force quiescent states on reluctant CPUs, and also detect which
2817  * CPUs are in dyntick-idle mode.
2818  */
2819 void rcu_force_quiescent_state(void)
2820 {
2821 	unsigned long flags;
2822 	bool ret;
2823 	struct rcu_node *rnp;
2824 	struct rcu_node *rnp_old = NULL;
2825 
2826 	if (!rcu_gp_in_progress())
2827 		return;
2828 	/* Funnel through hierarchy to reduce memory contention. */
2829 	rnp = raw_cpu_read(rcu_data.mynode);
2830 	for (; rnp != NULL; rnp = rnp->parent) {
2831 		ret = (READ_ONCE(rcu_state.gp_flags) & RCU_GP_FLAG_FQS) ||
2832 		       !raw_spin_trylock(&rnp->fqslock);
2833 		if (rnp_old != NULL)
2834 			raw_spin_unlock(&rnp_old->fqslock);
2835 		if (ret)
2836 			return;
2837 		rnp_old = rnp;
2838 	}
2839 	/* rnp_old == rcu_get_root(), rnp == NULL. */
2840 
2841 	/* Reached the root of the rcu_node tree, acquire lock. */
2842 	raw_spin_lock_irqsave_rcu_node(rnp_old, flags);
2843 	raw_spin_unlock(&rnp_old->fqslock);
2844 	if (READ_ONCE(rcu_state.gp_flags) & RCU_GP_FLAG_FQS) {
2845 		raw_spin_unlock_irqrestore_rcu_node(rnp_old, flags);
2846 		return;  /* Someone beat us to it. */
2847 	}
2848 	WRITE_ONCE(rcu_state.gp_flags, rcu_state.gp_flags | RCU_GP_FLAG_FQS);
2849 	raw_spin_unlock_irqrestore_rcu_node(rnp_old, flags);
2850 	rcu_gp_kthread_wake();
2851 }
2852 EXPORT_SYMBOL_GPL(rcu_force_quiescent_state);
2853 
2854 // Workqueue handler for an RCU reader for kernels enforcing struct RCU
2855 // grace periods.
2856 static void strict_work_handler(struct work_struct *work)
2857 {
2858 	rcu_read_lock();
2859 	rcu_read_unlock();
2860 }
2861 
2862 /* Perform RCU core processing work for the current CPU.  */
2863 static __latent_entropy void rcu_core(void)
2864 {
2865 	struct rcu_data *rdp = raw_cpu_ptr(&rcu_data);
2866 	struct rcu_node *rnp = rdp->mynode;
2867 
2868 	if (cpu_is_offline(smp_processor_id()))
2869 		return;
2870 	trace_rcu_utilization(TPS("Start RCU core"));
2871 	WARN_ON_ONCE(!rdp->beenonline);
2872 
2873 	/* Report any deferred quiescent states if preemption enabled. */
2874 	if (IS_ENABLED(CONFIG_PREEMPT_COUNT) && (!(preempt_count() & PREEMPT_MASK))) {
2875 		rcu_preempt_deferred_qs(current);
2876 	} else if (rcu_preempt_need_deferred_qs(current)) {
2877 		guard(irqsave)();
2878 		set_need_resched_current();
2879 	}
2880 
2881 	/* Update RCU state based on any recent quiescent states. */
2882 	rcu_check_quiescent_state(rdp);
2883 
2884 	/* No grace period and unregistered callbacks? */
2885 	if (!rcu_gp_in_progress() &&
2886 	    rcu_segcblist_is_enabled(&rdp->cblist) && !rcu_rdp_is_offloaded(rdp)) {
2887 		guard(irqsave)();
2888 		if (!rcu_segcblist_restempty(&rdp->cblist, RCU_NEXT_READY_TAIL))
2889 			rcu_accelerate_cbs_unlocked(rnp, rdp);
2890 	}
2891 
2892 	rcu_check_gp_start_stall(rnp, rdp, rcu_jiffies_till_stall_check());
2893 
2894 	/* If there are callbacks ready, invoke them. */
2895 	if (!rcu_rdp_is_offloaded(rdp) && rcu_segcblist_ready_cbs(&rdp->cblist) &&
2896 	    likely(READ_ONCE(rcu_scheduler_fully_active))) {
2897 		rcu_do_batch(rdp);
2898 		/* Re-invoke RCU core processing if there are callbacks remaining. */
2899 		if (rcu_segcblist_ready_cbs(&rdp->cblist))
2900 			invoke_rcu_core();
2901 	}
2902 
2903 	/* Do any needed deferred wakeups of rcuo kthreads. */
2904 	do_nocb_deferred_wakeup(rdp);
2905 	trace_rcu_utilization(TPS("End RCU core"));
2906 
2907 	// If strict GPs, schedule an RCU reader in a clean environment.
2908 	if (IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD))
2909 		queue_work_on(rdp->cpu, rcu_gp_wq, &rdp->strict_work);
2910 }
2911 
2912 static void rcu_core_si(void)
2913 {
2914 	rcu_core();
2915 }
2916 
2917 static void rcu_wake_cond(struct task_struct *t, int status)
2918 {
2919 	/*
2920 	 * If the thread is yielding, only wake it when this
2921 	 * is invoked from idle
2922 	 */
2923 	if (t && (status != RCU_KTHREAD_YIELDING || is_idle_task(current)))
2924 		wake_up_process(t);
2925 }
2926 
2927 static void invoke_rcu_core_kthread(void)
2928 {
2929 	struct task_struct *t;
2930 	unsigned long flags;
2931 
2932 	local_irq_save(flags);
2933 	__this_cpu_write(rcu_data.rcu_cpu_has_work, 1);
2934 	t = __this_cpu_read(rcu_data.rcu_cpu_kthread_task);
2935 	if (t != NULL && t != current)
2936 		rcu_wake_cond(t, __this_cpu_read(rcu_data.rcu_cpu_kthread_status));
2937 	local_irq_restore(flags);
2938 }
2939 
2940 /*
2941  * Wake up this CPU's rcuc kthread to do RCU core processing.
2942  */
2943 static void invoke_rcu_core(void)
2944 {
2945 	if (!cpu_online(smp_processor_id()))
2946 		return;
2947 	if (use_softirq)
2948 		raise_softirq(RCU_SOFTIRQ);
2949 	else
2950 		invoke_rcu_core_kthread();
2951 }
2952 
2953 static void rcu_cpu_kthread_park(unsigned int cpu)
2954 {
2955 	per_cpu(rcu_data.rcu_cpu_kthread_status, cpu) = RCU_KTHREAD_OFFCPU;
2956 }
2957 
2958 static int rcu_cpu_kthread_should_run(unsigned int cpu)
2959 {
2960 	return __this_cpu_read(rcu_data.rcu_cpu_has_work);
2961 }
2962 
2963 /*
2964  * Per-CPU kernel thread that invokes RCU callbacks.  This replaces
2965  * the RCU softirq used in configurations of RCU that do not support RCU
2966  * priority boosting.
2967  */
2968 static void rcu_cpu_kthread(unsigned int cpu)
2969 {
2970 	unsigned int *statusp = this_cpu_ptr(&rcu_data.rcu_cpu_kthread_status);
2971 	char work, *workp = this_cpu_ptr(&rcu_data.rcu_cpu_has_work);
2972 	unsigned long *j = this_cpu_ptr(&rcu_data.rcuc_activity);
2973 	int spincnt;
2974 
2975 	trace_rcu_utilization(TPS("Start CPU kthread@rcu_run"));
2976 	for (spincnt = 0; spincnt < 10; spincnt++) {
2977 		WRITE_ONCE(*j, jiffies);
2978 		local_bh_disable();
2979 		*statusp = RCU_KTHREAD_RUNNING;
2980 		local_irq_disable();
2981 		work = *workp;
2982 		WRITE_ONCE(*workp, 0);
2983 		local_irq_enable();
2984 		if (work)
2985 			rcu_core();
2986 		local_bh_enable();
2987 		if (!READ_ONCE(*workp)) {
2988 			trace_rcu_utilization(TPS("End CPU kthread@rcu_wait"));
2989 			*statusp = RCU_KTHREAD_WAITING;
2990 			return;
2991 		}
2992 	}
2993 	*statusp = RCU_KTHREAD_YIELDING;
2994 	trace_rcu_utilization(TPS("Start CPU kthread@rcu_yield"));
2995 	schedule_timeout_idle(2);
2996 	trace_rcu_utilization(TPS("End CPU kthread@rcu_yield"));
2997 	*statusp = RCU_KTHREAD_WAITING;
2998 	WRITE_ONCE(*j, jiffies);
2999 }
3000 
3001 static struct smp_hotplug_thread rcu_cpu_thread_spec = {
3002 	.store			= &rcu_data.rcu_cpu_kthread_task,
3003 	.thread_should_run	= rcu_cpu_kthread_should_run,
3004 	.thread_fn		= rcu_cpu_kthread,
3005 	.thread_comm		= "rcuc/%u",
3006 	.setup			= rcu_cpu_kthread_setup,
3007 	.park			= rcu_cpu_kthread_park,
3008 };
3009 
3010 /*
3011  * Spawn per-CPU RCU core processing kthreads.
3012  */
3013 static int __init rcu_spawn_core_kthreads(void)
3014 {
3015 	int cpu;
3016 
3017 	for_each_possible_cpu(cpu)
3018 		per_cpu(rcu_data.rcu_cpu_has_work, cpu) = 0;
3019 	if (use_softirq)
3020 		return 0;
3021 	WARN_ONCE(smpboot_register_percpu_thread(&rcu_cpu_thread_spec),
3022 		  "%s: Could not start rcuc kthread, OOM is now expected behavior\n", __func__);
3023 	return 0;
3024 }
3025 
3026 static void rcutree_enqueue(struct rcu_data *rdp, struct rcu_head *head, rcu_callback_t func)
3027 {
3028 	rcu_segcblist_enqueue(&rdp->cblist, head);
3029 	trace_rcu_callback(rcu_state.name, head,
3030 			   rcu_segcblist_n_cbs(&rdp->cblist));
3031 	trace_rcu_segcb_stats(&rdp->cblist, TPS("SegCBQueued"));
3032 }
3033 
3034 /*
3035  * Handle any core-RCU processing required by a call_rcu() invocation.
3036  */
3037 static void call_rcu_core(struct rcu_data *rdp, struct rcu_head *head,
3038 			  rcu_callback_t func, unsigned long flags)
3039 {
3040 	rcutree_enqueue(rdp, head, func);
3041 	/*
3042 	 * If called from an extended quiescent state, invoke the RCU
3043 	 * core in order to force a re-evaluation of RCU's idleness.
3044 	 */
3045 	if (!rcu_is_watching())
3046 		invoke_rcu_core();
3047 
3048 	/* If interrupts were disabled or CPU offline, don't invoke RCU core. */
3049 	if (irqs_disabled_flags(flags) || cpu_is_offline(smp_processor_id()))
3050 		return;
3051 
3052 	/*
3053 	 * Force the grace period if too many callbacks or too long waiting.
3054 	 * Enforce hysteresis, and don't invoke rcu_force_quiescent_state()
3055 	 * if some other CPU has recently done so.  Also, don't bother
3056 	 * invoking rcu_force_quiescent_state() if the newly enqueued callback
3057 	 * is the only one waiting for a grace period to complete.
3058 	 */
3059 	if (unlikely(rcu_segcblist_n_cbs(&rdp->cblist) >
3060 		     rdp->qlen_last_fqs_check + qhimark)) {
3061 
3062 		/* Are we ignoring a completed grace period? */
3063 		note_gp_changes(rdp);
3064 
3065 		/* Start a new grace period if one not already started. */
3066 		if (!rcu_gp_in_progress()) {
3067 			rcu_accelerate_cbs_unlocked(rdp->mynode, rdp);
3068 		} else {
3069 			/* Give the grace period a kick. */
3070 			rdp->blimit = DEFAULT_MAX_RCU_BLIMIT;
3071 			if (READ_ONCE(rcu_state.n_force_qs) == rdp->n_force_qs_snap &&
3072 			    rcu_segcblist_first_pend_cb(&rdp->cblist) != head)
3073 				rcu_force_quiescent_state();
3074 			rdp->n_force_qs_snap = READ_ONCE(rcu_state.n_force_qs);
3075 			rdp->qlen_last_fqs_check = rcu_segcblist_n_cbs(&rdp->cblist);
3076 		}
3077 	}
3078 }
3079 
3080 /*
3081  * RCU callback function to leak a callback.
3082  */
3083 static void rcu_leak_callback(struct rcu_head *rhp)
3084 {
3085 }
3086 
3087 /*
3088  * Check and if necessary update the leaf rcu_node structure's
3089  * ->cbovldmask bit corresponding to the current CPU based on that CPU's
3090  * number of queued RCU callbacks.  The caller must hold the leaf rcu_node
3091  * structure's ->lock.
3092  */
3093 static void check_cb_ovld_locked(struct rcu_data *rdp, struct rcu_node *rnp)
3094 {
3095 	raw_lockdep_assert_held_rcu_node(rnp);
3096 	if (qovld_calc <= 0)
3097 		return; // Early boot and wildcard value set.
3098 	if (rcu_segcblist_n_cbs(&rdp->cblist) >= qovld_calc)
3099 		WRITE_ONCE(rnp->cbovldmask, rnp->cbovldmask | rdp->grpmask);
3100 	else
3101 		WRITE_ONCE(rnp->cbovldmask, rnp->cbovldmask & ~rdp->grpmask);
3102 }
3103 
3104 /*
3105  * Check and if necessary update the leaf rcu_node structure's
3106  * ->cbovldmask bit corresponding to the current CPU based on that CPU's
3107  * number of queued RCU callbacks.  No locks need be held, but the
3108  * caller must have disabled interrupts.
3109  *
3110  * Note that this function ignores the possibility that there are a lot
3111  * of callbacks all of which have already seen the end of their respective
3112  * grace periods.  This omission is due to the need for no-CBs CPUs to
3113  * be holding ->nocb_lock to do this check, which is too heavy for a
3114  * common-case operation.
3115  */
3116 static void check_cb_ovld(struct rcu_data *rdp)
3117 {
3118 	struct rcu_node *const rnp = rdp->mynode;
3119 
3120 	if (qovld_calc <= 0 ||
3121 	    ((rcu_segcblist_n_cbs(&rdp->cblist) >= qovld_calc) ==
3122 	     !!(READ_ONCE(rnp->cbovldmask) & rdp->grpmask)))
3123 		return; // Early boot wildcard value or already set correctly.
3124 	raw_spin_lock_rcu_node(rnp);
3125 	check_cb_ovld_locked(rdp, rnp);
3126 	raw_spin_unlock_rcu_node(rnp);
3127 }
3128 
3129 static void
3130 __call_rcu_common(struct rcu_head *head, rcu_callback_t func, bool lazy_in)
3131 {
3132 	static atomic_t doublefrees;
3133 	unsigned long flags;
3134 	bool lazy;
3135 	struct rcu_data *rdp;
3136 
3137 	/* Misaligned rcu_head! */
3138 	WARN_ON_ONCE((unsigned long)head & (sizeof(void *) - 1));
3139 
3140 	/* Avoid NULL dereference if callback is NULL. */
3141 	if (WARN_ON_ONCE(!func))
3142 		return;
3143 
3144 	if (debug_rcu_head_queue(head)) {
3145 		/*
3146 		 * Probable double call_rcu(), so leak the callback.
3147 		 * Use rcu:rcu_callback trace event to find the previous
3148 		 * time callback was passed to call_rcu().
3149 		 */
3150 		if (atomic_inc_return(&doublefrees) < 4) {
3151 			pr_err("%s(): Double-freed CB %p->%pS()!!!  ", __func__, head, head->func);
3152 			mem_dump_obj(head);
3153 		}
3154 		WRITE_ONCE(head->func, rcu_leak_callback);
3155 		return;
3156 	}
3157 	head->func = func;
3158 	head->next = NULL;
3159 	kasan_record_aux_stack(head);
3160 
3161 	local_irq_save(flags);
3162 	rdp = this_cpu_ptr(&rcu_data);
3163 	RCU_LOCKDEP_WARN(!rcu_rdp_cpu_online(rdp), "Callback enqueued on offline CPU!");
3164 
3165 	lazy = lazy_in && !rcu_async_should_hurry();
3166 
3167 	/* Add the callback to our list. */
3168 	if (unlikely(!rcu_segcblist_is_enabled(&rdp->cblist))) {
3169 		// This can trigger due to call_rcu() from offline CPU:
3170 		WARN_ON_ONCE(rcu_scheduler_active != RCU_SCHEDULER_INACTIVE);
3171 		WARN_ON_ONCE(!rcu_is_watching());
3172 		// Very early boot, before rcu_init().  Initialize if needed
3173 		// and then drop through to queue the callback.
3174 		if (rcu_segcblist_empty(&rdp->cblist))
3175 			rcu_segcblist_init(&rdp->cblist);
3176 	}
3177 
3178 	check_cb_ovld(rdp);
3179 
3180 	if (unlikely(rcu_rdp_is_offloaded(rdp)))
3181 		call_rcu_nocb(rdp, head, func, flags, lazy);
3182 	else
3183 		call_rcu_core(rdp, head, func, flags);
3184 	local_irq_restore(flags);
3185 }
3186 
3187 #ifdef CONFIG_RCU_LAZY
3188 static bool enable_rcu_lazy __read_mostly = !IS_ENABLED(CONFIG_RCU_LAZY_DEFAULT_OFF);
3189 module_param(enable_rcu_lazy, bool, 0444);
3190 
3191 /**
3192  * call_rcu_hurry() - Queue RCU callback for invocation after grace period, and
3193  * flush all lazy callbacks (including the new one) to the main ->cblist while
3194  * doing so.
3195  *
3196  * @head: structure to be used for queueing the RCU updates.
3197  * @func: actual callback function to be invoked after the grace period
3198  *
3199  * The callback function will be invoked some time after a full grace
3200  * period elapses, in other words after all pre-existing RCU read-side
3201  * critical sections have completed.
3202  *
3203  * Use this API instead of call_rcu() if you don't want the callback to be
3204  * delayed for very long periods of time, which can happen on systems without
3205  * memory pressure and on systems which are lightly loaded or mostly idle.
3206  * This function will cause callbacks to be invoked sooner than later at the
3207  * expense of extra power. Other than that, this function is identical to, and
3208  * reuses call_rcu()'s logic. Refer to call_rcu() for more details about memory
3209  * ordering and other functionality.
3210  */
3211 void call_rcu_hurry(struct rcu_head *head, rcu_callback_t func)
3212 {
3213 	__call_rcu_common(head, func, false);
3214 }
3215 EXPORT_SYMBOL_GPL(call_rcu_hurry);
3216 #else
3217 #define enable_rcu_lazy		false
3218 #endif
3219 
3220 /**
3221  * call_rcu() - Queue an RCU callback for invocation after a grace period.
3222  * By default the callbacks are 'lazy' and are kept hidden from the main
3223  * ->cblist to prevent starting of grace periods too soon.
3224  * If you desire grace periods to start very soon, use call_rcu_hurry().
3225  *
3226  * @head: structure to be used for queueing the RCU updates.
3227  * @func: actual callback function to be invoked after the grace period
3228  *
3229  * The callback function will be invoked some time after a full grace
3230  * period elapses, in other words after all pre-existing RCU read-side
3231  * critical sections have completed.  However, the callback function
3232  * might well execute concurrently with RCU read-side critical sections
3233  * that started after call_rcu() was invoked.
3234  *
3235  * It is perfectly legal to repost an RCU callback, potentially with
3236  * a different callback function, from within its callback function.
3237  * The specified function will be invoked after another full grace period
3238  * has elapsed.  This use case is similar in form to the common practice
3239  * of reposting a timer from within its own handler.
3240  *
3241  * RCU read-side critical sections are delimited by rcu_read_lock()
3242  * and rcu_read_unlock(), and may be nested.  In addition, but only in
3243  * v5.0 and later, regions of code across which interrupts, preemption,
3244  * or softirqs have been disabled also serve as RCU read-side critical
3245  * sections.  This includes hardware interrupt handlers, softirq handlers,
3246  * and NMI handlers.
3247  *
3248  * Note that all CPUs must agree that the grace period extended beyond
3249  * all pre-existing RCU read-side critical section.  On systems with more
3250  * than one CPU, this means that when "func()" is invoked, each CPU is
3251  * guaranteed to have executed a full memory barrier since the end of its
3252  * last RCU read-side critical section whose beginning preceded the call
3253  * to call_rcu().  It also means that each CPU executing an RCU read-side
3254  * critical section that continues beyond the start of "func()" must have
3255  * executed a memory barrier after the call_rcu() but before the beginning
3256  * of that RCU read-side critical section.  Note that these guarantees
3257  * include CPUs that are offline, idle, or executing in user mode, as
3258  * well as CPUs that are executing in the kernel.
3259  *
3260  * Furthermore, if CPU A invoked call_rcu() and CPU B invoked the
3261  * resulting RCU callback function "func()", then both CPU A and CPU B are
3262  * guaranteed to execute a full memory barrier during the time interval
3263  * between the call to call_rcu() and the invocation of "func()" -- even
3264  * if CPU A and CPU B are the same CPU (but again only if the system has
3265  * more than one CPU).
3266  *
3267  * Implementation of these memory-ordering guarantees is described here:
3268  * Documentation/RCU/Design/Memory-Ordering/Tree-RCU-Memory-Ordering.rst.
3269  *
3270  * Specific to call_rcu() (as opposed to the other call_rcu*() functions),
3271  * in kernels built with CONFIG_RCU_LAZY=y, call_rcu() might delay for many
3272  * seconds before starting the grace period needed by the corresponding
3273  * callback.  This delay can significantly improve energy-efficiency
3274  * on low-utilization battery-powered devices.  To avoid this delay,
3275  * in latency-sensitive kernel code, use call_rcu_hurry().
3276  */
3277 void call_rcu(struct rcu_head *head, rcu_callback_t func)
3278 {
3279 	__call_rcu_common(head, func, enable_rcu_lazy);
3280 }
3281 EXPORT_SYMBOL_GPL(call_rcu);
3282 
3283 /*
3284  * During early boot, any blocking grace-period wait automatically
3285  * implies a grace period.
3286  *
3287  * Later on, this could in theory be the case for kernels built with
3288  * CONFIG_SMP=y && CONFIG_PREEMPTION=y running on a single CPU, but this
3289  * is not a common case.  Furthermore, this optimization would cause
3290  * the rcu_gp_oldstate structure to expand by 50%, so this potential
3291  * grace-period optimization is ignored once the scheduler is running.
3292  */
3293 static int rcu_blocking_is_gp(void)
3294 {
3295 	if (rcu_scheduler_active != RCU_SCHEDULER_INACTIVE) {
3296 		might_sleep();
3297 		return false;
3298 	}
3299 	return true;
3300 }
3301 
3302 /*
3303  * Helper function for the synchronize_rcu() API.
3304  */
3305 static void synchronize_rcu_normal(void)
3306 {
3307 	struct rcu_synchronize rs;
3308 
3309 	init_rcu_head_on_stack(&rs.head);
3310 	trace_rcu_sr_normal(rcu_state.name, &rs.head, TPS("request"));
3311 
3312 	if (READ_ONCE(rcu_normal_wake_from_gp) < 1 ||
3313 			READ_ONCE(rcu_sr_normal_latched)) {
3314 		wait_rcu_gp(call_rcu_hurry);
3315 		goto trace_complete_out;
3316 	}
3317 
3318 	init_completion(&rs.completion);
3319 
3320 	/*
3321 	 * This code might be preempted, therefore take a GP
3322 	 * snapshot before adding a request.
3323 	 */
3324 	if (IS_ENABLED(CONFIG_PROVE_RCU))
3325 		get_state_synchronize_rcu_full(&rs.oldstate);
3326 
3327 	rcu_sr_normal_add_req(&rs);
3328 
3329 	/* Kick a GP and start waiting. */
3330 	(void) start_poll_synchronize_rcu();
3331 
3332 	/* Now we can wait. */
3333 	wait_for_completion(&rs.completion);
3334 
3335 trace_complete_out:
3336 	trace_rcu_sr_normal(rcu_state.name, &rs.head, TPS("complete"));
3337 	destroy_rcu_head_on_stack(&rs.head);
3338 }
3339 
3340 /**
3341  * synchronize_rcu - wait until a grace period has elapsed.
3342  *
3343  * Control will return to the caller some time after a full grace
3344  * period has elapsed, in other words after all currently executing RCU
3345  * read-side critical sections have completed.  Note, however, that
3346  * upon return from synchronize_rcu(), the caller might well be executing
3347  * concurrently with new RCU read-side critical sections that began while
3348  * synchronize_rcu() was waiting.
3349  *
3350  * RCU read-side critical sections are delimited by rcu_read_lock()
3351  * and rcu_read_unlock(), and may be nested.  In addition, but only in
3352  * v5.0 and later, regions of code across which interrupts, preemption,
3353  * or softirqs have been disabled also serve as RCU read-side critical
3354  * sections.  This includes hardware interrupt handlers, softirq handlers,
3355  * and NMI handlers.
3356  *
3357  * Note that this guarantee implies further memory-ordering guarantees.
3358  * On systems with more than one CPU, when synchronize_rcu() returns,
3359  * each CPU is guaranteed to have executed a full memory barrier since
3360  * the end of its last RCU read-side critical section whose beginning
3361  * preceded the call to synchronize_rcu().  In addition, each CPU having
3362  * an RCU read-side critical section that extends beyond the return from
3363  * synchronize_rcu() is guaranteed to have executed a full memory barrier
3364  * after the beginning of synchronize_rcu() and before the beginning of
3365  * that RCU read-side critical section.  Note that these guarantees include
3366  * CPUs that are offline, idle, or executing in user mode, as well as CPUs
3367  * that are executing in the kernel.
3368  *
3369  * Furthermore, if CPU A invoked synchronize_rcu(), which returned
3370  * to its caller on CPU B, then both CPU A and CPU B are guaranteed
3371  * to have executed a full memory barrier during the execution of
3372  * synchronize_rcu() -- even if CPU A and CPU B are the same CPU (but
3373  * again only if the system has more than one CPU).
3374  *
3375  * Implementation of these memory-ordering guarantees is described here:
3376  * Documentation/RCU/Design/Memory-Ordering/Tree-RCU-Memory-Ordering.rst.
3377  */
3378 void synchronize_rcu(void)
3379 {
3380 	unsigned long flags;
3381 	struct rcu_node *rnp;
3382 
3383 	RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map) ||
3384 			 lock_is_held(&rcu_lock_map) ||
3385 			 lock_is_held(&rcu_sched_lock_map),
3386 			 "Illegal synchronize_rcu() in RCU read-side critical section");
3387 	if (!rcu_blocking_is_gp()) {
3388 		if (rcu_gp_is_expedited())
3389 			synchronize_rcu_expedited();
3390 		else
3391 			synchronize_rcu_normal();
3392 		return;
3393 	}
3394 
3395 	// Context allows vacuous grace periods.
3396 	// Note well that this code runs with !PREEMPT && !SMP.
3397 	// In addition, all code that advances grace periods runs at
3398 	// process level.  Therefore, this normal GP overlaps with other
3399 	// normal GPs only by being fully nested within them, which allows
3400 	// reuse of ->gp_seq_polled_snap.
3401 	rcu_poll_gp_seq_start_unlocked(&rcu_state.gp_seq_polled_snap);
3402 	rcu_poll_gp_seq_end_unlocked(&rcu_state.gp_seq_polled_snap);
3403 
3404 	// Update the normal grace-period counters to record
3405 	// this grace period, but only those used by the boot CPU.
3406 	// The rcu_scheduler_starting() will take care of the rest of
3407 	// these counters.
3408 	local_irq_save(flags);
3409 	WARN_ON_ONCE(num_online_cpus() > 1);
3410 	rcu_state.gp_seq += (1 << RCU_SEQ_CTR_SHIFT);
3411 	for (rnp = this_cpu_ptr(&rcu_data)->mynode; rnp; rnp = rnp->parent)
3412 		rnp->gp_seq_needed = rnp->gp_seq = rcu_state.gp_seq;
3413 	local_irq_restore(flags);
3414 }
3415 EXPORT_SYMBOL_GPL(synchronize_rcu);
3416 
3417 /**
3418  * get_completed_synchronize_rcu_full - Return a full pre-completed polled state cookie
3419  * @rgosp: Place to put state cookie
3420  *
3421  * Stores into @rgosp a value that will always be treated by functions
3422  * like poll_state_synchronize_rcu_full() as a cookie whose grace period
3423  * has already completed.
3424  */
3425 void get_completed_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp)
3426 {
3427 	rgosp->rgos_norm = RCU_GET_STATE_COMPLETED;
3428 	rgosp->rgos_exp = RCU_GET_STATE_COMPLETED;
3429 }
3430 EXPORT_SYMBOL_GPL(get_completed_synchronize_rcu_full);
3431 
3432 /**
3433  * get_state_synchronize_rcu - Snapshot current RCU state
3434  *
3435  * Returns a cookie that is used by a later call to cond_synchronize_rcu()
3436  * or poll_state_synchronize_rcu() to determine whether or not a full
3437  * grace period has elapsed in the meantime.
3438  */
3439 unsigned long get_state_synchronize_rcu(void)
3440 {
3441 	/*
3442 	 * Any prior manipulation of RCU-protected data must happen
3443 	 * before the load from ->gp_seq.
3444 	 */
3445 	smp_mb();  /* ^^^ */
3446 	return rcu_seq_snap(&rcu_state.gp_seq_polled);
3447 }
3448 EXPORT_SYMBOL_GPL(get_state_synchronize_rcu);
3449 
3450 /**
3451  * get_state_synchronize_rcu_full - Snapshot RCU state, both normal and expedited
3452  * @rgosp: location to place combined normal/expedited grace-period state
3453  *
3454  * Places the normal and expedited grace-period states in @rgosp.  This
3455  * state value can be passed to a later call to cond_synchronize_rcu_full()
3456  * or poll_state_synchronize_rcu_full() to determine whether or not a
3457  * grace period (whether normal or expedited) has elapsed in the meantime.
3458  * The rcu_gp_oldstate structure takes up twice the memory of an unsigned
3459  * long, but is guaranteed to see all grace periods.  In contrast, the
3460  * combined state occupies less memory, but can sometimes fail to take
3461  * grace periods into account.
3462  *
3463  * This does not guarantee that the needed grace period will actually
3464  * start.
3465  */
3466 void get_state_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp)
3467 {
3468 	/*
3469 	 * Any prior manipulation of RCU-protected data must happen
3470 	 * before the loads from ->gp_seq and ->expedited_sequence.
3471 	 */
3472 	smp_mb();  /* ^^^ */
3473 
3474 	// Yes, rcu_state.gp_seq, not rnp_root->gp_seq, the latter's use
3475 	// in poll_state_synchronize_rcu_full() notwithstanding.  Use of
3476 	// the latter here would result in too-short grace periods due to
3477 	// interactions with newly onlined CPUs.
3478 	rgosp->rgos_norm = rcu_seq_snap(&rcu_state.gp_seq);
3479 	rgosp->rgos_exp = rcu_seq_snap(&rcu_state.expedited_sequence);
3480 }
3481 EXPORT_SYMBOL_GPL(get_state_synchronize_rcu_full);
3482 
3483 /*
3484  * Helper function for start_poll_synchronize_rcu() and
3485  * start_poll_synchronize_rcu_full().
3486  */
3487 static void start_poll_synchronize_rcu_common(void)
3488 {
3489 	unsigned long flags;
3490 	bool needwake;
3491 	struct rcu_data *rdp;
3492 	struct rcu_node *rnp;
3493 
3494 	local_irq_save(flags);
3495 	rdp = this_cpu_ptr(&rcu_data);
3496 	rnp = rdp->mynode;
3497 	raw_spin_lock_rcu_node(rnp); // irqs already disabled.
3498 	// Note it is possible for a grace period to have elapsed between
3499 	// the above call to get_state_synchronize_rcu() and the below call
3500 	// to rcu_seq_snap.  This is OK, the worst that happens is that we
3501 	// get a grace period that no one needed.  These accesses are ordered
3502 	// by smp_mb(), and we are accessing them in the opposite order
3503 	// from which they are updated at grace-period start, as required.
3504 	needwake = rcu_start_this_gp(rnp, rdp, rcu_seq_snap(&rcu_state.gp_seq));
3505 	raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
3506 	if (needwake)
3507 		rcu_gp_kthread_wake();
3508 }
3509 
3510 /**
3511  * start_poll_synchronize_rcu - Snapshot and start RCU grace period
3512  *
3513  * Returns a cookie that is used by a later call to cond_synchronize_rcu()
3514  * or poll_state_synchronize_rcu() to determine whether or not a full
3515  * grace period has elapsed in the meantime.  If the needed grace period
3516  * is not already slated to start, notifies RCU core of the need for that
3517  * grace period.
3518  */
3519 unsigned long start_poll_synchronize_rcu(void)
3520 {
3521 	unsigned long gp_seq = get_state_synchronize_rcu();
3522 
3523 	start_poll_synchronize_rcu_common();
3524 	return gp_seq;
3525 }
3526 EXPORT_SYMBOL_GPL(start_poll_synchronize_rcu);
3527 
3528 /**
3529  * start_poll_synchronize_rcu_full - Take a full snapshot and start RCU grace period
3530  * @rgosp: value from get_state_synchronize_rcu_full() or start_poll_synchronize_rcu_full()
3531  *
3532  * Places the normal and expedited grace-period states in *@rgos.  This
3533  * state value can be passed to a later call to cond_synchronize_rcu_full()
3534  * or poll_state_synchronize_rcu_full() to determine whether or not a
3535  * grace period (whether normal or expedited) has elapsed in the meantime.
3536  * If the needed grace period is not already slated to start, notifies
3537  * RCU core of the need for that grace period.
3538  */
3539 void start_poll_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp)
3540 {
3541 	get_state_synchronize_rcu_full(rgosp);
3542 
3543 	start_poll_synchronize_rcu_common();
3544 }
3545 EXPORT_SYMBOL_GPL(start_poll_synchronize_rcu_full);
3546 
3547 /**
3548  * poll_state_synchronize_rcu - Has the specified RCU grace period completed?
3549  * @oldstate: value from get_state_synchronize_rcu() or start_poll_synchronize_rcu()
3550  *
3551  * If a full RCU grace period has elapsed since the earlier call from
3552  * which @oldstate was obtained, return @true, otherwise return @false.
3553  * If @false is returned, it is the caller's responsibility to invoke this
3554  * function later on until it does return @true.  Alternatively, the caller
3555  * can explicitly wait for a grace period, for example, by passing @oldstate
3556  * to either cond_synchronize_rcu() or cond_synchronize_rcu_expedited()
3557  * on the one hand or by directly invoking either synchronize_rcu() or
3558  * synchronize_rcu_expedited() on the other.
3559  *
3560  * Yes, this function does not take counter wrap into account.
3561  * But counter wrap is harmless.  If the counter wraps, we have waited for
3562  * more than a billion grace periods (and way more on a 64-bit system!).
3563  * Those needing to keep old state values for very long time periods
3564  * (many hours even on 32-bit systems) should check them occasionally and
3565  * either refresh them or set a flag indicating that the grace period has
3566  * completed.  Alternatively, they can use get_completed_synchronize_rcu()
3567  * to get a guaranteed-completed grace-period state.
3568  *
3569  * In addition, because oldstate compresses the grace-period state for
3570  * both normal and expedited grace periods into a single unsigned long,
3571  * it can miss a grace period when synchronize_rcu() runs concurrently
3572  * with synchronize_rcu_expedited().  If this is unacceptable, please
3573  * instead use the _full() variant of these polling APIs.
3574  *
3575  * This function provides the same memory-ordering guarantees that
3576  * would be provided by a synchronize_rcu() that was invoked at the call
3577  * to the function that provided @oldstate, and that returned at the end
3578  * of this function.
3579  */
3580 bool poll_state_synchronize_rcu(unsigned long oldstate)
3581 {
3582 	if (oldstate == RCU_GET_STATE_COMPLETED ||
3583 	    rcu_seq_done_exact(&rcu_state.gp_seq_polled, oldstate)) {
3584 		smp_mb(); /* Ensure GP ends before subsequent accesses. */
3585 		return true;
3586 	}
3587 	return false;
3588 }
3589 EXPORT_SYMBOL_GPL(poll_state_synchronize_rcu);
3590 
3591 /**
3592  * poll_state_synchronize_rcu_full - Has the specified RCU grace period completed?
3593  * @rgosp: value from get_state_synchronize_rcu_full() or start_poll_synchronize_rcu_full()
3594  *
3595  * If a full RCU grace period has elapsed since the earlier call from
3596  * which *rgosp was obtained, return @true, otherwise return @false.
3597  * If @false is returned, it is the caller's responsibility to invoke this
3598  * function later on until it does return @true.  Alternatively, the caller
3599  * can explicitly wait for a grace period, for example, by passing @rgosp
3600  * to cond_synchronize_rcu() or by directly invoking synchronize_rcu().
3601  *
3602  * Yes, this function does not take counter wrap into account.
3603  * But counter wrap is harmless.  If the counter wraps, we have waited
3604  * for more than a billion grace periods (and way more on a 64-bit
3605  * system!).  Those needing to keep rcu_gp_oldstate values for very
3606  * long time periods (many hours even on 32-bit systems) should check
3607  * them occasionally and either refresh them or set a flag indicating
3608  * that the grace period has completed.  Alternatively, they can use
3609  * get_completed_synchronize_rcu_full() to get a guaranteed-completed
3610  * grace-period state.
3611  *
3612  * This function provides the same memory-ordering guarantees that would
3613  * be provided by a synchronize_rcu() that was invoked at the call to
3614  * the function that provided @rgosp, and that returned at the end of this
3615  * function.  And this guarantee requires that the root rcu_node structure's
3616  * ->gp_seq field be checked instead of that of the rcu_state structure.
3617  * The problem is that the just-ending grace-period's callbacks can be
3618  * invoked between the time that the root rcu_node structure's ->gp_seq
3619  * field is updated and the time that the rcu_state structure's ->gp_seq
3620  * field is updated.  Therefore, if a single synchronize_rcu() is to
3621  * cause a subsequent poll_state_synchronize_rcu_full() to return @true,
3622  * then the root rcu_node structure is the one that needs to be polled.
3623  */
3624 bool poll_state_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp)
3625 {
3626 	struct rcu_node *rnp = rcu_get_root();
3627 
3628 	smp_mb(); // Order against root rcu_node structure grace-period cleanup.
3629 	if (rgosp->rgos_norm == RCU_GET_STATE_COMPLETED ||
3630 	    rcu_seq_done_exact(&rnp->gp_seq, rgosp->rgos_norm) ||
3631 	    rgosp->rgos_exp == RCU_GET_STATE_COMPLETED ||
3632 	    rcu_seq_done_exact(&rcu_state.expedited_sequence, rgosp->rgos_exp)) {
3633 		smp_mb(); /* Ensure GP ends before subsequent accesses. */
3634 		return true;
3635 	}
3636 	return false;
3637 }
3638 EXPORT_SYMBOL_GPL(poll_state_synchronize_rcu_full);
3639 
3640 /**
3641  * cond_synchronize_rcu - Conditionally wait for an RCU grace period
3642  * @oldstate: value from get_state_synchronize_rcu(), start_poll_synchronize_rcu(), or start_poll_synchronize_rcu_expedited()
3643  *
3644  * If a full RCU grace period has elapsed since the earlier call to
3645  * get_state_synchronize_rcu() or start_poll_synchronize_rcu(), just return.
3646  * Otherwise, invoke synchronize_rcu() to wait for a full grace period.
3647  *
3648  * Yes, this function does not take counter wrap into account.
3649  * But counter wrap is harmless.  If the counter wraps, we have waited for
3650  * more than 2 billion grace periods (and way more on a 64-bit system!),
3651  * so waiting for a couple of additional grace periods should be just fine.
3652  *
3653  * This function provides the same memory-ordering guarantees that
3654  * would be provided by a synchronize_rcu() that was invoked at the call
3655  * to the function that provided @oldstate and that returned at the end
3656  * of this function.
3657  */
3658 void cond_synchronize_rcu(unsigned long oldstate)
3659 {
3660 	if (!poll_state_synchronize_rcu(oldstate))
3661 		synchronize_rcu();
3662 }
3663 EXPORT_SYMBOL_GPL(cond_synchronize_rcu);
3664 
3665 /**
3666  * cond_synchronize_rcu_full - Conditionally wait for an RCU grace period
3667  * @rgosp: value from get_state_synchronize_rcu_full(), start_poll_synchronize_rcu_full(), or start_poll_synchronize_rcu_expedited_full()
3668  *
3669  * If a full RCU grace period has elapsed since the call to
3670  * get_state_synchronize_rcu_full(), start_poll_synchronize_rcu_full(),
3671  * or start_poll_synchronize_rcu_expedited_full() from which @rgosp was
3672  * obtained, just return.  Otherwise, invoke synchronize_rcu() to wait
3673  * for a full grace period.
3674  *
3675  * Yes, this function does not take counter wrap into account.
3676  * But counter wrap is harmless.  If the counter wraps, we have waited for
3677  * more than 2 billion grace periods (and way more on a 64-bit system!),
3678  * so waiting for a couple of additional grace periods should be just fine.
3679  *
3680  * This function provides the same memory-ordering guarantees that
3681  * would be provided by a synchronize_rcu() that was invoked at the call
3682  * to the function that provided @rgosp and that returned at the end of
3683  * this function.
3684  */
3685 void cond_synchronize_rcu_full(struct rcu_gp_oldstate *rgosp)
3686 {
3687 	if (!poll_state_synchronize_rcu_full(rgosp))
3688 		synchronize_rcu();
3689 }
3690 EXPORT_SYMBOL_GPL(cond_synchronize_rcu_full);
3691 
3692 /*
3693  * Check to see if there is any immediate RCU-related work to be done by
3694  * the current CPU, returning 1 if so and zero otherwise.  The checks are
3695  * in order of increasing expense: checks that can be carried out against
3696  * CPU-local state are performed first.  However, we must check for CPU
3697  * stalls first, else we might not get a chance.
3698  */
3699 static int rcu_pending(int user)
3700 {
3701 	bool gp_in_progress;
3702 	struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
3703 	struct rcu_node *rnp = rdp->mynode;
3704 
3705 	lockdep_assert_irqs_disabled();
3706 
3707 	/* Check for CPU stalls, if enabled. */
3708 	check_cpu_stall(rdp);
3709 
3710 	/* Does this CPU need a deferred NOCB wakeup? */
3711 	if (rcu_nocb_need_deferred_wakeup(rdp, RCU_NOCB_WAKE))
3712 		return 1;
3713 
3714 	/* Is this a nohz_full CPU in userspace or idle?  (Ignore RCU if so.) */
3715 	gp_in_progress = rcu_gp_in_progress();
3716 	if ((user || rcu_is_cpu_rrupt_from_idle() ||
3717 	     (gp_in_progress &&
3718 	      time_before(jiffies, READ_ONCE(rcu_state.gp_start) +
3719 			  nohz_full_patience_delay_jiffies))) &&
3720 	    rcu_nohz_full_cpu())
3721 		return 0;
3722 
3723 	/* Is the RCU core waiting for a quiescent state from this CPU? */
3724 	if (rdp->core_needs_qs && !rdp->cpu_no_qs.b.norm && gp_in_progress)
3725 		return 1;
3726 
3727 	/* Does this CPU have callbacks ready to invoke? */
3728 	if (!rcu_rdp_is_offloaded(rdp) &&
3729 	    rcu_segcblist_ready_cbs(&rdp->cblist))
3730 		return 1;
3731 
3732 	/* Has RCU gone idle with this CPU needing another grace period? */
3733 	if (!gp_in_progress && rcu_segcblist_is_enabled(&rdp->cblist) &&
3734 	    !rcu_rdp_is_offloaded(rdp) &&
3735 	    !rcu_segcblist_restempty(&rdp->cblist, RCU_NEXT_READY_TAIL))
3736 		return 1;
3737 
3738 	/* Have RCU grace period completed or started?  */
3739 	if (rcu_seq_current(&rnp->gp_seq) != rdp->gp_seq ||
3740 	    unlikely(READ_ONCE(rdp->gpwrap))) /* outside lock */
3741 		return 1;
3742 
3743 	/* nothing to do */
3744 	return 0;
3745 }
3746 
3747 /*
3748  * Helper function for rcu_barrier() tracing.  If tracing is disabled,
3749  * the compiler is expected to optimize this away.
3750  */
3751 static void rcu_barrier_trace(const char *s, int cpu, unsigned long done)
3752 {
3753 	trace_rcu_barrier(rcu_state.name, s, cpu,
3754 			  atomic_read(&rcu_state.barrier_cpu_count), done);
3755 }
3756 
3757 /*
3758  * RCU callback function for rcu_barrier().  If we are last, wake
3759  * up the task executing rcu_barrier().
3760  *
3761  * Note that the value of rcu_state.barrier_sequence must be captured
3762  * before the atomic_dec_and_test().  Otherwise, if this CPU is not last,
3763  * other CPUs might count the value down to zero before this CPU gets
3764  * around to invoking rcu_barrier_trace(), which might result in bogus
3765  * data from the next instance of rcu_barrier().
3766  */
3767 static void rcu_barrier_callback(struct rcu_head *rhp)
3768 {
3769 	unsigned long __maybe_unused s = rcu_state.barrier_sequence;
3770 
3771 	rhp->next = rhp; // Mark the callback as having been invoked.
3772 	if (atomic_dec_and_test(&rcu_state.barrier_cpu_count)) {
3773 		rcu_barrier_trace(TPS("LastCB"), -1, s);
3774 		complete(&rcu_state.barrier_completion);
3775 	} else {
3776 		rcu_barrier_trace(TPS("CB"), -1, s);
3777 	}
3778 }
3779 
3780 /*
3781  * If needed, entrain an rcu_barrier() callback on rdp->cblist.
3782  */
3783 static void rcu_barrier_entrain(struct rcu_data *rdp)
3784 {
3785 	unsigned long gseq = READ_ONCE(rcu_state.barrier_sequence);
3786 	unsigned long lseq = READ_ONCE(rdp->barrier_seq_snap);
3787 	bool wake_nocb = false;
3788 	bool was_alldone = false;
3789 
3790 	lockdep_assert_held(&rcu_state.barrier_lock);
3791 	if (rcu_seq_state(lseq) || !rcu_seq_state(gseq) || rcu_seq_ctr(lseq) != rcu_seq_ctr(gseq))
3792 		return;
3793 	rcu_barrier_trace(TPS("IRQ"), -1, rcu_state.barrier_sequence);
3794 	rdp->barrier_head.func = rcu_barrier_callback;
3795 	debug_rcu_head_queue(&rdp->barrier_head);
3796 	rcu_nocb_lock(rdp);
3797 	/*
3798 	 * Flush bypass and wakeup rcuog if we add callbacks to an empty regular
3799 	 * queue. This way we don't wait for bypass timer that can reach seconds
3800 	 * if it's fully lazy.
3801 	 */
3802 	was_alldone = rcu_rdp_is_offloaded(rdp) && !rcu_segcblist_pend_cbs(&rdp->cblist);
3803 	WARN_ON_ONCE(!rcu_nocb_flush_bypass(rdp, NULL, jiffies, false));
3804 	wake_nocb = was_alldone && rcu_segcblist_pend_cbs(&rdp->cblist);
3805 	if (rcu_segcblist_entrain(&rdp->cblist, &rdp->barrier_head)) {
3806 		atomic_inc(&rcu_state.barrier_cpu_count);
3807 	} else {
3808 		debug_rcu_head_unqueue(&rdp->barrier_head);
3809 		rcu_barrier_trace(TPS("IRQNQ"), -1, rcu_state.barrier_sequence);
3810 	}
3811 	rcu_nocb_unlock(rdp);
3812 	if (wake_nocb)
3813 		wake_nocb_gp(rdp);
3814 	smp_store_release(&rdp->barrier_seq_snap, gseq);
3815 }
3816 
3817 /*
3818  * Called with preemption disabled, and from cross-cpu IRQ context.
3819  */
3820 static void rcu_barrier_handler(void *cpu_in)
3821 {
3822 	uintptr_t cpu = (uintptr_t)cpu_in;
3823 	struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
3824 
3825 	lockdep_assert_irqs_disabled();
3826 	WARN_ON_ONCE(cpu != rdp->cpu);
3827 	WARN_ON_ONCE(cpu != smp_processor_id());
3828 	raw_spin_lock(&rcu_state.barrier_lock);
3829 	rcu_barrier_entrain(rdp);
3830 	raw_spin_unlock(&rcu_state.barrier_lock);
3831 }
3832 
3833 /**
3834  * rcu_barrier - Wait until all in-flight call_rcu() callbacks complete.
3835  *
3836  * Note that this primitive does not necessarily wait for an RCU grace period
3837  * to complete.  For example, if there are no RCU callbacks queued anywhere
3838  * in the system, then rcu_barrier() is within its rights to return
3839  * immediately, without waiting for anything, much less an RCU grace period.
3840  * In fact, rcu_barrier() will normally not result in any RCU grace periods
3841  * beyond those that were already destined to be executed.
3842  *
3843  * In kernels built with CONFIG_RCU_LAZY=y, this function also hurries all
3844  * pending lazy RCU callbacks.
3845  */
3846 void rcu_barrier(void)
3847 {
3848 	uintptr_t cpu;
3849 	unsigned long flags;
3850 	unsigned long gseq;
3851 	struct rcu_data *rdp;
3852 	unsigned long s = rcu_seq_snap(&rcu_state.barrier_sequence);
3853 
3854 	rcu_barrier_trace(TPS("Begin"), -1, s);
3855 
3856 	/* Take mutex to serialize concurrent rcu_barrier() requests. */
3857 	mutex_lock(&rcu_state.barrier_mutex);
3858 
3859 	/* Did someone else do our work for us? */
3860 	if (rcu_seq_done(&rcu_state.barrier_sequence, s)) {
3861 		rcu_barrier_trace(TPS("EarlyExit"), -1, rcu_state.barrier_sequence);
3862 		smp_mb(); /* caller's subsequent code after above check. */
3863 		mutex_unlock(&rcu_state.barrier_mutex);
3864 		return;
3865 	}
3866 
3867 	/* Mark the start of the barrier operation. */
3868 	raw_spin_lock_irqsave(&rcu_state.barrier_lock, flags);
3869 	rcu_seq_start(&rcu_state.barrier_sequence);
3870 	gseq = rcu_state.barrier_sequence;
3871 	rcu_barrier_trace(TPS("Inc1"), -1, rcu_state.barrier_sequence);
3872 
3873 	/*
3874 	 * Initialize the count to two rather than to zero in order
3875 	 * to avoid a too-soon return to zero in case of an immediate
3876 	 * invocation of the just-enqueued callback (or preemption of
3877 	 * this task).  Exclude CPU-hotplug operations to ensure that no
3878 	 * offline non-offloaded CPU has callbacks queued.
3879 	 */
3880 	init_completion(&rcu_state.barrier_completion);
3881 	atomic_set(&rcu_state.barrier_cpu_count, 2);
3882 	raw_spin_unlock_irqrestore(&rcu_state.barrier_lock, flags);
3883 
3884 	/*
3885 	 * Force each CPU with callbacks to register a new callback.
3886 	 * When that callback is invoked, we will know that all of the
3887 	 * corresponding CPU's preceding callbacks have been invoked.
3888 	 */
3889 	for_each_possible_cpu(cpu) {
3890 		rdp = per_cpu_ptr(&rcu_data, cpu);
3891 retry:
3892 		if (smp_load_acquire(&rdp->barrier_seq_snap) == gseq)
3893 			continue;
3894 		raw_spin_lock_irqsave(&rcu_state.barrier_lock, flags);
3895 		if (!rcu_segcblist_n_cbs(&rdp->cblist)) {
3896 			WRITE_ONCE(rdp->barrier_seq_snap, gseq);
3897 			raw_spin_unlock_irqrestore(&rcu_state.barrier_lock, flags);
3898 			rcu_barrier_trace(TPS("NQ"), cpu, rcu_state.barrier_sequence);
3899 			continue;
3900 		}
3901 		if (!rcu_rdp_cpu_online(rdp)) {
3902 			rcu_barrier_entrain(rdp);
3903 			WARN_ON_ONCE(READ_ONCE(rdp->barrier_seq_snap) != gseq);
3904 			raw_spin_unlock_irqrestore(&rcu_state.barrier_lock, flags);
3905 			rcu_barrier_trace(TPS("OfflineNoCBQ"), cpu, rcu_state.barrier_sequence);
3906 			continue;
3907 		}
3908 		raw_spin_unlock_irqrestore(&rcu_state.barrier_lock, flags);
3909 		if (smp_call_function_single(cpu, rcu_barrier_handler, (void *)cpu, 1)) {
3910 			schedule_timeout_uninterruptible(1);
3911 			goto retry;
3912 		}
3913 		WARN_ON_ONCE(READ_ONCE(rdp->barrier_seq_snap) != gseq);
3914 		rcu_barrier_trace(TPS("OnlineQ"), cpu, rcu_state.barrier_sequence);
3915 	}
3916 
3917 	/*
3918 	 * Now that we have an rcu_barrier_callback() callback on each
3919 	 * CPU, and thus each counted, remove the initial count.
3920 	 */
3921 	if (atomic_sub_and_test(2, &rcu_state.barrier_cpu_count))
3922 		complete(&rcu_state.barrier_completion);
3923 
3924 	/* Wait for all rcu_barrier_callback() callbacks to be invoked. */
3925 	wait_for_completion(&rcu_state.barrier_completion);
3926 
3927 	/* Mark the end of the barrier operation. */
3928 	rcu_barrier_trace(TPS("Inc2"), -1, rcu_state.barrier_sequence);
3929 	rcu_seq_end(&rcu_state.barrier_sequence);
3930 	gseq = rcu_state.barrier_sequence;
3931 	for_each_possible_cpu(cpu) {
3932 		rdp = per_cpu_ptr(&rcu_data, cpu);
3933 
3934 		WRITE_ONCE(rdp->barrier_seq_snap, gseq);
3935 	}
3936 
3937 	/* Other rcu_barrier() invocations can now safely proceed. */
3938 	mutex_unlock(&rcu_state.barrier_mutex);
3939 }
3940 EXPORT_SYMBOL_GPL(rcu_barrier);
3941 
3942 static unsigned long rcu_barrier_last_throttle;
3943 
3944 /**
3945  * rcu_barrier_throttled - Do rcu_barrier(), but limit to one per second
3946  *
3947  * This can be thought of as guard rails around rcu_barrier() that
3948  * permits unrestricted userspace use, at least assuming the hardware's
3949  * try_cmpxchg() is robust.  There will be at most one call per second to
3950  * rcu_barrier() system-wide from use of this function, which means that
3951  * callers might needlessly wait a second or three.
3952  *
3953  * This is intended for use by test suites to avoid OOM by flushing RCU
3954  * callbacks from the previous test before starting the next.  See the
3955  * rcutree.do_rcu_barrier module parameter for more information.
3956  *
3957  * Why not simply make rcu_barrier() more scalable?  That might be
3958  * the eventual endpoint, but let's keep it simple for the time being.
3959  * Note that the module parameter infrastructure serializes calls to a
3960  * given .set() function, but should concurrent .set() invocation ever be
3961  * possible, we are ready!
3962  */
3963 static void rcu_barrier_throttled(void)
3964 {
3965 	unsigned long j = jiffies;
3966 	unsigned long old = READ_ONCE(rcu_barrier_last_throttle);
3967 	unsigned long s = rcu_seq_snap(&rcu_state.barrier_sequence);
3968 
3969 	while (time_in_range(j, old, old + HZ / 16) ||
3970 	       !try_cmpxchg(&rcu_barrier_last_throttle, &old, j)) {
3971 		schedule_timeout_idle(HZ / 16);
3972 		if (rcu_seq_done(&rcu_state.barrier_sequence, s)) {
3973 			smp_mb(); /* caller's subsequent code after above check. */
3974 			return;
3975 		}
3976 		j = jiffies;
3977 		old = READ_ONCE(rcu_barrier_last_throttle);
3978 	}
3979 	rcu_barrier();
3980 }
3981 
3982 /*
3983  * Invoke rcu_barrier_throttled() when a rcutree.do_rcu_barrier
3984  * request arrives.  We insist on a true value to allow for possible
3985  * future expansion.
3986  */
3987 static int param_set_do_rcu_barrier(const char *val, const struct kernel_param *kp)
3988 {
3989 	bool b;
3990 	int ret;
3991 
3992 	if (rcu_scheduler_active != RCU_SCHEDULER_RUNNING)
3993 		return -EAGAIN;
3994 	ret = kstrtobool(val, &b);
3995 	if (!ret && b) {
3996 		atomic_inc((atomic_t *)kp->arg);
3997 		rcu_barrier_throttled();
3998 		atomic_dec((atomic_t *)kp->arg);
3999 	}
4000 	return ret;
4001 }
4002 
4003 /*
4004  * Output the number of outstanding rcutree.do_rcu_barrier requests.
4005  */
4006 static int param_get_do_rcu_barrier(char *buffer, const struct kernel_param *kp)
4007 {
4008 	return sprintf(buffer, "%d\n", atomic_read((atomic_t *)kp->arg));
4009 }
4010 
4011 static const struct kernel_param_ops do_rcu_barrier_ops = {
4012 	.set = param_set_do_rcu_barrier,
4013 	.get = param_get_do_rcu_barrier,
4014 };
4015 static atomic_t do_rcu_barrier;
4016 module_param_cb(do_rcu_barrier, &do_rcu_barrier_ops, &do_rcu_barrier, 0644);
4017 
4018 /*
4019  * Compute the mask of online CPUs for the specified rcu_node structure.
4020  * This will not be stable unless the rcu_node structure's ->lock is
4021  * held, but the bit corresponding to the current CPU will be stable
4022  * in most contexts.
4023  */
4024 static unsigned long rcu_rnp_online_cpus(struct rcu_node *rnp)
4025 {
4026 	return READ_ONCE(rnp->qsmaskinitnext);
4027 }
4028 
4029 /*
4030  * Is the CPU corresponding to the specified rcu_data structure online
4031  * from RCU's perspective?  This perspective is given by that structure's
4032  * ->qsmaskinitnext field rather than by the global cpu_online_mask.
4033  */
4034 static bool rcu_rdp_cpu_online(struct rcu_data *rdp)
4035 {
4036 	return !!(rdp->grpmask & rcu_rnp_online_cpus(rdp->mynode));
4037 }
4038 
4039 bool rcu_cpu_online(int cpu)
4040 {
4041 	struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
4042 
4043 	return rcu_rdp_cpu_online(rdp);
4044 }
4045 
4046 #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU)
4047 
4048 /*
4049  * Is the current CPU online as far as RCU is concerned?
4050  *
4051  * Disable preemption to avoid false positives that could otherwise
4052  * happen due to the current CPU number being sampled, this task being
4053  * preempted, its old CPU being taken offline, resuming on some other CPU,
4054  * then determining that its old CPU is now offline.
4055  *
4056  * Disable checking if in an NMI handler because we cannot safely
4057  * report errors from NMI handlers anyway.  In addition, it is OK to use
4058  * RCU on an offline processor during initial boot, hence the check for
4059  * rcu_scheduler_fully_active.
4060  */
4061 bool notrace rcu_lockdep_current_cpu_online(void)
4062 {
4063 	struct rcu_data *rdp;
4064 	bool ret = false;
4065 
4066 	if (in_nmi() || !rcu_scheduler_fully_active)
4067 		return true;
4068 	preempt_disable_notrace();
4069 	rdp = this_cpu_ptr(&rcu_data);
4070 	/*
4071 	 * Strictly, we care here about the case where the current CPU is
4072 	 * in rcutree_report_cpu_starting() and thus has an excuse for rdp->grpmask
4073 	 * not being up to date. So arch_spin_is_locked() might have a
4074 	 * false positive if it's held by some *other* CPU, but that's
4075 	 * OK because that just means a false *negative* on the warning.
4076 	 */
4077 	if (rcu_rdp_cpu_online(rdp) || arch_spin_is_locked(&rcu_state.ofl_lock))
4078 		ret = true;
4079 	preempt_enable_notrace();
4080 	return ret;
4081 }
4082 EXPORT_SYMBOL_GPL(rcu_lockdep_current_cpu_online);
4083 
4084 #endif /* #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU) */
4085 
4086 // Has rcu_init() been invoked?  This is used (for example) to determine
4087 // whether spinlocks may be acquired safely.
4088 static bool rcu_init_invoked(void)
4089 {
4090 	return !!READ_ONCE(rcu_state.n_online_cpus);
4091 }
4092 
4093 /*
4094  * All CPUs for the specified rcu_node structure have gone offline,
4095  * and all tasks that were preempted within an RCU read-side critical
4096  * section while running on one of those CPUs have since exited their RCU
4097  * read-side critical section.  Some other CPU is reporting this fact with
4098  * the specified rcu_node structure's ->lock held and interrupts disabled.
4099  * This function therefore goes up the tree of rcu_node structures,
4100  * clearing the corresponding bits in the ->qsmaskinit fields.  Note that
4101  * the leaf rcu_node structure's ->qsmaskinit field has already been
4102  * updated.
4103  *
4104  * This function does check that the specified rcu_node structure has
4105  * all CPUs offline and no blocked tasks, so it is OK to invoke it
4106  * prematurely.  That said, invoking it after the fact will cost you
4107  * a needless lock acquisition.  So once it has done its work, don't
4108  * invoke it again.
4109  */
4110 static void rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf)
4111 {
4112 	long mask;
4113 	struct rcu_node *rnp = rnp_leaf;
4114 
4115 	raw_lockdep_assert_held_rcu_node(rnp_leaf);
4116 	if (!IS_ENABLED(CONFIG_HOTPLUG_CPU) ||
4117 	    WARN_ON_ONCE(rnp_leaf->qsmaskinit) ||
4118 	    WARN_ON_ONCE(rcu_preempt_has_tasks(rnp_leaf)))
4119 		return;
4120 	for (;;) {
4121 		mask = rnp->grpmask;
4122 		rnp = rnp->parent;
4123 		if (!rnp)
4124 			break;
4125 		raw_spin_lock_rcu_node(rnp); /* irqs already disabled. */
4126 		rnp->qsmaskinit &= ~mask;
4127 		/* Between grace periods, so better already be zero! */
4128 		WARN_ON_ONCE(rnp->qsmask);
4129 		if (rnp->qsmaskinit) {
4130 			raw_spin_unlock_rcu_node(rnp);
4131 			/* irqs remain disabled. */
4132 			return;
4133 		}
4134 		raw_spin_unlock_rcu_node(rnp); /* irqs remain disabled. */
4135 	}
4136 }
4137 
4138 /*
4139  * Propagate ->qsinitmask bits up the rcu_node tree to account for the
4140  * first CPU in a given leaf rcu_node structure coming online.  The caller
4141  * must hold the corresponding leaf rcu_node ->lock with interrupts
4142  * disabled.
4143  */
4144 static void rcu_init_new_rnp(struct rcu_node *rnp_leaf)
4145 {
4146 	long mask;
4147 	long oldmask;
4148 	struct rcu_node *rnp = rnp_leaf;
4149 
4150 	raw_lockdep_assert_held_rcu_node(rnp_leaf);
4151 	WARN_ON_ONCE(rnp->wait_blkd_tasks);
4152 	for (;;) {
4153 		mask = rnp->grpmask;
4154 		rnp = rnp->parent;
4155 		if (rnp == NULL)
4156 			return;
4157 		raw_spin_lock_rcu_node(rnp); /* Interrupts already disabled. */
4158 		oldmask = rnp->qsmaskinit;
4159 		rnp->qsmaskinit |= mask;
4160 		raw_spin_unlock_rcu_node(rnp); /* Interrupts remain disabled. */
4161 		if (oldmask)
4162 			return;
4163 	}
4164 }
4165 
4166 /*
4167  * Do boot-time initialization of a CPU's per-CPU RCU data.
4168  */
4169 static void __init
4170 rcu_boot_init_percpu_data(int cpu)
4171 {
4172 	struct context_tracking *ct = this_cpu_ptr(&context_tracking);
4173 	struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
4174 
4175 	/* Set up local state, ensuring consistent view of global state. */
4176 	rdp->grpmask = leaf_node_cpu_bit(rdp->mynode, cpu);
4177 	INIT_WORK(&rdp->strict_work, strict_work_handler);
4178 	WARN_ON_ONCE(ct->nesting != 1);
4179 	WARN_ON_ONCE(rcu_watching_snap_in_eqs(ct_rcu_watching_cpu(cpu)));
4180 	rdp->barrier_seq_snap = rcu_state.barrier_sequence;
4181 	rdp->rcu_ofl_gp_seq = rcu_state.gp_seq;
4182 	rdp->rcu_ofl_gp_state = RCU_GP_CLEANED;
4183 	rdp->rcu_onl_gp_seq = rcu_state.gp_seq;
4184 	rdp->rcu_onl_gp_state = RCU_GP_CLEANED;
4185 	rdp->last_sched_clock = jiffies;
4186 	rdp->cpu = cpu;
4187 	rcu_boot_init_nocb_percpu_data(rdp);
4188 }
4189 
4190 static void rcu_thread_affine_rnp(struct task_struct *t, struct rcu_node *rnp)
4191 {
4192 	cpumask_var_t affinity;
4193 	int cpu;
4194 
4195 	if (!zalloc_cpumask_var(&affinity, GFP_KERNEL))
4196 		return;
4197 
4198 	for_each_leaf_node_possible_cpu(rnp, cpu)
4199 		cpumask_set_cpu(cpu, affinity);
4200 
4201 	kthread_affine_preferred(t, affinity);
4202 
4203 	free_cpumask_var(affinity);
4204 }
4205 
4206 struct kthread_worker *rcu_exp_gp_kworker;
4207 
4208 static void rcu_spawn_exp_par_gp_kworker(struct rcu_node *rnp)
4209 {
4210 	struct kthread_worker *kworker;
4211 	const char *name = "rcu_exp_par_gp_kthread_worker/%d";
4212 	struct sched_param param = { .sched_priority = kthread_prio };
4213 	int rnp_index = rnp - rcu_get_root();
4214 
4215 	if (rnp->exp_kworker)
4216 		return;
4217 
4218 	kworker = kthread_create_worker(0, name, rnp_index);
4219 	if (IS_ERR_OR_NULL(kworker)) {
4220 		pr_err("Failed to create par gp kworker on %d/%d\n",
4221 		       rnp->grplo, rnp->grphi);
4222 		return;
4223 	}
4224 	WRITE_ONCE(rnp->exp_kworker, kworker);
4225 
4226 	if (IS_ENABLED(CONFIG_RCU_EXP_KTHREAD))
4227 		sched_setscheduler_nocheck(kworker->task, SCHED_FIFO, &param);
4228 
4229 	rcu_thread_affine_rnp(kworker->task, rnp);
4230 	wake_up_process(kworker->task);
4231 }
4232 
4233 static void __init rcu_start_exp_gp_kworker(void)
4234 {
4235 	const char *name = "rcu_exp_gp_kthread_worker";
4236 	struct sched_param param = { .sched_priority = kthread_prio };
4237 
4238 	rcu_exp_gp_kworker = kthread_run_worker(0, name);
4239 	if (IS_ERR_OR_NULL(rcu_exp_gp_kworker)) {
4240 		pr_err("Failed to create %s!\n", name);
4241 		rcu_exp_gp_kworker = NULL;
4242 		return;
4243 	}
4244 
4245 	if (IS_ENABLED(CONFIG_RCU_EXP_KTHREAD))
4246 		sched_setscheduler_nocheck(rcu_exp_gp_kworker->task, SCHED_FIFO, &param);
4247 }
4248 
4249 static void rcu_spawn_rnp_kthreads(struct rcu_node *rnp)
4250 {
4251 	if (rcu_scheduler_fully_active) {
4252 		mutex_lock(&rnp->kthread_mutex);
4253 		rcu_spawn_one_boost_kthread(rnp);
4254 		rcu_spawn_exp_par_gp_kworker(rnp);
4255 		mutex_unlock(&rnp->kthread_mutex);
4256 	}
4257 }
4258 
4259 /*
4260  * Invoked early in the CPU-online process, when pretty much all services
4261  * are available.  The incoming CPU is not present.
4262  *
4263  * Initializes a CPU's per-CPU RCU data.  Note that only one online or
4264  * offline event can be happening at a given time.  Note also that we can
4265  * accept some slop in the rsp->gp_seq access due to the fact that this
4266  * CPU cannot possibly have any non-offloaded RCU callbacks in flight yet.
4267  * And any offloaded callbacks are being numbered elsewhere.
4268  */
4269 int rcutree_prepare_cpu(unsigned int cpu)
4270 {
4271 	unsigned long flags;
4272 	struct context_tracking *ct = per_cpu_ptr(&context_tracking, cpu);
4273 	struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
4274 	struct rcu_node *rnp = rcu_get_root();
4275 
4276 	/* Set up local state, ensuring consistent view of global state. */
4277 	raw_spin_lock_irqsave_rcu_node(rnp, flags);
4278 	rdp->qlen_last_fqs_check = 0;
4279 	rdp->n_force_qs_snap = READ_ONCE(rcu_state.n_force_qs);
4280 	rdp->blimit = blimit;
4281 	ct->nesting = 1;	/* CPU not up, no tearing. */
4282 	raw_spin_unlock_rcu_node(rnp);		/* irqs remain disabled. */
4283 
4284 	/*
4285 	 * Only non-NOCB CPUs that didn't have early-boot callbacks need to be
4286 	 * (re-)initialized.
4287 	 */
4288 	if (!rcu_segcblist_is_enabled(&rdp->cblist))
4289 		rcu_segcblist_init(&rdp->cblist);  /* Re-enable callbacks. */
4290 
4291 	/*
4292 	 * Add CPU to leaf rcu_node pending-online bitmask.  Any needed
4293 	 * propagation up the rcu_node tree will happen at the beginning
4294 	 * of the next grace period.
4295 	 */
4296 	rnp = rdp->mynode;
4297 	raw_spin_lock_rcu_node(rnp);		/* irqs already disabled. */
4298 	rdp->gp_seq = READ_ONCE(rnp->gp_seq);
4299 	rdp->gp_seq_needed = rdp->gp_seq;
4300 	rdp->cpu_no_qs.b.norm = true;
4301 	rdp->core_needs_qs = false;
4302 	rdp->rcu_iw_pending = false;
4303 	rdp->rcu_iw = IRQ_WORK_INIT_HARD(rcu_iw_handler);
4304 	rdp->rcu_iw_gp_seq = rdp->gp_seq - 1;
4305 	trace_rcu_grace_period(rcu_state.name, rdp->gp_seq, TPS("cpuonl"));
4306 	raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4307 
4308 	rcu_preempt_deferred_qs_init(rdp);
4309 	rcu_spawn_rnp_kthreads(rnp);
4310 	rcu_spawn_cpu_nocb_kthread(cpu);
4311 	ASSERT_EXCLUSIVE_WRITER(rcu_state.n_online_cpus);
4312 	WRITE_ONCE(rcu_state.n_online_cpus, rcu_state.n_online_cpus + 1);
4313 
4314 	return 0;
4315 }
4316 
4317 /*
4318  * Has the specified (known valid) CPU ever been fully online?
4319  */
4320 bool rcu_cpu_beenfullyonline(int cpu)
4321 {
4322 	struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
4323 
4324 	return smp_load_acquire(&rdp->beenonline);
4325 }
4326 
4327 /*
4328  * Near the end of the CPU-online process.  Pretty much all services
4329  * enabled, and the CPU is now very much alive.
4330  */
4331 int rcutree_online_cpu(unsigned int cpu)
4332 {
4333 	unsigned long flags;
4334 	struct rcu_data *rdp;
4335 	struct rcu_node *rnp;
4336 
4337 	rdp = per_cpu_ptr(&rcu_data, cpu);
4338 	rnp = rdp->mynode;
4339 	raw_spin_lock_irqsave_rcu_node(rnp, flags);
4340 	rnp->ffmask |= rdp->grpmask;
4341 	raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4342 	if (rcu_scheduler_active == RCU_SCHEDULER_INACTIVE)
4343 		return 0; /* Too early in boot for scheduler work. */
4344 
4345 	// Stop-machine done, so allow nohz_full to disable tick.
4346 	tick_dep_clear(TICK_DEP_BIT_RCU);
4347 	return 0;
4348 }
4349 
4350 /*
4351  * Mark the specified CPU as being online so that subsequent grace periods
4352  * (both expedited and normal) will wait on it.  Note that this means that
4353  * incoming CPUs are not allowed to use RCU read-side critical sections
4354  * until this function is called.  Failing to observe this restriction
4355  * will result in lockdep splats.
4356  *
4357  * Note that this function is special in that it is invoked directly
4358  * from the incoming CPU rather than from the cpuhp_step mechanism.
4359  * This is because this function must be invoked at a precise location.
4360  * This incoming CPU must not have enabled interrupts yet.
4361  *
4362  * This mirrors the effects of rcutree_report_cpu_dead().
4363  */
4364 void rcutree_report_cpu_starting(unsigned int cpu)
4365 {
4366 	unsigned long mask;
4367 	struct rcu_data *rdp;
4368 	struct rcu_node *rnp;
4369 	bool newcpu;
4370 
4371 	lockdep_assert_irqs_disabled();
4372 	rdp = per_cpu_ptr(&rcu_data, cpu);
4373 	if (rdp->cpu_started)
4374 		return;
4375 	rdp->cpu_started = true;
4376 
4377 	rnp = rdp->mynode;
4378 	mask = rdp->grpmask;
4379 	arch_spin_lock(&rcu_state.ofl_lock);
4380 	rcu_watching_online();
4381 	raw_spin_lock(&rcu_state.barrier_lock);
4382 	raw_spin_lock_rcu_node(rnp);
4383 	WRITE_ONCE(rnp->qsmaskinitnext, rnp->qsmaskinitnext | mask);
4384 	raw_spin_unlock(&rcu_state.barrier_lock);
4385 	newcpu = !(rnp->expmaskinitnext & mask);
4386 	rnp->expmaskinitnext |= mask;
4387 	/* Allow lockless access for expedited grace periods. */
4388 	smp_store_release(&rcu_state.ncpus, rcu_state.ncpus + newcpu); /* ^^^ */
4389 	ASSERT_EXCLUSIVE_WRITER(rcu_state.ncpus);
4390 	rcu_gpnum_ovf(rnp, rdp); /* Offline-induced counter wrap? */
4391 	rdp->rcu_onl_gp_seq = READ_ONCE(rcu_state.gp_seq);
4392 	rdp->rcu_onl_gp_state = READ_ONCE(rcu_state.gp_state);
4393 
4394 	/* An incoming CPU should never be blocking a grace period. */
4395 	if (WARN_ON_ONCE(rnp->qsmask & mask)) { /* RCU waiting on incoming CPU? */
4396 		/* rcu_report_qs_rnp() *really* wants some flags to restore */
4397 		unsigned long flags;
4398 
4399 		local_irq_save(flags);
4400 		rcu_disable_urgency_upon_qs(rdp);
4401 		/* Report QS -after- changing ->qsmaskinitnext! */
4402 		rcu_report_qs_rnp(mask, rnp, rnp->gp_seq, flags);
4403 	} else {
4404 		raw_spin_unlock_rcu_node(rnp);
4405 	}
4406 	arch_spin_unlock(&rcu_state.ofl_lock);
4407 	smp_store_release(&rdp->beenonline, true);
4408 	smp_mb(); /* Ensure RCU read-side usage follows above initialization. */
4409 }
4410 
4411 /*
4412  * The outgoing function has no further need of RCU, so remove it from
4413  * the rcu_node tree's ->qsmaskinitnext bit masks.
4414  *
4415  * Note that this function is special in that it is invoked directly
4416  * from the outgoing CPU rather than from the cpuhp_step mechanism.
4417  * This is because this function must be invoked at a precise location.
4418  *
4419  * This mirrors the effect of rcutree_report_cpu_starting().
4420  */
4421 void rcutree_report_cpu_dead(void)
4422 {
4423 	unsigned long flags;
4424 	unsigned long mask;
4425 	struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
4426 	struct rcu_node *rnp = rdp->mynode;  /* Outgoing CPU's rdp & rnp. */
4427 
4428 	/*
4429 	 * IRQS must be disabled from now on and until the CPU dies, or an interrupt
4430 	 * may introduce a new READ-side while it is actually off the QS masks.
4431 	 */
4432 	lockdep_assert_irqs_disabled();
4433 	/*
4434 	 * CPUHP_AP_SMPCFD_DYING was the last call for rcu_exp_handler() execution.
4435 	 * The requested QS must have been reported on the last context switch
4436 	 * from stop machine to idle.
4437 	 */
4438 	WARN_ON_ONCE(rdp->cpu_no_qs.b.exp);
4439 	// Do any dangling deferred wakeups.
4440 	do_nocb_deferred_wakeup(rdp);
4441 
4442 	rcu_preempt_deferred_qs(current);
4443 
4444 	/* Remove outgoing CPU from mask in the leaf rcu_node structure. */
4445 	mask = rdp->grpmask;
4446 
4447 	/*
4448 	 * Hold the ofl_lock and rnp lock to avoid races between CPU going
4449 	 * offline and doing a QS report (as below), versus rcu_gp_init().
4450 	 * See Requirements.rst > Hotplug CPU > Concurrent QS Reporting section
4451 	 * for more details.
4452 	 */
4453 	arch_spin_lock(&rcu_state.ofl_lock);
4454 	raw_spin_lock_irqsave_rcu_node(rnp, flags); /* Enforce GP memory-order guarantee. */
4455 	rdp->rcu_ofl_gp_seq = READ_ONCE(rcu_state.gp_seq);
4456 	rdp->rcu_ofl_gp_state = READ_ONCE(rcu_state.gp_state);
4457 	if (rnp->qsmask & mask) { /* RCU waiting on outgoing CPU? */
4458 		/* Report quiescent state -before- changing ->qsmaskinitnext! */
4459 		rcu_disable_urgency_upon_qs(rdp);
4460 		rcu_report_qs_rnp(mask, rnp, rnp->gp_seq, flags);
4461 		raw_spin_lock_irqsave_rcu_node(rnp, flags);
4462 	}
4463 	/* Clear from ->qsmaskinitnext to mark offline. */
4464 	WRITE_ONCE(rnp->qsmaskinitnext, rnp->qsmaskinitnext & ~mask);
4465 	raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4466 	arch_spin_unlock(&rcu_state.ofl_lock);
4467 	rdp->cpu_started = false;
4468 }
4469 
4470 #ifdef CONFIG_HOTPLUG_CPU
4471 /*
4472  * The outgoing CPU has just passed through the dying-idle state, and we
4473  * are being invoked from the CPU that was IPIed to continue the offline
4474  * operation.  Migrate the outgoing CPU's callbacks to the current CPU.
4475  */
4476 void rcutree_migrate_callbacks(int cpu)
4477 {
4478 	unsigned long flags;
4479 	struct rcu_data *my_rdp;
4480 	struct rcu_node *my_rnp;
4481 	struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
4482 	bool needwake;
4483 
4484 	if (rcu_rdp_is_offloaded(rdp))
4485 		return;
4486 
4487 	raw_spin_lock_irqsave(&rcu_state.barrier_lock, flags);
4488 	if (rcu_segcblist_empty(&rdp->cblist)) {
4489 		raw_spin_unlock_irqrestore(&rcu_state.barrier_lock, flags);
4490 		return;  /* No callbacks to migrate. */
4491 	}
4492 
4493 	WARN_ON_ONCE(rcu_rdp_cpu_online(rdp));
4494 	rcu_barrier_entrain(rdp);
4495 	my_rdp = this_cpu_ptr(&rcu_data);
4496 	my_rnp = my_rdp->mynode;
4497 	rcu_nocb_lock(my_rdp); /* irqs already disabled. */
4498 	WARN_ON_ONCE(!rcu_nocb_flush_bypass(my_rdp, NULL, jiffies, false));
4499 	raw_spin_lock_rcu_node(my_rnp); /* irqs already disabled. */
4500 	/* Leverage recent GPs and set GP for new callbacks. */
4501 	needwake = rcu_advance_cbs(my_rnp, rdp) ||
4502 		   rcu_advance_cbs(my_rnp, my_rdp);
4503 	rcu_segcblist_merge(&my_rdp->cblist, &rdp->cblist);
4504 	raw_spin_unlock(&rcu_state.barrier_lock); /* irqs remain disabled. */
4505 	needwake = needwake || rcu_advance_cbs(my_rnp, my_rdp);
4506 	rcu_segcblist_disable(&rdp->cblist);
4507 	WARN_ON_ONCE(rcu_segcblist_empty(&my_rdp->cblist) != !rcu_segcblist_n_cbs(&my_rdp->cblist));
4508 	check_cb_ovld_locked(my_rdp, my_rnp);
4509 	if (rcu_rdp_is_offloaded(my_rdp)) {
4510 		raw_spin_unlock_rcu_node(my_rnp); /* irqs remain disabled. */
4511 		__call_rcu_nocb_wake(my_rdp, true, flags);
4512 	} else {
4513 		rcu_nocb_unlock(my_rdp); /* irqs remain disabled. */
4514 		raw_spin_unlock_rcu_node(my_rnp); /* irqs remain disabled. */
4515 	}
4516 	local_irq_restore(flags);
4517 	if (needwake)
4518 		rcu_gp_kthread_wake();
4519 	lockdep_assert_irqs_enabled();
4520 	WARN_ONCE(rcu_segcblist_n_cbs(&rdp->cblist) != 0 ||
4521 		  !rcu_segcblist_empty(&rdp->cblist),
4522 		  "rcu_cleanup_dead_cpu: Callbacks on offline CPU %d: qlen=%lu, 1stCB=%p\n",
4523 		  cpu, rcu_segcblist_n_cbs(&rdp->cblist),
4524 		  rcu_segcblist_first_cb(&rdp->cblist));
4525 }
4526 
4527 /*
4528  * The CPU has been completely removed, and some other CPU is reporting
4529  * this fact from process context.  Do the remainder of the cleanup.
4530  * There can only be one CPU hotplug operation at a time, so no need for
4531  * explicit locking.
4532  */
4533 int rcutree_dead_cpu(unsigned int cpu)
4534 {
4535 	ASSERT_EXCLUSIVE_WRITER(rcu_state.n_online_cpus);
4536 	WRITE_ONCE(rcu_state.n_online_cpus, rcu_state.n_online_cpus - 1);
4537 	// Stop-machine done, so allow nohz_full to disable tick.
4538 	tick_dep_clear(TICK_DEP_BIT_RCU);
4539 	return 0;
4540 }
4541 
4542 /*
4543  * Near the end of the offline process.  Trace the fact that this CPU
4544  * is going offline.
4545  */
4546 int rcutree_dying_cpu(unsigned int cpu)
4547 {
4548 	bool blkd;
4549 	struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
4550 	struct rcu_node *rnp = rdp->mynode;
4551 
4552 	blkd = !!(READ_ONCE(rnp->qsmask) & rdp->grpmask);
4553 	trace_rcu_grace_period(rcu_state.name, READ_ONCE(rnp->gp_seq),
4554 			       blkd ? TPS("cpuofl-bgp") : TPS("cpuofl"));
4555 	return 0;
4556 }
4557 
4558 /*
4559  * Near the beginning of the process.  The CPU is still very much alive
4560  * with pretty much all services enabled.
4561  */
4562 int rcutree_offline_cpu(unsigned int cpu)
4563 {
4564 	unsigned long flags;
4565 	struct rcu_data *rdp;
4566 	struct rcu_node *rnp;
4567 
4568 	rdp = per_cpu_ptr(&rcu_data, cpu);
4569 	rnp = rdp->mynode;
4570 	raw_spin_lock_irqsave_rcu_node(rnp, flags);
4571 	rnp->ffmask &= ~rdp->grpmask;
4572 	raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4573 
4574 	// nohz_full CPUs need the tick for stop-machine to work quickly
4575 	tick_dep_set(TICK_DEP_BIT_RCU);
4576 	return 0;
4577 }
4578 #endif /* #ifdef CONFIG_HOTPLUG_CPU */
4579 
4580 /*
4581  * On non-huge systems, use expedited RCU grace periods to make suspend
4582  * and hibernation run faster.
4583  */
4584 static int rcu_pm_notify(struct notifier_block *self,
4585 			 unsigned long action, void *hcpu)
4586 {
4587 	switch (action) {
4588 	case PM_HIBERNATION_PREPARE:
4589 	case PM_SUSPEND_PREPARE:
4590 		rcu_async_hurry();
4591 		rcu_expedite_gp();
4592 		break;
4593 	case PM_POST_HIBERNATION:
4594 	case PM_POST_SUSPEND:
4595 		rcu_unexpedite_gp();
4596 		rcu_async_relax();
4597 		break;
4598 	default:
4599 		break;
4600 	}
4601 	return NOTIFY_OK;
4602 }
4603 
4604 /*
4605  * Spawn the kthreads that handle RCU's grace periods.
4606  */
4607 static int __init rcu_spawn_gp_kthread(void)
4608 {
4609 	unsigned long flags;
4610 	struct rcu_node *rnp;
4611 	struct sched_param sp;
4612 	struct task_struct *t;
4613 	struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
4614 
4615 	rcu_scheduler_fully_active = 1;
4616 	t = kthread_create(rcu_gp_kthread, NULL, "%s", rcu_state.name);
4617 	if (WARN_ONCE(IS_ERR(t), "%s: Could not start grace-period kthread, OOM is now expected behavior\n", __func__))
4618 		return 0;
4619 	if (kthread_prio) {
4620 		sp.sched_priority = kthread_prio;
4621 		sched_setscheduler_nocheck(t, SCHED_FIFO, &sp);
4622 	}
4623 	rnp = rcu_get_root();
4624 	raw_spin_lock_irqsave_rcu_node(rnp, flags);
4625 	WRITE_ONCE(rcu_state.gp_activity, jiffies);
4626 	WRITE_ONCE(rcu_state.gp_req_activity, jiffies);
4627 	// Reset .gp_activity and .gp_req_activity before setting .gp_kthread.
4628 	smp_store_release(&rcu_state.gp_kthread, t);  /* ^^^ */
4629 	raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4630 	wake_up_process(t);
4631 	/* This is a pre-SMP initcall, we expect a single CPU */
4632 	WARN_ON(num_online_cpus() > 1);
4633 	/*
4634 	 * Those kthreads couldn't be created on rcu_init() -> rcutree_prepare_cpu()
4635 	 * due to rcu_scheduler_fully_active.
4636 	 */
4637 	rcu_spawn_cpu_nocb_kthread(smp_processor_id());
4638 	rcu_spawn_rnp_kthreads(rdp->mynode);
4639 	rcu_spawn_core_kthreads();
4640 	/* Create kthread worker for expedited GPs */
4641 	rcu_start_exp_gp_kworker();
4642 	return 0;
4643 }
4644 early_initcall(rcu_spawn_gp_kthread);
4645 
4646 /*
4647  * This function is invoked towards the end of the scheduler's
4648  * initialization process.  Before this is called, the idle task might
4649  * contain synchronous grace-period primitives (during which time, this idle
4650  * task is booting the system, and such primitives are no-ops).  After this
4651  * function is called, any synchronous grace-period primitives are run as
4652  * expedited, with the requesting task driving the grace period forward.
4653  * A later core_initcall() rcu_set_runtime_mode() will switch to full
4654  * runtime RCU functionality.
4655  */
4656 void rcu_scheduler_starting(void)
4657 {
4658 	unsigned long flags;
4659 	struct rcu_node *rnp;
4660 
4661 	WARN_ON(num_online_cpus() != 1);
4662 	WARN_ON(nr_context_switches() > 0);
4663 	rcu_test_sync_prims();
4664 
4665 	// Fix up the ->gp_seq counters.
4666 	local_irq_save(flags);
4667 	rcu_for_each_node_breadth_first(rnp)
4668 		rnp->gp_seq_needed = rnp->gp_seq = rcu_state.gp_seq;
4669 	local_irq_restore(flags);
4670 
4671 	// Switch out of early boot mode.
4672 	rcu_scheduler_active = RCU_SCHEDULER_INIT;
4673 	rcu_test_sync_prims();
4674 }
4675 
4676 /*
4677  * Helper function for rcu_init() that initializes the rcu_state structure.
4678  */
4679 static void __init rcu_init_one(void)
4680 {
4681 	static const char * const buf[] = RCU_NODE_NAME_INIT;
4682 	static const char * const fqs[] = RCU_FQS_NAME_INIT;
4683 	static struct lock_class_key rcu_node_class[RCU_NUM_LVLS];
4684 	static struct lock_class_key rcu_fqs_class[RCU_NUM_LVLS];
4685 
4686 	int levelspread[RCU_NUM_LVLS];		/* kids/node in each level. */
4687 	int cpustride = 1;
4688 	int i;
4689 	int j;
4690 	struct rcu_node *rnp;
4691 
4692 	BUILD_BUG_ON(RCU_NUM_LVLS > ARRAY_SIZE(buf));  /* Fix buf[] init! */
4693 
4694 	/* Silence gcc 4.8 false positive about array index out of range. */
4695 	if (rcu_num_lvls <= 0 || rcu_num_lvls > RCU_NUM_LVLS)
4696 		panic("rcu_init_one: rcu_num_lvls out of range");
4697 
4698 	/* Initialize the level-tracking arrays. */
4699 
4700 	for (i = 1; i < rcu_num_lvls; i++)
4701 		rcu_state.level[i] =
4702 			rcu_state.level[i - 1] + num_rcu_lvl[i - 1];
4703 	rcu_init_levelspread(levelspread, num_rcu_lvl);
4704 
4705 	/* Initialize the elements themselves, starting from the leaves. */
4706 
4707 	for (i = rcu_num_lvls - 1; i >= 0; i--) {
4708 		cpustride *= levelspread[i];
4709 		rnp = rcu_state.level[i];
4710 		for (j = 0; j < num_rcu_lvl[i]; j++, rnp++) {
4711 			raw_spin_lock_init(&ACCESS_PRIVATE(rnp, lock));
4712 			lockdep_set_class_and_name(&ACCESS_PRIVATE(rnp, lock),
4713 						   &rcu_node_class[i], buf[i]);
4714 			raw_spin_lock_init(&rnp->fqslock);
4715 			lockdep_set_class_and_name(&rnp->fqslock,
4716 						   &rcu_fqs_class[i], fqs[i]);
4717 			rnp->gp_seq = rcu_state.gp_seq;
4718 			rnp->gp_seq_needed = rcu_state.gp_seq;
4719 			rnp->completedqs = rcu_state.gp_seq;
4720 			rnp->qsmask = 0;
4721 			rnp->qsmaskinit = 0;
4722 			rnp->grplo = j * cpustride;
4723 			rnp->grphi = (j + 1) * cpustride - 1;
4724 			if (rnp->grphi >= nr_cpu_ids)
4725 				rnp->grphi = nr_cpu_ids - 1;
4726 			if (i == 0) {
4727 				rnp->grpnum = 0;
4728 				rnp->grpmask = 0;
4729 				rnp->parent = NULL;
4730 			} else {
4731 				rnp->grpnum = j % levelspread[i - 1];
4732 				rnp->grpmask = BIT(rnp->grpnum);
4733 				rnp->parent = rcu_state.level[i - 1] +
4734 					      j / levelspread[i - 1];
4735 			}
4736 			rnp->level = i;
4737 			INIT_LIST_HEAD(&rnp->blkd_tasks);
4738 			rcu_init_one_nocb(rnp);
4739 			init_waitqueue_head(&rnp->exp_wq[0]);
4740 			init_waitqueue_head(&rnp->exp_wq[1]);
4741 			init_waitqueue_head(&rnp->exp_wq[2]);
4742 			init_waitqueue_head(&rnp->exp_wq[3]);
4743 			spin_lock_init(&rnp->exp_lock);
4744 			mutex_init(&rnp->kthread_mutex);
4745 			raw_spin_lock_init(&rnp->exp_poll_lock);
4746 			rnp->exp_seq_poll_rq = RCU_GET_STATE_COMPLETED;
4747 			INIT_WORK(&rnp->exp_poll_wq, sync_rcu_do_polled_gp);
4748 		}
4749 	}
4750 
4751 	init_swait_queue_head(&rcu_state.gp_wq);
4752 	init_swait_queue_head(&rcu_state.expedited_wq);
4753 	rnp = rcu_first_leaf_node();
4754 	for_each_possible_cpu(i) {
4755 		while (i > rnp->grphi)
4756 			rnp++;
4757 		per_cpu_ptr(&rcu_data, i)->mynode = rnp;
4758 		per_cpu_ptr(&rcu_data, i)->barrier_head.next =
4759 			&per_cpu_ptr(&rcu_data, i)->barrier_head;
4760 		rcu_boot_init_percpu_data(i);
4761 	}
4762 }
4763 
4764 /*
4765  * Force priority from the kernel command-line into range.
4766  */
4767 static void __init sanitize_kthread_prio(void)
4768 {
4769 	int kthread_prio_in = kthread_prio;
4770 
4771 	if (IS_ENABLED(CONFIG_RCU_BOOST) && kthread_prio < 2
4772 	    && IS_BUILTIN(CONFIG_RCU_TORTURE_TEST))
4773 		kthread_prio = 2;
4774 	else if (IS_ENABLED(CONFIG_RCU_BOOST) && kthread_prio < 1)
4775 		kthread_prio = 1;
4776 	else if (kthread_prio < 0)
4777 		kthread_prio = 0;
4778 	else if (kthread_prio > 99)
4779 		kthread_prio = 99;
4780 
4781 	if (kthread_prio != kthread_prio_in)
4782 		pr_alert("%s: Limited prio to %d from %d\n",
4783 			 __func__, kthread_prio, kthread_prio_in);
4784 }
4785 
4786 /*
4787  * Compute the rcu_node tree geometry from kernel parameters.  This cannot
4788  * replace the definitions in tree.h because those are needed to size
4789  * the ->node array in the rcu_state structure.
4790  */
4791 void rcu_init_geometry(void)
4792 {
4793 	ulong d;
4794 	int i;
4795 	static unsigned long old_nr_cpu_ids;
4796 	int rcu_capacity[RCU_NUM_LVLS];
4797 	static bool initialized;
4798 
4799 	if (initialized) {
4800 		/*
4801 		 * Warn if setup_nr_cpu_ids() had not yet been invoked,
4802 		 * unless nr_cpus_ids == NR_CPUS, in which case who cares?
4803 		 */
4804 		WARN_ON_ONCE(old_nr_cpu_ids != nr_cpu_ids);
4805 		return;
4806 	}
4807 
4808 	old_nr_cpu_ids = nr_cpu_ids;
4809 	initialized = true;
4810 
4811 	/*
4812 	 * Initialize any unspecified boot parameters.
4813 	 * The default values of jiffies_till_first_fqs and
4814 	 * jiffies_till_next_fqs are set to the RCU_JIFFIES_TILL_FORCE_QS
4815 	 * value, which is a function of HZ, then adding one for each
4816 	 * RCU_JIFFIES_FQS_DIV CPUs that might be on the system.
4817 	 */
4818 	d = RCU_JIFFIES_TILL_FORCE_QS + nr_cpu_ids / RCU_JIFFIES_FQS_DIV;
4819 	if (jiffies_till_first_fqs == ULONG_MAX)
4820 		jiffies_till_first_fqs = d;
4821 	if (jiffies_till_next_fqs == ULONG_MAX)
4822 		jiffies_till_next_fqs = d;
4823 	adjust_jiffies_till_sched_qs();
4824 
4825 	/* If the compile-time values are accurate, just leave. */
4826 	if (rcu_fanout_leaf == RCU_FANOUT_LEAF &&
4827 	    nr_cpu_ids == NR_CPUS)
4828 		return;
4829 	pr_info("Adjusting geometry for rcu_fanout_leaf=%d, nr_cpu_ids=%u\n",
4830 		rcu_fanout_leaf, nr_cpu_ids);
4831 
4832 	/*
4833 	 * The boot-time rcu_fanout_leaf parameter must be at least two
4834 	 * and cannot exceed the number of bits in the rcu_node masks.
4835 	 * Complain and fall back to the compile-time values if this
4836 	 * limit is exceeded.
4837 	 */
4838 	if (rcu_fanout_leaf < 2 || rcu_fanout_leaf > BITS_PER_LONG) {
4839 		rcu_fanout_leaf = RCU_FANOUT_LEAF;
4840 		WARN_ON(1);
4841 		return;
4842 	}
4843 
4844 	/*
4845 	 * Compute number of nodes that can be handled an rcu_node tree
4846 	 * with the given number of levels.
4847 	 */
4848 	rcu_capacity[0] = rcu_fanout_leaf;
4849 	for (i = 1; i < RCU_NUM_LVLS; i++)
4850 		rcu_capacity[i] = rcu_capacity[i - 1] * RCU_FANOUT;
4851 
4852 	/*
4853 	 * The tree must be able to accommodate the configured number of CPUs.
4854 	 * If this limit is exceeded, fall back to the compile-time values.
4855 	 */
4856 	if (nr_cpu_ids > rcu_capacity[RCU_NUM_LVLS - 1]) {
4857 		rcu_fanout_leaf = RCU_FANOUT_LEAF;
4858 		WARN_ON(1);
4859 		return;
4860 	}
4861 
4862 	/* Calculate the number of levels in the tree. */
4863 	for (i = 0; nr_cpu_ids > rcu_capacity[i]; i++) {
4864 	}
4865 	rcu_num_lvls = i + 1;
4866 
4867 	/* Calculate the number of rcu_nodes at each level of the tree. */
4868 	for (i = 0; i < rcu_num_lvls; i++) {
4869 		int cap = rcu_capacity[(rcu_num_lvls - 1) - i];
4870 		num_rcu_lvl[i] = DIV_ROUND_UP(nr_cpu_ids, cap);
4871 	}
4872 
4873 	/* Calculate the total number of rcu_node structures. */
4874 	rcu_num_nodes = 0;
4875 	for (i = 0; i < rcu_num_lvls; i++)
4876 		rcu_num_nodes += num_rcu_lvl[i];
4877 }
4878 
4879 /*
4880  * Dump out the structure of the rcu_node combining tree associated
4881  * with the rcu_state structure.
4882  */
4883 static void __init rcu_dump_rcu_node_tree(void)
4884 {
4885 	int level = 0;
4886 	struct rcu_node *rnp;
4887 
4888 	pr_info("rcu_node tree layout dump\n");
4889 	pr_info(" ");
4890 	rcu_for_each_node_breadth_first(rnp) {
4891 		if (rnp->level != level) {
4892 			pr_cont("\n");
4893 			pr_info(" ");
4894 			level = rnp->level;
4895 		}
4896 		pr_cont("%d:%d ^%d  ", rnp->grplo, rnp->grphi, rnp->grpnum);
4897 	}
4898 	pr_cont("\n");
4899 }
4900 
4901 struct workqueue_struct *rcu_gp_wq;
4902 
4903 void __init rcu_init(void)
4904 {
4905 	int cpu = smp_processor_id();
4906 
4907 	rcu_early_boot_tests();
4908 
4909 	rcu_bootup_announce();
4910 	sanitize_kthread_prio();
4911 	rcu_init_geometry();
4912 	rcu_init_one();
4913 	if (dump_tree)
4914 		rcu_dump_rcu_node_tree();
4915 	if (use_softirq)
4916 		open_softirq(RCU_SOFTIRQ, rcu_core_si);
4917 
4918 	/*
4919 	 * We don't need protection against CPU-hotplug here because
4920 	 * this is called early in boot, before either interrupts
4921 	 * or the scheduler are operational.
4922 	 */
4923 	pm_notifier(rcu_pm_notify, 0);
4924 	WARN_ON(num_online_cpus() > 1); // Only one CPU this early in boot.
4925 	rcutree_prepare_cpu(cpu);
4926 	rcutree_report_cpu_starting(cpu);
4927 	rcutree_online_cpu(cpu);
4928 
4929 	/* Create workqueue for Tree SRCU and for expedited GPs. */
4930 	rcu_gp_wq = alloc_workqueue("rcu_gp", WQ_MEM_RECLAIM | WQ_PERCPU, 0);
4931 	WARN_ON(!rcu_gp_wq);
4932 
4933 	sync_wq = alloc_workqueue("sync_wq", WQ_MEM_RECLAIM | WQ_UNBOUND, 0);
4934 	WARN_ON(!sync_wq);
4935 
4936 	/* Fill in default value for rcutree.qovld boot parameter. */
4937 	/* -After- the rcu_node ->lock fields are initialized! */
4938 	if (qovld < 0)
4939 		qovld_calc = DEFAULT_RCU_QOVLD_MULT * qhimark;
4940 	else
4941 		qovld_calc = qovld;
4942 
4943 	// Kick-start in case any polled grace periods started early.
4944 	(void)start_poll_synchronize_rcu_expedited();
4945 
4946 	rcu_test_sync_prims();
4947 
4948 	tasks_cblist_init_generic();
4949 }
4950 
4951 #include "tree_stall.h"
4952 #include "tree_exp.h"
4953 #include "tree_nocb.h"
4954 #include "tree_plugin.h"
4955