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