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