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