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