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