1 // SPDX-License-Identifier: GPL-2.0+
3 * Read-Copy Update mechanism for mutual exclusion (tree-based version)
5 * Copyright IBM Corporation, 2008
12 * and inputs from Rusty Russell, Andrea Arcangeli and Andi Kleen.
14 * For detailed explanation of Read-Copy Update mechanism see -
18 #define pr_fmt(fmt) "rcu: " fmt
20 #include <linux/types.h>
21 #include <linux/kernel.h>
22 #include <linux/init.h>
23 #include <linux/spinlock.h>
24 #include <linux/smp.h>
25 #include <linux/rcupdate_wait.h>
26 #include <linux/interrupt.h>
27 #include <linux/sched.h>
28 #include <linux/sched/debug.h>
29 #include <linux/nmi.h>
30 #include <linux/atomic.h>
31 #include <linux/bitops.h>
32 #include <linux/export.h>
33 #include <linux/completion.h>
34 #include <linux/moduleparam.h>
35 #include <linux/percpu.h>
36 #include <linux/notifier.h>
37 #include <linux/cpu.h>
38 #include <linux/mutex.h>
39 #include <linux/time.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/wait.h>
42 #include <linux/kthread.h>
43 #include <uapi/linux/sched/types.h>
44 #include <linux/prefetch.h>
45 #include <linux/delay.h>
46 #include <linux/random.h>
47 #include <linux/trace_events.h>
48 #include <linux/suspend.h>
49 #include <linux/ftrace.h>
50 #include <linux/tick.h>
51 #include <linux/sysrq.h>
52 #include <linux/kprobes.h>
53 #include <linux/gfp.h>
54 #include <linux/oom.h>
55 #include <linux/smpboot.h>
56 #include <linux/jiffies.h>
57 #include <linux/slab.h>
58 #include <linux/sched/isolation.h>
59 #include <linux/sched/clock.h>
60 #include <linux/vmalloc.h>
62 #include <linux/kasan.h>
63 #include "../time/tick-internal.h"
68 #ifdef MODULE_PARAM_PREFIX
69 #undef MODULE_PARAM_PREFIX
71 #define MODULE_PARAM_PREFIX "rcutree."
73 /* Data structures. */
76 * Steal a bit from the bottom of ->dynticks for idle entry/exit
77 * control. Initially this is for TLB flushing.
79 #define RCU_DYNTICK_CTRL_MASK 0x1
80 #define RCU_DYNTICK_CTRL_CTR (RCU_DYNTICK_CTRL_MASK + 1)
82 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rcu_data, rcu_data) = {
83 .dynticks_nesting = 1,
84 .dynticks_nmi_nesting = DYNTICK_IRQ_NONIDLE,
85 .dynticks = ATOMIC_INIT(RCU_DYNTICK_CTRL_CTR),
87 static struct rcu_state rcu_state = {
88 .level = { &rcu_state.node[0] },
89 .gp_state = RCU_GP_IDLE,
90 .gp_seq = (0UL - 300UL) << RCU_SEQ_CTR_SHIFT,
91 .barrier_mutex = __MUTEX_INITIALIZER(rcu_state.barrier_mutex),
94 .exp_mutex = __MUTEX_INITIALIZER(rcu_state.exp_mutex),
95 .exp_wake_mutex = __MUTEX_INITIALIZER(rcu_state.exp_wake_mutex),
96 .ofl_lock = __RAW_SPIN_LOCK_UNLOCKED(rcu_state.ofl_lock),
99 /* Dump rcu_node combining tree at boot to verify correct setup. */
100 static bool dump_tree;
101 module_param(dump_tree, bool, 0444);
102 /* By default, use RCU_SOFTIRQ instead of rcuc kthreads. */
103 static bool use_softirq = !IS_ENABLED(CONFIG_PREEMPT_RT);
104 #ifndef CONFIG_PREEMPT_RT
105 module_param(use_softirq, bool, 0444);
107 /* Control rcu_node-tree auto-balancing at boot time. */
108 static bool rcu_fanout_exact;
109 module_param(rcu_fanout_exact, bool, 0444);
110 /* Increase (but not decrease) the RCU_FANOUT_LEAF at boot time. */
111 static int rcu_fanout_leaf = RCU_FANOUT_LEAF;
112 module_param(rcu_fanout_leaf, int, 0444);
113 int rcu_num_lvls __read_mostly = RCU_NUM_LVLS;
114 /* Number of rcu_nodes at specified level. */
115 int num_rcu_lvl[] = NUM_RCU_LVL_INIT;
116 int rcu_num_nodes __read_mostly = NUM_RCU_NODES; /* Total # rcu_nodes in use. */
119 * The rcu_scheduler_active variable is initialized to the value
120 * RCU_SCHEDULER_INACTIVE and transitions RCU_SCHEDULER_INIT just before the
121 * first task is spawned. So when this variable is RCU_SCHEDULER_INACTIVE,
122 * RCU can assume that there is but one task, allowing RCU to (for example)
123 * optimize synchronize_rcu() to a simple barrier(). When this variable
124 * is RCU_SCHEDULER_INIT, RCU must actually do all the hard work required
125 * to detect real grace periods. This variable is also used to suppress
126 * boot-time false positives from lockdep-RCU error checking. Finally, it
127 * transitions from RCU_SCHEDULER_INIT to RCU_SCHEDULER_RUNNING after RCU
128 * is fully initialized, including all of its kthreads having been spawned.
130 int rcu_scheduler_active __read_mostly;
131 EXPORT_SYMBOL_GPL(rcu_scheduler_active);
134 * The rcu_scheduler_fully_active variable transitions from zero to one
135 * during the early_initcall() processing, which is after the scheduler
136 * is capable of creating new tasks. So RCU processing (for example,
137 * creating tasks for RCU priority boosting) must be delayed until after
138 * rcu_scheduler_fully_active transitions from zero to one. We also
139 * currently delay invocation of any RCU callbacks until after this point.
141 * It might later prove better for people registering RCU callbacks during
142 * early boot to take responsibility for these callbacks, but one step at
145 static int rcu_scheduler_fully_active __read_mostly;
147 static void rcu_report_qs_rnp(unsigned long mask, struct rcu_node *rnp,
148 unsigned long gps, unsigned long flags);
149 static void rcu_init_new_rnp(struct rcu_node *rnp_leaf);
150 static void rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf);
151 static void rcu_boost_kthread_setaffinity(struct rcu_node *rnp, int outgoingcpu);
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);
157 /* rcuc/rcub kthread realtime priority */
158 static int kthread_prio = IS_ENABLED(CONFIG_RCU_BOOST) ? 1 : 0;
159 module_param(kthread_prio, int, 0444);
161 /* Delay in jiffies for grace-period initialization delays, debug only. */
163 static int gp_preinit_delay;
164 module_param(gp_preinit_delay, int, 0444);
165 static int gp_init_delay;
166 module_param(gp_init_delay, int, 0444);
167 static int gp_cleanup_delay;
168 module_param(gp_cleanup_delay, int, 0444);
170 // Add delay to rcu_read_unlock() for strict grace periods.
171 static int rcu_unlock_delay;
172 #ifdef CONFIG_RCU_STRICT_GRACE_PERIOD
173 module_param(rcu_unlock_delay, int, 0444);
177 * This rcu parameter is runtime-read-only. It reflects
178 * a minimum allowed number of objects which can be cached
179 * per-CPU. Object size is equal to one page. This value
180 * can be changed at boot time.
182 static int rcu_min_cached_objs = 5;
183 module_param(rcu_min_cached_objs, int, 0444);
185 /* Retrieve RCU kthreads priority for rcutorture */
186 int rcu_get_gp_kthreads_prio(void)
190 EXPORT_SYMBOL_GPL(rcu_get_gp_kthreads_prio);
193 * Number of grace periods between delays, normalized by the duration of
194 * the delay. The longer the delay, the more the grace periods between
195 * each delay. The reason for this normalization is that it means that,
196 * for non-zero delays, the overall slowdown of grace periods is constant
197 * regardless of the duration of the delay. This arrangement balances
198 * the need for long delays to increase some race probabilities with the
199 * need for fast grace periods to increase other race probabilities.
201 #define PER_RCU_NODE_PERIOD 3 /* Number of grace periods between delays. */
204 * Compute the mask of online CPUs for the specified rcu_node structure.
205 * This will not be stable unless the rcu_node structure's ->lock is
206 * held, but the bit corresponding to the current CPU will be stable
209 static unsigned long rcu_rnp_online_cpus(struct rcu_node *rnp)
211 return READ_ONCE(rnp->qsmaskinitnext);
215 * Return true if an RCU grace period is in progress. The READ_ONCE()s
216 * permit this function to be invoked without holding the root rcu_node
217 * structure's ->lock, but of course results can be subject to change.
219 static int rcu_gp_in_progress(void)
221 return rcu_seq_state(rcu_seq_current(&rcu_state.gp_seq));
225 * Return the number of callbacks queued on the specified CPU.
226 * Handles both the nocbs and normal cases.
228 static long rcu_get_n_cbs_cpu(int cpu)
230 struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
232 if (rcu_segcblist_is_enabled(&rdp->cblist))
233 return rcu_segcblist_n_cbs(&rdp->cblist);
237 void rcu_softirq_qs(void)
240 rcu_preempt_deferred_qs(current);
244 * Record entry into an extended quiescent state. This is only to be
245 * called when not already in an extended quiescent state, that is,
246 * RCU is watching prior to the call to this function and is no longer
247 * watching upon return.
249 static noinstr void rcu_dynticks_eqs_enter(void)
251 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
255 * CPUs seeing atomic_add_return() must see prior RCU read-side
256 * critical sections, and we also must force ordering with the
259 rcu_dynticks_task_trace_enter(); // Before ->dynticks update!
260 seq = arch_atomic_add_return(RCU_DYNTICK_CTRL_CTR, &rdp->dynticks);
261 // RCU is no longer watching. Better be in extended quiescent state!
262 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
263 (seq & RCU_DYNTICK_CTRL_CTR));
264 /* Better not have special action (TLB flush) pending! */
265 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
266 (seq & RCU_DYNTICK_CTRL_MASK));
270 * Record exit from an extended quiescent state. This is only to be
271 * called from an extended quiescent state, that is, RCU is not watching
272 * prior to the call to this function and is watching upon return.
274 static noinstr void rcu_dynticks_eqs_exit(void)
276 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
280 * CPUs seeing atomic_add_return() must see prior idle sojourns,
281 * and we also must force ordering with the next RCU read-side
284 seq = arch_atomic_add_return(RCU_DYNTICK_CTRL_CTR, &rdp->dynticks);
285 // RCU is now watching. Better not be in an extended quiescent state!
286 rcu_dynticks_task_trace_exit(); // After ->dynticks update!
287 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
288 !(seq & RCU_DYNTICK_CTRL_CTR));
289 if (seq & RCU_DYNTICK_CTRL_MASK) {
290 arch_atomic_andnot(RCU_DYNTICK_CTRL_MASK, &rdp->dynticks);
291 smp_mb__after_atomic(); /* _exit after clearing mask. */
296 * Reset the current CPU's ->dynticks counter to indicate that the
297 * newly onlined CPU is no longer in an extended quiescent state.
298 * This will either leave the counter unchanged, or increment it
299 * to the next non-quiescent value.
301 * The non-atomic test/increment sequence works because the upper bits
302 * of the ->dynticks counter are manipulated only by the corresponding CPU,
303 * or when the corresponding CPU is offline.
305 static void rcu_dynticks_eqs_online(void)
307 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
309 if (atomic_read(&rdp->dynticks) & RCU_DYNTICK_CTRL_CTR)
311 atomic_add(RCU_DYNTICK_CTRL_CTR, &rdp->dynticks);
315 * Is the current CPU in an extended quiescent state?
317 * No ordering, as we are sampling CPU-local information.
319 static __always_inline bool rcu_dynticks_curr_cpu_in_eqs(void)
321 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
323 return !(arch_atomic_read(&rdp->dynticks) & RCU_DYNTICK_CTRL_CTR);
327 * Snapshot the ->dynticks counter with full ordering so as to allow
328 * stable comparison of this counter with past and future snapshots.
330 static int rcu_dynticks_snap(struct rcu_data *rdp)
332 int snap = atomic_add_return(0, &rdp->dynticks);
334 return snap & ~RCU_DYNTICK_CTRL_MASK;
338 * Return true if the snapshot returned from rcu_dynticks_snap()
339 * indicates that RCU is in an extended quiescent state.
341 static bool rcu_dynticks_in_eqs(int snap)
343 return !(snap & RCU_DYNTICK_CTRL_CTR);
346 /* Return true if the specified CPU is currently idle from an RCU viewpoint. */
347 bool rcu_is_idle_cpu(int cpu)
349 struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
351 return rcu_dynticks_in_eqs(rcu_dynticks_snap(rdp));
355 * Return true if the CPU corresponding to the specified rcu_data
356 * structure has spent some time in an extended quiescent state since
357 * rcu_dynticks_snap() returned the specified snapshot.
359 static bool rcu_dynticks_in_eqs_since(struct rcu_data *rdp, int snap)
361 return snap != rcu_dynticks_snap(rdp);
365 * Return true if the referenced integer is zero while the specified
366 * CPU remains within a single extended quiescent state.
368 bool rcu_dynticks_zero_in_eqs(int cpu, int *vp)
370 struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
373 // If not quiescent, force back to earlier extended quiescent state.
374 snap = atomic_read(&rdp->dynticks) & ~(RCU_DYNTICK_CTRL_MASK |
375 RCU_DYNTICK_CTRL_CTR);
377 smp_rmb(); // Order ->dynticks and *vp reads.
379 return false; // Non-zero, so report failure;
380 smp_rmb(); // Order *vp read and ->dynticks re-read.
382 // If still in the same extended quiescent state, we are good!
383 return snap == (atomic_read(&rdp->dynticks) & ~RCU_DYNTICK_CTRL_MASK);
387 * Set the special (bottom) bit of the specified CPU so that it
388 * will take special action (such as flushing its TLB) on the
389 * next exit from an extended quiescent state. Returns true if
390 * the bit was successfully set, or false if the CPU was not in
391 * an extended quiescent state.
393 bool rcu_eqs_special_set(int cpu)
398 struct rcu_data *rdp = &per_cpu(rcu_data, cpu);
400 new_old = atomic_read(&rdp->dynticks);
403 if (old & RCU_DYNTICK_CTRL_CTR)
405 new = old | RCU_DYNTICK_CTRL_MASK;
406 new_old = atomic_cmpxchg(&rdp->dynticks, old, new);
407 } while (new_old != old);
412 * Let the RCU core know that this CPU has gone through the scheduler,
413 * which is a quiescent state. This is called when the need for a
414 * quiescent state is urgent, so we burn an atomic operation and full
415 * memory barriers to let the RCU core know about it, regardless of what
416 * this CPU might (or might not) do in the near future.
418 * We inform the RCU core by emulating a zero-duration dyntick-idle period.
420 * The caller must have disabled interrupts and must not be idle.
422 notrace void rcu_momentary_dyntick_idle(void)
426 raw_cpu_write(rcu_data.rcu_need_heavy_qs, false);
427 special = atomic_add_return(2 * RCU_DYNTICK_CTRL_CTR,
428 &this_cpu_ptr(&rcu_data)->dynticks);
429 /* It is illegal to call this from idle state. */
430 WARN_ON_ONCE(!(special & RCU_DYNTICK_CTRL_CTR));
431 rcu_preempt_deferred_qs(current);
433 EXPORT_SYMBOL_GPL(rcu_momentary_dyntick_idle);
436 * rcu_is_cpu_rrupt_from_idle - see if 'interrupted' from idle
438 * If the current CPU is idle and running at a first-level (not nested)
439 * interrupt, or directly, from idle, return true.
441 * The caller must have at least disabled IRQs.
443 static int rcu_is_cpu_rrupt_from_idle(void)
448 * Usually called from the tick; but also used from smp_function_call()
449 * for expedited grace periods. This latter can result in running from
450 * the idle task, instead of an actual IPI.
452 lockdep_assert_irqs_disabled();
454 /* Check for counter underflows */
455 RCU_LOCKDEP_WARN(__this_cpu_read(rcu_data.dynticks_nesting) < 0,
456 "RCU dynticks_nesting counter underflow!");
457 RCU_LOCKDEP_WARN(__this_cpu_read(rcu_data.dynticks_nmi_nesting) <= 0,
458 "RCU dynticks_nmi_nesting counter underflow/zero!");
460 /* Are we at first interrupt nesting level? */
461 nesting = __this_cpu_read(rcu_data.dynticks_nmi_nesting);
466 * If we're not in an interrupt, we must be in the idle task!
468 WARN_ON_ONCE(!nesting && !is_idle_task(current));
470 /* Does CPU appear to be idle from an RCU standpoint? */
471 return __this_cpu_read(rcu_data.dynticks_nesting) == 0;
474 #define DEFAULT_RCU_BLIMIT (IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD) ? 1000 : 10)
475 // Maximum callbacks per rcu_do_batch ...
476 #define DEFAULT_MAX_RCU_BLIMIT 10000 // ... even during callback flood.
477 static long blimit = DEFAULT_RCU_BLIMIT;
478 #define DEFAULT_RCU_QHIMARK 10000 // If this many pending, ignore blimit.
479 static long qhimark = DEFAULT_RCU_QHIMARK;
480 #define DEFAULT_RCU_QLOMARK 100 // Once only this many pending, use blimit.
481 static long qlowmark = DEFAULT_RCU_QLOMARK;
482 #define DEFAULT_RCU_QOVLD_MULT 2
483 #define DEFAULT_RCU_QOVLD (DEFAULT_RCU_QOVLD_MULT * DEFAULT_RCU_QHIMARK)
484 static long qovld = DEFAULT_RCU_QOVLD; // If this many pending, hammer QS.
485 static long qovld_calc = -1; // No pre-initialization lock acquisitions!
487 module_param(blimit, long, 0444);
488 module_param(qhimark, long, 0444);
489 module_param(qlowmark, long, 0444);
490 module_param(qovld, long, 0444);
492 static ulong jiffies_till_first_fqs = IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD) ? 0 : ULONG_MAX;
493 static ulong jiffies_till_next_fqs = ULONG_MAX;
494 static bool rcu_kick_kthreads;
495 static int rcu_divisor = 7;
496 module_param(rcu_divisor, int, 0644);
498 /* Force an exit from rcu_do_batch() after 3 milliseconds. */
499 static long rcu_resched_ns = 3 * NSEC_PER_MSEC;
500 module_param(rcu_resched_ns, long, 0644);
503 * How long the grace period must be before we start recruiting
504 * quiescent-state help from rcu_note_context_switch().
506 static ulong jiffies_till_sched_qs = ULONG_MAX;
507 module_param(jiffies_till_sched_qs, ulong, 0444);
508 static ulong jiffies_to_sched_qs; /* See adjust_jiffies_till_sched_qs(). */
509 module_param(jiffies_to_sched_qs, ulong, 0444); /* Display only! */
512 * Make sure that we give the grace-period kthread time to detect any
513 * idle CPUs before taking active measures to force quiescent states.
514 * However, don't go below 100 milliseconds, adjusted upwards for really
517 static void adjust_jiffies_till_sched_qs(void)
521 /* If jiffies_till_sched_qs was specified, respect the request. */
522 if (jiffies_till_sched_qs != ULONG_MAX) {
523 WRITE_ONCE(jiffies_to_sched_qs, jiffies_till_sched_qs);
526 /* Otherwise, set to third fqs scan, but bound below on large system. */
527 j = READ_ONCE(jiffies_till_first_fqs) +
528 2 * READ_ONCE(jiffies_till_next_fqs);
529 if (j < HZ / 10 + nr_cpu_ids / RCU_JIFFIES_FQS_DIV)
530 j = HZ / 10 + nr_cpu_ids / RCU_JIFFIES_FQS_DIV;
531 pr_info("RCU calculated value of scheduler-enlistment delay is %ld jiffies.\n", j);
532 WRITE_ONCE(jiffies_to_sched_qs, j);
535 static int param_set_first_fqs_jiffies(const char *val, const struct kernel_param *kp)
538 int ret = kstrtoul(val, 0, &j);
541 WRITE_ONCE(*(ulong *)kp->arg, (j > HZ) ? HZ : j);
542 adjust_jiffies_till_sched_qs();
547 static int param_set_next_fqs_jiffies(const char *val, const struct kernel_param *kp)
550 int ret = kstrtoul(val, 0, &j);
553 WRITE_ONCE(*(ulong *)kp->arg, (j > HZ) ? HZ : (j ?: 1));
554 adjust_jiffies_till_sched_qs();
559 static const struct kernel_param_ops first_fqs_jiffies_ops = {
560 .set = param_set_first_fqs_jiffies,
561 .get = param_get_ulong,
564 static const struct kernel_param_ops next_fqs_jiffies_ops = {
565 .set = param_set_next_fqs_jiffies,
566 .get = param_get_ulong,
569 module_param_cb(jiffies_till_first_fqs, &first_fqs_jiffies_ops, &jiffies_till_first_fqs, 0644);
570 module_param_cb(jiffies_till_next_fqs, &next_fqs_jiffies_ops, &jiffies_till_next_fqs, 0644);
571 module_param(rcu_kick_kthreads, bool, 0644);
573 static void force_qs_rnp(int (*f)(struct rcu_data *rdp));
574 static int rcu_pending(int user);
577 * Return the number of RCU GPs completed thus far for debug & stats.
579 unsigned long rcu_get_gp_seq(void)
581 return READ_ONCE(rcu_state.gp_seq);
583 EXPORT_SYMBOL_GPL(rcu_get_gp_seq);
586 * Return the number of RCU expedited batches completed thus far for
587 * debug & stats. Odd numbers mean that a batch is in progress, even
588 * numbers mean idle. The value returned will thus be roughly double
589 * the cumulative batches since boot.
591 unsigned long rcu_exp_batches_completed(void)
593 return rcu_state.expedited_sequence;
595 EXPORT_SYMBOL_GPL(rcu_exp_batches_completed);
598 * Return the root node of the rcu_state structure.
600 static struct rcu_node *rcu_get_root(void)
602 return &rcu_state.node[0];
606 * Send along grace-period-related data for rcutorture diagnostics.
608 void rcutorture_get_gp_data(enum rcutorture_type test_type, int *flags,
609 unsigned long *gp_seq)
613 *flags = READ_ONCE(rcu_state.gp_flags);
614 *gp_seq = rcu_seq_current(&rcu_state.gp_seq);
620 EXPORT_SYMBOL_GPL(rcutorture_get_gp_data);
623 * Enter an RCU extended quiescent state, which can be either the
624 * idle loop or adaptive-tickless usermode execution.
626 * We crowbar the ->dynticks_nmi_nesting field to zero to allow for
627 * the possibility of usermode upcalls having messed up our count
628 * of interrupt nesting level during the prior busy period.
630 static noinstr void rcu_eqs_enter(bool user)
632 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
634 WARN_ON_ONCE(rdp->dynticks_nmi_nesting != DYNTICK_IRQ_NONIDLE);
635 WRITE_ONCE(rdp->dynticks_nmi_nesting, 0);
636 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
637 rdp->dynticks_nesting == 0);
638 if (rdp->dynticks_nesting != 1) {
639 // RCU will still be watching, so just do accounting and leave.
640 rdp->dynticks_nesting--;
644 lockdep_assert_irqs_disabled();
645 instrumentation_begin();
646 trace_rcu_dyntick(TPS("Start"), rdp->dynticks_nesting, 0, atomic_read(&rdp->dynticks));
647 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) && !user && !is_idle_task(current));
648 rdp = this_cpu_ptr(&rcu_data);
649 do_nocb_deferred_wakeup(rdp);
650 rcu_prepare_for_idle();
651 rcu_preempt_deferred_qs(current);
653 // instrumentation for the noinstr rcu_dynticks_eqs_enter()
654 instrument_atomic_write(&rdp->dynticks, sizeof(rdp->dynticks));
656 instrumentation_end();
657 WRITE_ONCE(rdp->dynticks_nesting, 0); /* Avoid irq-access tearing. */
658 // RCU is watching here ...
659 rcu_dynticks_eqs_enter();
660 // ... but is no longer watching here.
661 rcu_dynticks_task_enter();
665 * rcu_idle_enter - inform RCU that current CPU is entering idle
667 * Enter idle mode, in other words, -leave- the mode in which RCU
668 * read-side critical sections can occur. (Though RCU read-side
669 * critical sections can occur in irq handlers in idle, a possibility
670 * handled by irq_enter() and irq_exit().)
672 * If you add or remove a call to rcu_idle_enter(), be sure to test with
673 * CONFIG_RCU_EQS_DEBUG=y.
675 void rcu_idle_enter(void)
677 lockdep_assert_irqs_disabled();
678 rcu_eqs_enter(false);
680 EXPORT_SYMBOL_GPL(rcu_idle_enter);
682 #ifdef CONFIG_NO_HZ_FULL
684 * rcu_user_enter - inform RCU that we are resuming userspace.
686 * Enter RCU idle mode right before resuming userspace. No use of RCU
687 * is permitted between this call and rcu_user_exit(). This way the
688 * CPU doesn't need to maintain the tick for RCU maintenance purposes
689 * when the CPU runs in userspace.
691 * If you add or remove a call to rcu_user_enter(), be sure to test with
692 * CONFIG_RCU_EQS_DEBUG=y.
694 noinstr void rcu_user_enter(void)
696 lockdep_assert_irqs_disabled();
699 #endif /* CONFIG_NO_HZ_FULL */
702 * rcu_nmi_exit - inform RCU of exit from NMI context
704 * If we are returning from the outermost NMI handler that interrupted an
705 * RCU-idle period, update rdp->dynticks and rdp->dynticks_nmi_nesting
706 * to let the RCU grace-period handling know that the CPU is back to
709 * If you add or remove a call to rcu_nmi_exit(), be sure to test
710 * with CONFIG_RCU_EQS_DEBUG=y.
712 noinstr void rcu_nmi_exit(void)
714 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
716 instrumentation_begin();
718 * Check for ->dynticks_nmi_nesting underflow and bad ->dynticks.
719 * (We are exiting an NMI handler, so RCU better be paying attention
722 WARN_ON_ONCE(rdp->dynticks_nmi_nesting <= 0);
723 WARN_ON_ONCE(rcu_dynticks_curr_cpu_in_eqs());
726 * If the nesting level is not 1, the CPU wasn't RCU-idle, so
727 * leave it in non-RCU-idle state.
729 if (rdp->dynticks_nmi_nesting != 1) {
730 trace_rcu_dyntick(TPS("--="), rdp->dynticks_nmi_nesting, rdp->dynticks_nmi_nesting - 2,
731 atomic_read(&rdp->dynticks));
732 WRITE_ONCE(rdp->dynticks_nmi_nesting, /* No store tearing. */
733 rdp->dynticks_nmi_nesting - 2);
734 instrumentation_end();
738 /* This NMI interrupted an RCU-idle CPU, restore RCU-idleness. */
739 trace_rcu_dyntick(TPS("Startirq"), rdp->dynticks_nmi_nesting, 0, atomic_read(&rdp->dynticks));
740 WRITE_ONCE(rdp->dynticks_nmi_nesting, 0); /* Avoid store tearing. */
743 rcu_prepare_for_idle();
745 // instrumentation for the noinstr rcu_dynticks_eqs_enter()
746 instrument_atomic_write(&rdp->dynticks, sizeof(rdp->dynticks));
747 instrumentation_end();
749 // RCU is watching here ...
750 rcu_dynticks_eqs_enter();
751 // ... but is no longer watching here.
754 rcu_dynticks_task_enter();
758 * rcu_irq_exit - inform RCU that current CPU is exiting irq towards idle
760 * Exit from an interrupt handler, which might possibly result in entering
761 * idle mode, in other words, leaving the mode in which read-side critical
762 * sections can occur. The caller must have disabled interrupts.
764 * This code assumes that the idle loop never does anything that might
765 * result in unbalanced calls to irq_enter() and irq_exit(). If your
766 * architecture's idle loop violates this assumption, RCU will give you what
767 * you deserve, good and hard. But very infrequently and irreproducibly.
769 * Use things like work queues to work around this limitation.
771 * You have been warned.
773 * If you add or remove a call to rcu_irq_exit(), be sure to test with
774 * CONFIG_RCU_EQS_DEBUG=y.
776 void noinstr rcu_irq_exit(void)
778 lockdep_assert_irqs_disabled();
783 * rcu_irq_exit_preempt - Inform RCU that current CPU is exiting irq
784 * towards in kernel preemption
786 * Same as rcu_irq_exit() but has a sanity check that scheduling is safe
787 * from RCU point of view. Invoked from return from interrupt before kernel
790 void rcu_irq_exit_preempt(void)
792 lockdep_assert_irqs_disabled();
795 RCU_LOCKDEP_WARN(__this_cpu_read(rcu_data.dynticks_nesting) <= 0,
796 "RCU dynticks_nesting counter underflow/zero!");
797 RCU_LOCKDEP_WARN(__this_cpu_read(rcu_data.dynticks_nmi_nesting) !=
799 "Bad RCU dynticks_nmi_nesting counter\n");
800 RCU_LOCKDEP_WARN(rcu_dynticks_curr_cpu_in_eqs(),
801 "RCU in extended quiescent state!");
804 #ifdef CONFIG_PROVE_RCU
806 * rcu_irq_exit_check_preempt - Validate that scheduling is possible
808 void rcu_irq_exit_check_preempt(void)
810 lockdep_assert_irqs_disabled();
812 RCU_LOCKDEP_WARN(__this_cpu_read(rcu_data.dynticks_nesting) <= 0,
813 "RCU dynticks_nesting counter underflow/zero!");
814 RCU_LOCKDEP_WARN(__this_cpu_read(rcu_data.dynticks_nmi_nesting) !=
816 "Bad RCU dynticks_nmi_nesting counter\n");
817 RCU_LOCKDEP_WARN(rcu_dynticks_curr_cpu_in_eqs(),
818 "RCU in extended quiescent state!");
820 #endif /* #ifdef CONFIG_PROVE_RCU */
823 * Wrapper for rcu_irq_exit() where interrupts are enabled.
825 * If you add or remove a call to rcu_irq_exit_irqson(), be sure to test
826 * with CONFIG_RCU_EQS_DEBUG=y.
828 void rcu_irq_exit_irqson(void)
832 local_irq_save(flags);
834 local_irq_restore(flags);
838 * Exit an RCU extended quiescent state, which can be either the
839 * idle loop or adaptive-tickless usermode execution.
841 * We crowbar the ->dynticks_nmi_nesting field to DYNTICK_IRQ_NONIDLE to
842 * allow for the possibility of usermode upcalls messing up our count of
843 * interrupt nesting level during the busy period that is just now starting.
845 static void noinstr rcu_eqs_exit(bool user)
847 struct rcu_data *rdp;
850 lockdep_assert_irqs_disabled();
851 rdp = this_cpu_ptr(&rcu_data);
852 oldval = rdp->dynticks_nesting;
853 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) && oldval < 0);
855 // RCU was already watching, so just do accounting and leave.
856 rdp->dynticks_nesting++;
859 rcu_dynticks_task_exit();
860 // RCU is not watching here ...
861 rcu_dynticks_eqs_exit();
862 // ... but is watching here.
863 instrumentation_begin();
865 // instrumentation for the noinstr rcu_dynticks_eqs_exit()
866 instrument_atomic_write(&rdp->dynticks, sizeof(rdp->dynticks));
868 rcu_cleanup_after_idle();
869 trace_rcu_dyntick(TPS("End"), rdp->dynticks_nesting, 1, atomic_read(&rdp->dynticks));
870 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) && !user && !is_idle_task(current));
871 WRITE_ONCE(rdp->dynticks_nesting, 1);
872 WARN_ON_ONCE(rdp->dynticks_nmi_nesting);
873 WRITE_ONCE(rdp->dynticks_nmi_nesting, DYNTICK_IRQ_NONIDLE);
874 instrumentation_end();
878 * rcu_idle_exit - inform RCU that current CPU is leaving idle
880 * Exit idle mode, in other words, -enter- the mode in which RCU
881 * read-side critical sections can occur.
883 * If you add or remove a call to rcu_idle_exit(), be sure to test with
884 * CONFIG_RCU_EQS_DEBUG=y.
886 void rcu_idle_exit(void)
890 local_irq_save(flags);
892 local_irq_restore(flags);
894 EXPORT_SYMBOL_GPL(rcu_idle_exit);
896 #ifdef CONFIG_NO_HZ_FULL
898 * rcu_user_exit - inform RCU that we are exiting userspace.
900 * Exit RCU idle mode while entering the kernel because it can
901 * run a RCU read side critical section anytime.
903 * If you add or remove a call to rcu_user_exit(), be sure to test with
904 * CONFIG_RCU_EQS_DEBUG=y.
906 void noinstr rcu_user_exit(void)
912 * __rcu_irq_enter_check_tick - Enable scheduler tick on CPU if RCU needs it.
914 * The scheduler tick is not normally enabled when CPUs enter the kernel
915 * from nohz_full userspace execution. After all, nohz_full userspace
916 * execution is an RCU quiescent state and the time executing in the kernel
917 * is quite short. Except of course when it isn't. And it is not hard to
918 * cause a large system to spend tens of seconds or even minutes looping
919 * in the kernel, which can cause a number of problems, include RCU CPU
922 * Therefore, if a nohz_full CPU fails to report a quiescent state
923 * in a timely manner, the RCU grace-period kthread sets that CPU's
924 * ->rcu_urgent_qs flag with the expectation that the next interrupt or
925 * exception will invoke this function, which will turn on the scheduler
926 * tick, which will enable RCU to detect that CPU's quiescent states,
927 * for example, due to cond_resched() calls in CONFIG_PREEMPT=n kernels.
928 * The tick will be disabled once a quiescent state is reported for
931 * Of course, in carefully tuned systems, there might never be an
932 * interrupt or exception. In that case, the RCU grace-period kthread
933 * will eventually cause one to happen. However, in less carefully
934 * controlled environments, this function allows RCU to get what it
935 * needs without creating otherwise useless interruptions.
937 void __rcu_irq_enter_check_tick(void)
939 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
941 // If we're here from NMI there's nothing to do.
945 RCU_LOCKDEP_WARN(rcu_dynticks_curr_cpu_in_eqs(),
946 "Illegal rcu_irq_enter_check_tick() from extended quiescent state");
948 if (!tick_nohz_full_cpu(rdp->cpu) ||
949 !READ_ONCE(rdp->rcu_urgent_qs) ||
950 READ_ONCE(rdp->rcu_forced_tick)) {
951 // RCU doesn't need nohz_full help from this CPU, or it is
952 // already getting that help.
956 // We get here only when not in an extended quiescent state and
957 // from interrupts (as opposed to NMIs). Therefore, (1) RCU is
958 // already watching and (2) The fact that we are in an interrupt
959 // handler and that the rcu_node lock is an irq-disabled lock
960 // prevents self-deadlock. So we can safely recheck under the lock.
961 // Note that the nohz_full state currently cannot change.
962 raw_spin_lock_rcu_node(rdp->mynode);
963 if (rdp->rcu_urgent_qs && !rdp->rcu_forced_tick) {
964 // A nohz_full CPU is in the kernel and RCU needs a
965 // quiescent state. Turn on the tick!
966 WRITE_ONCE(rdp->rcu_forced_tick, true);
967 tick_dep_set_cpu(rdp->cpu, TICK_DEP_BIT_RCU);
969 raw_spin_unlock_rcu_node(rdp->mynode);
971 #endif /* CONFIG_NO_HZ_FULL */
974 * rcu_nmi_enter - inform RCU of entry to NMI context
976 * If the CPU was idle from RCU's viewpoint, update rdp->dynticks and
977 * rdp->dynticks_nmi_nesting to let the RCU grace-period handling know
978 * that the CPU is active. This implementation permits nested NMIs, as
979 * long as the nesting level does not overflow an int. (You will probably
980 * run out of stack space first.)
982 * If you add or remove a call to rcu_nmi_enter(), be sure to test
983 * with CONFIG_RCU_EQS_DEBUG=y.
985 noinstr void rcu_nmi_enter(void)
988 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
990 /* Complain about underflow. */
991 WARN_ON_ONCE(rdp->dynticks_nmi_nesting < 0);
994 * If idle from RCU viewpoint, atomically increment ->dynticks
995 * to mark non-idle and increment ->dynticks_nmi_nesting by one.
996 * Otherwise, increment ->dynticks_nmi_nesting by two. This means
997 * if ->dynticks_nmi_nesting is equal to one, we are guaranteed
998 * to be in the outermost NMI handler that interrupted an RCU-idle
999 * period (observation due to Andy Lutomirski).
1001 if (rcu_dynticks_curr_cpu_in_eqs()) {
1004 rcu_dynticks_task_exit();
1006 // RCU is not watching here ...
1007 rcu_dynticks_eqs_exit();
1008 // ... but is watching here.
1011 instrumentation_begin();
1012 rcu_cleanup_after_idle();
1013 instrumentation_end();
1016 instrumentation_begin();
1017 // instrumentation for the noinstr rcu_dynticks_curr_cpu_in_eqs()
1018 instrument_atomic_read(&rdp->dynticks, sizeof(rdp->dynticks));
1019 // instrumentation for the noinstr rcu_dynticks_eqs_exit()
1020 instrument_atomic_write(&rdp->dynticks, sizeof(rdp->dynticks));
1023 } else if (!in_nmi()) {
1024 instrumentation_begin();
1025 rcu_irq_enter_check_tick();
1026 instrumentation_end();
1028 instrumentation_begin();
1031 trace_rcu_dyntick(incby == 1 ? TPS("Endirq") : TPS("++="),
1032 rdp->dynticks_nmi_nesting,
1033 rdp->dynticks_nmi_nesting + incby, atomic_read(&rdp->dynticks));
1034 instrumentation_end();
1035 WRITE_ONCE(rdp->dynticks_nmi_nesting, /* Prevent store tearing. */
1036 rdp->dynticks_nmi_nesting + incby);
1041 * rcu_irq_enter - inform RCU that current CPU is entering irq away from idle
1043 * Enter an interrupt handler, which might possibly result in exiting
1044 * idle mode, in other words, entering the mode in which read-side critical
1045 * sections can occur. The caller must have disabled interrupts.
1047 * Note that the Linux kernel is fully capable of entering an interrupt
1048 * handler that it never exits, for example when doing upcalls to user mode!
1049 * This code assumes that the idle loop never does upcalls to user mode.
1050 * If your architecture's idle loop does do upcalls to user mode (or does
1051 * anything else that results in unbalanced calls to the irq_enter() and
1052 * irq_exit() functions), RCU will give you what you deserve, good and hard.
1053 * But very infrequently and irreproducibly.
1055 * Use things like work queues to work around this limitation.
1057 * You have been warned.
1059 * If you add or remove a call to rcu_irq_enter(), be sure to test with
1060 * CONFIG_RCU_EQS_DEBUG=y.
1062 noinstr void rcu_irq_enter(void)
1064 lockdep_assert_irqs_disabled();
1069 * Wrapper for rcu_irq_enter() where interrupts are enabled.
1071 * If you add or remove a call to rcu_irq_enter_irqson(), be sure to test
1072 * with CONFIG_RCU_EQS_DEBUG=y.
1074 void rcu_irq_enter_irqson(void)
1076 unsigned long flags;
1078 local_irq_save(flags);
1080 local_irq_restore(flags);
1084 * If any sort of urgency was applied to the current CPU (for example,
1085 * the scheduler-clock interrupt was enabled on a nohz_full CPU) in order
1086 * to get to a quiescent state, disable it.
1088 static void rcu_disable_urgency_upon_qs(struct rcu_data *rdp)
1090 raw_lockdep_assert_held_rcu_node(rdp->mynode);
1091 WRITE_ONCE(rdp->rcu_urgent_qs, false);
1092 WRITE_ONCE(rdp->rcu_need_heavy_qs, false);
1093 if (tick_nohz_full_cpu(rdp->cpu) && rdp->rcu_forced_tick) {
1094 tick_dep_clear_cpu(rdp->cpu, TICK_DEP_BIT_RCU);
1095 WRITE_ONCE(rdp->rcu_forced_tick, false);
1100 * rcu_is_watching - see if RCU thinks that the current CPU is not idle
1102 * Return true if RCU is watching the running CPU, which means that this
1103 * CPU can safely enter RCU read-side critical sections. In other words,
1104 * if the current CPU is not in its idle loop or is in an interrupt or
1105 * NMI handler, return true.
1107 * Make notrace because it can be called by the internal functions of
1108 * ftrace, and making this notrace removes unnecessary recursion calls.
1110 notrace bool rcu_is_watching(void)
1114 preempt_disable_notrace();
1115 ret = !rcu_dynticks_curr_cpu_in_eqs();
1116 preempt_enable_notrace();
1119 EXPORT_SYMBOL_GPL(rcu_is_watching);
1122 * If a holdout task is actually running, request an urgent quiescent
1123 * state from its CPU. This is unsynchronized, so migrations can cause
1124 * the request to go to the wrong CPU. Which is OK, all that will happen
1125 * is that the CPU's next context switch will be a bit slower and next
1126 * time around this task will generate another request.
1128 void rcu_request_urgent_qs_task(struct task_struct *t)
1135 return; /* This task is not running on that CPU. */
1136 smp_store_release(per_cpu_ptr(&rcu_data.rcu_urgent_qs, cpu), true);
1139 #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU)
1142 * Is the current CPU online as far as RCU is concerned?
1144 * Disable preemption to avoid false positives that could otherwise
1145 * happen due to the current CPU number being sampled, this task being
1146 * preempted, its old CPU being taken offline, resuming on some other CPU,
1147 * then determining that its old CPU is now offline.
1149 * Disable checking if in an NMI handler because we cannot safely
1150 * report errors from NMI handlers anyway. In addition, it is OK to use
1151 * RCU on an offline processor during initial boot, hence the check for
1152 * rcu_scheduler_fully_active.
1154 bool rcu_lockdep_current_cpu_online(void)
1156 struct rcu_data *rdp;
1157 struct rcu_node *rnp;
1160 if (in_nmi() || !rcu_scheduler_fully_active)
1162 preempt_disable_notrace();
1163 rdp = this_cpu_ptr(&rcu_data);
1165 if (rdp->grpmask & rcu_rnp_online_cpus(rnp) || READ_ONCE(rnp->ofl_seq) & 0x1)
1167 preempt_enable_notrace();
1170 EXPORT_SYMBOL_GPL(rcu_lockdep_current_cpu_online);
1172 #endif /* #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU) */
1175 * We are reporting a quiescent state on behalf of some other CPU, so
1176 * it is our responsibility to check for and handle potential overflow
1177 * of the rcu_node ->gp_seq counter with respect to the rcu_data counters.
1178 * After all, the CPU might be in deep idle state, and thus executing no
1181 static void rcu_gpnum_ovf(struct rcu_node *rnp, struct rcu_data *rdp)
1183 raw_lockdep_assert_held_rcu_node(rnp);
1184 if (ULONG_CMP_LT(rcu_seq_current(&rdp->gp_seq) + ULONG_MAX / 4,
1186 WRITE_ONCE(rdp->gpwrap, true);
1187 if (ULONG_CMP_LT(rdp->rcu_iw_gp_seq + ULONG_MAX / 4, rnp->gp_seq))
1188 rdp->rcu_iw_gp_seq = rnp->gp_seq + ULONG_MAX / 4;
1192 * Snapshot the specified CPU's dynticks counter so that we can later
1193 * credit them with an implicit quiescent state. Return 1 if this CPU
1194 * is in dynticks idle mode, which is an extended quiescent state.
1196 static int dyntick_save_progress_counter(struct rcu_data *rdp)
1198 rdp->dynticks_snap = rcu_dynticks_snap(rdp);
1199 if (rcu_dynticks_in_eqs(rdp->dynticks_snap)) {
1200 trace_rcu_fqs(rcu_state.name, rdp->gp_seq, rdp->cpu, TPS("dti"));
1201 rcu_gpnum_ovf(rdp->mynode, rdp);
1208 * Return true if the specified CPU has passed through a quiescent
1209 * state by virtue of being in or having passed through an dynticks
1210 * idle state since the last call to dyntick_save_progress_counter()
1211 * for this same CPU, or by virtue of having been offline.
1213 static int rcu_implicit_dynticks_qs(struct rcu_data *rdp)
1218 struct rcu_node *rnp = rdp->mynode;
1221 * If the CPU passed through or entered a dynticks idle phase with
1222 * no active irq/NMI handlers, then we can safely pretend that the CPU
1223 * already acknowledged the request to pass through a quiescent
1224 * state. Either way, that CPU cannot possibly be in an RCU
1225 * read-side critical section that started before the beginning
1226 * of the current RCU grace period.
1228 if (rcu_dynticks_in_eqs_since(rdp, rdp->dynticks_snap)) {
1229 trace_rcu_fqs(rcu_state.name, rdp->gp_seq, rdp->cpu, TPS("dti"));
1230 rcu_gpnum_ovf(rnp, rdp);
1235 * Complain if a CPU that is considered to be offline from RCU's
1236 * perspective has not yet reported a quiescent state. After all,
1237 * the offline CPU should have reported a quiescent state during
1238 * the CPU-offline process, or, failing that, by rcu_gp_init()
1239 * if it ran concurrently with either the CPU going offline or the
1240 * last task on a leaf rcu_node structure exiting its RCU read-side
1241 * critical section while all CPUs corresponding to that structure
1242 * are offline. This added warning detects bugs in any of these
1245 * The rcu_node structure's ->lock is held here, which excludes
1246 * the relevant portions the CPU-hotplug code, the grace-period
1247 * initialization code, and the rcu_read_unlock() code paths.
1249 * For more detail, please refer to the "Hotplug CPU" section
1250 * of RCU's Requirements documentation.
1252 if (WARN_ON_ONCE(!(rdp->grpmask & rcu_rnp_online_cpus(rnp)))) {
1254 struct rcu_node *rnp1;
1256 pr_info("%s: grp: %d-%d level: %d ->gp_seq %ld ->completedqs %ld\n",
1257 __func__, rnp->grplo, rnp->grphi, rnp->level,
1258 (long)rnp->gp_seq, (long)rnp->completedqs);
1259 for (rnp1 = rnp; rnp1; rnp1 = rnp1->parent)
1260 pr_info("%s: %d:%d ->qsmask %#lx ->qsmaskinit %#lx ->qsmaskinitnext %#lx ->rcu_gp_init_mask %#lx\n",
1261 __func__, rnp1->grplo, rnp1->grphi, rnp1->qsmask, rnp1->qsmaskinit, rnp1->qsmaskinitnext, rnp1->rcu_gp_init_mask);
1262 onl = !!(rdp->grpmask & rcu_rnp_online_cpus(rnp));
1263 pr_info("%s %d: %c online: %ld(%d) offline: %ld(%d)\n",
1264 __func__, rdp->cpu, ".o"[onl],
1265 (long)rdp->rcu_onl_gp_seq, rdp->rcu_onl_gp_flags,
1266 (long)rdp->rcu_ofl_gp_seq, rdp->rcu_ofl_gp_flags);
1267 return 1; /* Break things loose after complaining. */
1271 * A CPU running for an extended time within the kernel can
1272 * delay RCU grace periods: (1) At age jiffies_to_sched_qs,
1273 * set .rcu_urgent_qs, (2) At age 2*jiffies_to_sched_qs, set
1274 * both .rcu_need_heavy_qs and .rcu_urgent_qs. Note that the
1275 * unsynchronized assignments to the per-CPU rcu_need_heavy_qs
1276 * variable are safe because the assignments are repeated if this
1277 * CPU failed to pass through a quiescent state. This code
1278 * also checks .jiffies_resched in case jiffies_to_sched_qs
1281 jtsq = READ_ONCE(jiffies_to_sched_qs);
1282 ruqp = per_cpu_ptr(&rcu_data.rcu_urgent_qs, rdp->cpu);
1283 rnhqp = &per_cpu(rcu_data.rcu_need_heavy_qs, rdp->cpu);
1284 if (!READ_ONCE(*rnhqp) &&
1285 (time_after(jiffies, rcu_state.gp_start + jtsq * 2) ||
1286 time_after(jiffies, rcu_state.jiffies_resched) ||
1287 rcu_state.cbovld)) {
1288 WRITE_ONCE(*rnhqp, true);
1289 /* Store rcu_need_heavy_qs before rcu_urgent_qs. */
1290 smp_store_release(ruqp, true);
1291 } else if (time_after(jiffies, rcu_state.gp_start + jtsq)) {
1292 WRITE_ONCE(*ruqp, true);
1296 * NO_HZ_FULL CPUs can run in-kernel without rcu_sched_clock_irq!
1297 * The above code handles this, but only for straight cond_resched().
1298 * And some in-kernel loops check need_resched() before calling
1299 * cond_resched(), which defeats the above code for CPUs that are
1300 * running in-kernel with scheduling-clock interrupts disabled.
1301 * So hit them over the head with the resched_cpu() hammer!
1303 if (tick_nohz_full_cpu(rdp->cpu) &&
1304 (time_after(jiffies, READ_ONCE(rdp->last_fqs_resched) + jtsq * 3) ||
1305 rcu_state.cbovld)) {
1306 WRITE_ONCE(*ruqp, true);
1307 resched_cpu(rdp->cpu);
1308 WRITE_ONCE(rdp->last_fqs_resched, jiffies);
1312 * If more than halfway to RCU CPU stall-warning time, invoke
1313 * resched_cpu() more frequently to try to loosen things up a bit.
1314 * Also check to see if the CPU is getting hammered with interrupts,
1315 * but only once per grace period, just to keep the IPIs down to
1318 if (time_after(jiffies, rcu_state.jiffies_resched)) {
1319 if (time_after(jiffies,
1320 READ_ONCE(rdp->last_fqs_resched) + jtsq)) {
1321 resched_cpu(rdp->cpu);
1322 WRITE_ONCE(rdp->last_fqs_resched, jiffies);
1324 if (IS_ENABLED(CONFIG_IRQ_WORK) &&
1325 !rdp->rcu_iw_pending && rdp->rcu_iw_gp_seq != rnp->gp_seq &&
1326 (rnp->ffmask & rdp->grpmask)) {
1327 rdp->rcu_iw_pending = true;
1328 rdp->rcu_iw_gp_seq = rnp->gp_seq;
1329 irq_work_queue_on(&rdp->rcu_iw, rdp->cpu);
1336 /* Trace-event wrapper function for trace_rcu_future_grace_period. */
1337 static void trace_rcu_this_gp(struct rcu_node *rnp, struct rcu_data *rdp,
1338 unsigned long gp_seq_req, const char *s)
1340 trace_rcu_future_grace_period(rcu_state.name, READ_ONCE(rnp->gp_seq),
1341 gp_seq_req, rnp->level,
1342 rnp->grplo, rnp->grphi, s);
1346 * rcu_start_this_gp - Request the start of a particular grace period
1347 * @rnp_start: The leaf node of the CPU from which to start.
1348 * @rdp: The rcu_data corresponding to the CPU from which to start.
1349 * @gp_seq_req: The gp_seq of the grace period to start.
1351 * Start the specified grace period, as needed to handle newly arrived
1352 * callbacks. The required future grace periods are recorded in each
1353 * rcu_node structure's ->gp_seq_needed field. Returns true if there
1354 * is reason to awaken the grace-period kthread.
1356 * The caller must hold the specified rcu_node structure's ->lock, which
1357 * is why the caller is responsible for waking the grace-period kthread.
1359 * Returns true if the GP thread needs to be awakened else false.
1361 static bool rcu_start_this_gp(struct rcu_node *rnp_start, struct rcu_data *rdp,
1362 unsigned long gp_seq_req)
1365 struct rcu_node *rnp;
1368 * Use funnel locking to either acquire the root rcu_node
1369 * structure's lock or bail out if the need for this grace period
1370 * has already been recorded -- or if that grace period has in
1371 * fact already started. If there is already a grace period in
1372 * progress in a non-leaf node, no recording is needed because the
1373 * end of the grace period will scan the leaf rcu_node structures.
1374 * Note that rnp_start->lock must not be released.
1376 raw_lockdep_assert_held_rcu_node(rnp_start);
1377 trace_rcu_this_gp(rnp_start, rdp, gp_seq_req, TPS("Startleaf"));
1378 for (rnp = rnp_start; 1; rnp = rnp->parent) {
1379 if (rnp != rnp_start)
1380 raw_spin_lock_rcu_node(rnp);
1381 if (ULONG_CMP_GE(rnp->gp_seq_needed, gp_seq_req) ||
1382 rcu_seq_started(&rnp->gp_seq, gp_seq_req) ||
1383 (rnp != rnp_start &&
1384 rcu_seq_state(rcu_seq_current(&rnp->gp_seq)))) {
1385 trace_rcu_this_gp(rnp, rdp, gp_seq_req,
1389 WRITE_ONCE(rnp->gp_seq_needed, gp_seq_req);
1390 if (rcu_seq_state(rcu_seq_current(&rnp->gp_seq))) {
1392 * We just marked the leaf or internal node, and a
1393 * grace period is in progress, which means that
1394 * rcu_gp_cleanup() will see the marking. Bail to
1395 * reduce contention.
1397 trace_rcu_this_gp(rnp_start, rdp, gp_seq_req,
1398 TPS("Startedleaf"));
1401 if (rnp != rnp_start && rnp->parent != NULL)
1402 raw_spin_unlock_rcu_node(rnp);
1404 break; /* At root, and perhaps also leaf. */
1407 /* If GP already in progress, just leave, otherwise start one. */
1408 if (rcu_gp_in_progress()) {
1409 trace_rcu_this_gp(rnp, rdp, gp_seq_req, TPS("Startedleafroot"));
1412 trace_rcu_this_gp(rnp, rdp, gp_seq_req, TPS("Startedroot"));
1413 WRITE_ONCE(rcu_state.gp_flags, rcu_state.gp_flags | RCU_GP_FLAG_INIT);
1414 WRITE_ONCE(rcu_state.gp_req_activity, jiffies);
1415 if (!READ_ONCE(rcu_state.gp_kthread)) {
1416 trace_rcu_this_gp(rnp, rdp, gp_seq_req, TPS("NoGPkthread"));
1419 trace_rcu_grace_period(rcu_state.name, data_race(rcu_state.gp_seq), TPS("newreq"));
1420 ret = true; /* Caller must wake GP kthread. */
1422 /* Push furthest requested GP to leaf node and rcu_data structure. */
1423 if (ULONG_CMP_LT(gp_seq_req, rnp->gp_seq_needed)) {
1424 WRITE_ONCE(rnp_start->gp_seq_needed, rnp->gp_seq_needed);
1425 WRITE_ONCE(rdp->gp_seq_needed, rnp->gp_seq_needed);
1427 if (rnp != rnp_start)
1428 raw_spin_unlock_rcu_node(rnp);
1433 * Clean up any old requests for the just-ended grace period. Also return
1434 * whether any additional grace periods have been requested.
1436 static bool rcu_future_gp_cleanup(struct rcu_node *rnp)
1439 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
1441 needmore = ULONG_CMP_LT(rnp->gp_seq, rnp->gp_seq_needed);
1443 rnp->gp_seq_needed = rnp->gp_seq; /* Avoid counter wrap. */
1444 trace_rcu_this_gp(rnp, rdp, rnp->gp_seq,
1445 needmore ? TPS("CleanupMore") : TPS("Cleanup"));
1450 * Awaken the grace-period kthread. Don't do a self-awaken (unless in an
1451 * interrupt or softirq handler, in which case we just might immediately
1452 * sleep upon return, resulting in a grace-period hang), and don't bother
1453 * awakening when there is nothing for the grace-period kthread to do
1454 * (as in several CPUs raced to awaken, we lost), and finally don't try
1455 * to awaken a kthread that has not yet been created. If all those checks
1456 * are passed, track some debug information and awaken.
1458 * So why do the self-wakeup when in an interrupt or softirq handler
1459 * in the grace-period kthread's context? Because the kthread might have
1460 * been interrupted just as it was going to sleep, and just after the final
1461 * pre-sleep check of the awaken condition. In this case, a wakeup really
1462 * is required, and is therefore supplied.
1464 static void rcu_gp_kthread_wake(void)
1466 struct task_struct *t = READ_ONCE(rcu_state.gp_kthread);
1468 if ((current == t && !in_irq() && !in_serving_softirq()) ||
1469 !READ_ONCE(rcu_state.gp_flags) || !t)
1471 WRITE_ONCE(rcu_state.gp_wake_time, jiffies);
1472 WRITE_ONCE(rcu_state.gp_wake_seq, READ_ONCE(rcu_state.gp_seq));
1473 swake_up_one(&rcu_state.gp_wq);
1477 * If there is room, assign a ->gp_seq number to any callbacks on this
1478 * CPU that have not already been assigned. Also accelerate any callbacks
1479 * that were previously assigned a ->gp_seq number that has since proven
1480 * to be too conservative, which can happen if callbacks get assigned a
1481 * ->gp_seq number while RCU is idle, but with reference to a non-root
1482 * rcu_node structure. This function is idempotent, so it does not hurt
1483 * to call it repeatedly. Returns an flag saying that we should awaken
1484 * the RCU grace-period kthread.
1486 * The caller must hold rnp->lock with interrupts disabled.
1488 static bool rcu_accelerate_cbs(struct rcu_node *rnp, struct rcu_data *rdp)
1490 unsigned long gp_seq_req;
1493 rcu_lockdep_assert_cblist_protected(rdp);
1494 raw_lockdep_assert_held_rcu_node(rnp);
1496 /* If no pending (not yet ready to invoke) callbacks, nothing to do. */
1497 if (!rcu_segcblist_pend_cbs(&rdp->cblist))
1501 * Callbacks are often registered with incomplete grace-period
1502 * information. Something about the fact that getting exact
1503 * information requires acquiring a global lock... RCU therefore
1504 * makes a conservative estimate of the grace period number at which
1505 * a given callback will become ready to invoke. The following
1506 * code checks this estimate and improves it when possible, thus
1507 * accelerating callback invocation to an earlier grace-period
1510 gp_seq_req = rcu_seq_snap(&rcu_state.gp_seq);
1511 if (rcu_segcblist_accelerate(&rdp->cblist, gp_seq_req))
1512 ret = rcu_start_this_gp(rnp, rdp, gp_seq_req);
1514 /* Trace depending on how much we were able to accelerate. */
1515 if (rcu_segcblist_restempty(&rdp->cblist, RCU_WAIT_TAIL))
1516 trace_rcu_grace_period(rcu_state.name, gp_seq_req, TPS("AccWaitCB"));
1518 trace_rcu_grace_period(rcu_state.name, gp_seq_req, TPS("AccReadyCB"));
1524 * Similar to rcu_accelerate_cbs(), but does not require that the leaf
1525 * rcu_node structure's ->lock be held. It consults the cached value
1526 * of ->gp_seq_needed in the rcu_data structure, and if that indicates
1527 * that a new grace-period request be made, invokes rcu_accelerate_cbs()
1528 * while holding the leaf rcu_node structure's ->lock.
1530 static void rcu_accelerate_cbs_unlocked(struct rcu_node *rnp,
1531 struct rcu_data *rdp)
1536 rcu_lockdep_assert_cblist_protected(rdp);
1537 c = rcu_seq_snap(&rcu_state.gp_seq);
1538 if (!READ_ONCE(rdp->gpwrap) && ULONG_CMP_GE(rdp->gp_seq_needed, c)) {
1539 /* Old request still live, so mark recent callbacks. */
1540 (void)rcu_segcblist_accelerate(&rdp->cblist, c);
1543 raw_spin_lock_rcu_node(rnp); /* irqs already disabled. */
1544 needwake = rcu_accelerate_cbs(rnp, rdp);
1545 raw_spin_unlock_rcu_node(rnp); /* irqs remain disabled. */
1547 rcu_gp_kthread_wake();
1551 * Move any callbacks whose grace period has completed to the
1552 * RCU_DONE_TAIL sublist, then compact the remaining sublists and
1553 * assign ->gp_seq numbers to any callbacks in the RCU_NEXT_TAIL
1554 * sublist. This function is idempotent, so it does not hurt to
1555 * invoke it repeatedly. As long as it is not invoked -too- often...
1556 * Returns true if the RCU grace-period kthread needs to be awakened.
1558 * The caller must hold rnp->lock with interrupts disabled.
1560 static bool rcu_advance_cbs(struct rcu_node *rnp, struct rcu_data *rdp)
1562 rcu_lockdep_assert_cblist_protected(rdp);
1563 raw_lockdep_assert_held_rcu_node(rnp);
1565 /* If no pending (not yet ready to invoke) callbacks, nothing to do. */
1566 if (!rcu_segcblist_pend_cbs(&rdp->cblist))
1570 * Find all callbacks whose ->gp_seq numbers indicate that they
1571 * are ready to invoke, and put them into the RCU_DONE_TAIL sublist.
1573 rcu_segcblist_advance(&rdp->cblist, rnp->gp_seq);
1575 /* Classify any remaining callbacks. */
1576 return rcu_accelerate_cbs(rnp, rdp);
1580 * Move and classify callbacks, but only if doing so won't require
1581 * that the RCU grace-period kthread be awakened.
1583 static void __maybe_unused rcu_advance_cbs_nowake(struct rcu_node *rnp,
1584 struct rcu_data *rdp)
1586 rcu_lockdep_assert_cblist_protected(rdp);
1587 if (!rcu_seq_state(rcu_seq_current(&rnp->gp_seq)) ||
1588 !raw_spin_trylock_rcu_node(rnp))
1590 WARN_ON_ONCE(rcu_advance_cbs(rnp, rdp));
1591 raw_spin_unlock_rcu_node(rnp);
1595 * In CONFIG_RCU_STRICT_GRACE_PERIOD=y kernels, attempt to generate a
1596 * quiescent state. This is intended to be invoked when the CPU notices
1597 * a new grace period.
1599 static void rcu_strict_gp_check_qs(void)
1601 if (IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD)) {
1608 * Update CPU-local rcu_data state to record the beginnings and ends of
1609 * grace periods. The caller must hold the ->lock of the leaf rcu_node
1610 * structure corresponding to the current CPU, and must have irqs disabled.
1611 * Returns true if the grace-period kthread needs to be awakened.
1613 static bool __note_gp_changes(struct rcu_node *rnp, struct rcu_data *rdp)
1617 const bool offloaded = rcu_segcblist_is_offloaded(&rdp->cblist);
1619 raw_lockdep_assert_held_rcu_node(rnp);
1621 if (rdp->gp_seq == rnp->gp_seq)
1622 return false; /* Nothing to do. */
1624 /* Handle the ends of any preceding grace periods first. */
1625 if (rcu_seq_completed_gp(rdp->gp_seq, rnp->gp_seq) ||
1626 unlikely(READ_ONCE(rdp->gpwrap))) {
1628 ret = rcu_advance_cbs(rnp, rdp); /* Advance CBs. */
1629 rdp->core_needs_qs = false;
1630 trace_rcu_grace_period(rcu_state.name, rdp->gp_seq, TPS("cpuend"));
1633 ret = rcu_accelerate_cbs(rnp, rdp); /* Recent CBs. */
1634 if (rdp->core_needs_qs)
1635 rdp->core_needs_qs = !!(rnp->qsmask & rdp->grpmask);
1638 /* Now handle the beginnings of any new-to-this-CPU grace periods. */
1639 if (rcu_seq_new_gp(rdp->gp_seq, rnp->gp_seq) ||
1640 unlikely(READ_ONCE(rdp->gpwrap))) {
1642 * If the current grace period is waiting for this CPU,
1643 * set up to detect a quiescent state, otherwise don't
1644 * go looking for one.
1646 trace_rcu_grace_period(rcu_state.name, rnp->gp_seq, TPS("cpustart"));
1647 need_qs = !!(rnp->qsmask & rdp->grpmask);
1648 rdp->cpu_no_qs.b.norm = need_qs;
1649 rdp->core_needs_qs = need_qs;
1650 zero_cpu_stall_ticks(rdp);
1652 rdp->gp_seq = rnp->gp_seq; /* Remember new grace-period state. */
1653 if (ULONG_CMP_LT(rdp->gp_seq_needed, rnp->gp_seq_needed) || rdp->gpwrap)
1654 WRITE_ONCE(rdp->gp_seq_needed, rnp->gp_seq_needed);
1655 WRITE_ONCE(rdp->gpwrap, false);
1656 rcu_gpnum_ovf(rnp, rdp);
1660 static void note_gp_changes(struct rcu_data *rdp)
1662 unsigned long flags;
1664 struct rcu_node *rnp;
1666 local_irq_save(flags);
1668 if ((rdp->gp_seq == rcu_seq_current(&rnp->gp_seq) &&
1669 !unlikely(READ_ONCE(rdp->gpwrap))) || /* w/out lock. */
1670 !raw_spin_trylock_rcu_node(rnp)) { /* irqs already off, so later. */
1671 local_irq_restore(flags);
1674 needwake = __note_gp_changes(rnp, rdp);
1675 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1676 rcu_strict_gp_check_qs();
1678 rcu_gp_kthread_wake();
1681 static void rcu_gp_slow(int delay)
1684 !(rcu_seq_ctr(rcu_state.gp_seq) %
1685 (rcu_num_nodes * PER_RCU_NODE_PERIOD * delay)))
1686 schedule_timeout_idle(delay);
1689 static unsigned long sleep_duration;
1691 /* Allow rcutorture to stall the grace-period kthread. */
1692 void rcu_gp_set_torture_wait(int duration)
1694 if (IS_ENABLED(CONFIG_RCU_TORTURE_TEST) && duration > 0)
1695 WRITE_ONCE(sleep_duration, duration);
1697 EXPORT_SYMBOL_GPL(rcu_gp_set_torture_wait);
1699 /* Actually implement the aforementioned wait. */
1700 static void rcu_gp_torture_wait(void)
1702 unsigned long duration;
1704 if (!IS_ENABLED(CONFIG_RCU_TORTURE_TEST))
1706 duration = xchg(&sleep_duration, 0UL);
1708 pr_alert("%s: Waiting %lu jiffies\n", __func__, duration);
1709 schedule_timeout_idle(duration);
1710 pr_alert("%s: Wait complete\n", __func__);
1715 * Handler for on_each_cpu() to invoke the target CPU's RCU core
1718 static void rcu_strict_gp_boundary(void *unused)
1724 * Initialize a new grace period. Return false if no grace period required.
1726 static bool rcu_gp_init(void)
1728 unsigned long firstseq;
1729 unsigned long flags;
1730 unsigned long oldmask;
1732 struct rcu_data *rdp;
1733 struct rcu_node *rnp = rcu_get_root();
1735 WRITE_ONCE(rcu_state.gp_activity, jiffies);
1736 raw_spin_lock_irq_rcu_node(rnp);
1737 if (!READ_ONCE(rcu_state.gp_flags)) {
1738 /* Spurious wakeup, tell caller to go back to sleep. */
1739 raw_spin_unlock_irq_rcu_node(rnp);
1742 WRITE_ONCE(rcu_state.gp_flags, 0); /* Clear all flags: New GP. */
1744 if (WARN_ON_ONCE(rcu_gp_in_progress())) {
1746 * Grace period already in progress, don't start another.
1747 * Not supposed to be able to happen.
1749 raw_spin_unlock_irq_rcu_node(rnp);
1753 /* Advance to a new grace period and initialize state. */
1754 record_gp_stall_check_time();
1755 /* Record GP times before starting GP, hence rcu_seq_start(). */
1756 rcu_seq_start(&rcu_state.gp_seq);
1757 ASSERT_EXCLUSIVE_WRITER(rcu_state.gp_seq);
1758 trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq, TPS("start"));
1759 raw_spin_unlock_irq_rcu_node(rnp);
1762 * Apply per-leaf buffered online and offline operations to
1763 * the rcu_node tree. Note that this new grace period need not
1764 * wait for subsequent online CPUs, and that RCU hooks in the CPU
1765 * offlining path, when combined with checks in this function,
1766 * will handle CPUs that are currently going offline or that will
1767 * go offline later. Please also refer to "Hotplug CPU" section
1768 * of RCU's Requirements documentation.
1770 rcu_state.gp_state = RCU_GP_ONOFF;
1771 rcu_for_each_leaf_node(rnp) {
1772 smp_mb(); // Pair with barriers used when updating ->ofl_seq to odd values.
1773 firstseq = READ_ONCE(rnp->ofl_seq);
1775 while (firstseq == READ_ONCE(rnp->ofl_seq))
1776 schedule_timeout_idle(1); // Can't wake unless RCU is watching.
1777 smp_mb(); // Pair with barriers used when updating ->ofl_seq to even values.
1778 raw_spin_lock(&rcu_state.ofl_lock);
1779 raw_spin_lock_irq_rcu_node(rnp);
1780 if (rnp->qsmaskinit == rnp->qsmaskinitnext &&
1781 !rnp->wait_blkd_tasks) {
1782 /* Nothing to do on this leaf rcu_node structure. */
1783 raw_spin_unlock_irq_rcu_node(rnp);
1784 raw_spin_unlock(&rcu_state.ofl_lock);
1788 /* Record old state, apply changes to ->qsmaskinit field. */
1789 oldmask = rnp->qsmaskinit;
1790 rnp->qsmaskinit = rnp->qsmaskinitnext;
1792 /* If zero-ness of ->qsmaskinit changed, propagate up tree. */
1793 if (!oldmask != !rnp->qsmaskinit) {
1794 if (!oldmask) { /* First online CPU for rcu_node. */
1795 if (!rnp->wait_blkd_tasks) /* Ever offline? */
1796 rcu_init_new_rnp(rnp);
1797 } else if (rcu_preempt_has_tasks(rnp)) {
1798 rnp->wait_blkd_tasks = true; /* blocked tasks */
1799 } else { /* Last offline CPU and can propagate. */
1800 rcu_cleanup_dead_rnp(rnp);
1805 * If all waited-on tasks from prior grace period are
1806 * done, and if all this rcu_node structure's CPUs are
1807 * still offline, propagate up the rcu_node tree and
1808 * clear ->wait_blkd_tasks. Otherwise, if one of this
1809 * rcu_node structure's CPUs has since come back online,
1810 * simply clear ->wait_blkd_tasks.
1812 if (rnp->wait_blkd_tasks &&
1813 (!rcu_preempt_has_tasks(rnp) || rnp->qsmaskinit)) {
1814 rnp->wait_blkd_tasks = false;
1815 if (!rnp->qsmaskinit)
1816 rcu_cleanup_dead_rnp(rnp);
1819 raw_spin_unlock_irq_rcu_node(rnp);
1820 raw_spin_unlock(&rcu_state.ofl_lock);
1822 rcu_gp_slow(gp_preinit_delay); /* Races with CPU hotplug. */
1825 * Set the quiescent-state-needed bits in all the rcu_node
1826 * structures for all currently online CPUs in breadth-first
1827 * order, starting from the root rcu_node structure, relying on the
1828 * layout of the tree within the rcu_state.node[] array. Note that
1829 * other CPUs will access only the leaves of the hierarchy, thus
1830 * seeing that no grace period is in progress, at least until the
1831 * corresponding leaf node has been initialized.
1833 * The grace period cannot complete until the initialization
1834 * process finishes, because this kthread handles both.
1836 rcu_state.gp_state = RCU_GP_INIT;
1837 rcu_for_each_node_breadth_first(rnp) {
1838 rcu_gp_slow(gp_init_delay);
1839 raw_spin_lock_irqsave_rcu_node(rnp, flags);
1840 rdp = this_cpu_ptr(&rcu_data);
1841 rcu_preempt_check_blocked_tasks(rnp);
1842 rnp->qsmask = rnp->qsmaskinit;
1843 WRITE_ONCE(rnp->gp_seq, rcu_state.gp_seq);
1844 if (rnp == rdp->mynode)
1845 (void)__note_gp_changes(rnp, rdp);
1846 rcu_preempt_boost_start_gp(rnp);
1847 trace_rcu_grace_period_init(rcu_state.name, rnp->gp_seq,
1848 rnp->level, rnp->grplo,
1849 rnp->grphi, rnp->qsmask);
1850 /* Quiescent states for tasks on any now-offline CPUs. */
1851 mask = rnp->qsmask & ~rnp->qsmaskinitnext;
1852 rnp->rcu_gp_init_mask = mask;
1853 if ((mask || rnp->wait_blkd_tasks) && rcu_is_leaf_node(rnp))
1854 rcu_report_qs_rnp(mask, rnp, rnp->gp_seq, flags);
1856 raw_spin_unlock_irq_rcu_node(rnp);
1857 cond_resched_tasks_rcu_qs();
1858 WRITE_ONCE(rcu_state.gp_activity, jiffies);
1861 // If strict, make all CPUs aware of new grace period.
1862 if (IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD))
1863 on_each_cpu(rcu_strict_gp_boundary, NULL, 0);
1869 * Helper function for swait_event_idle_exclusive() wakeup at force-quiescent-state
1872 static bool rcu_gp_fqs_check_wake(int *gfp)
1874 struct rcu_node *rnp = rcu_get_root();
1876 // If under overload conditions, force an immediate FQS scan.
1877 if (*gfp & RCU_GP_FLAG_OVLD)
1880 // Someone like call_rcu() requested a force-quiescent-state scan.
1881 *gfp = READ_ONCE(rcu_state.gp_flags);
1882 if (*gfp & RCU_GP_FLAG_FQS)
1885 // The current grace period has completed.
1886 if (!READ_ONCE(rnp->qsmask) && !rcu_preempt_blocked_readers_cgp(rnp))
1893 * Do one round of quiescent-state forcing.
1895 static void rcu_gp_fqs(bool first_time)
1897 struct rcu_node *rnp = rcu_get_root();
1899 WRITE_ONCE(rcu_state.gp_activity, jiffies);
1900 rcu_state.n_force_qs++;
1902 /* Collect dyntick-idle snapshots. */
1903 force_qs_rnp(dyntick_save_progress_counter);
1905 /* Handle dyntick-idle and offline CPUs. */
1906 force_qs_rnp(rcu_implicit_dynticks_qs);
1908 /* Clear flag to prevent immediate re-entry. */
1909 if (READ_ONCE(rcu_state.gp_flags) & RCU_GP_FLAG_FQS) {
1910 raw_spin_lock_irq_rcu_node(rnp);
1911 WRITE_ONCE(rcu_state.gp_flags,
1912 READ_ONCE(rcu_state.gp_flags) & ~RCU_GP_FLAG_FQS);
1913 raw_spin_unlock_irq_rcu_node(rnp);
1918 * Loop doing repeated quiescent-state forcing until the grace period ends.
1920 static void rcu_gp_fqs_loop(void)
1926 struct rcu_node *rnp = rcu_get_root();
1928 first_gp_fqs = true;
1929 j = READ_ONCE(jiffies_till_first_fqs);
1930 if (rcu_state.cbovld)
1931 gf = RCU_GP_FLAG_OVLD;
1935 rcu_state.jiffies_force_qs = jiffies + j;
1936 WRITE_ONCE(rcu_state.jiffies_kick_kthreads,
1937 jiffies + (j ? 3 * j : 2));
1939 trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
1941 rcu_state.gp_state = RCU_GP_WAIT_FQS;
1942 ret = swait_event_idle_timeout_exclusive(
1943 rcu_state.gp_wq, rcu_gp_fqs_check_wake(&gf), j);
1944 rcu_gp_torture_wait();
1945 rcu_state.gp_state = RCU_GP_DOING_FQS;
1946 /* Locking provides needed memory barriers. */
1947 /* If grace period done, leave loop. */
1948 if (!READ_ONCE(rnp->qsmask) &&
1949 !rcu_preempt_blocked_readers_cgp(rnp))
1951 /* If time for quiescent-state forcing, do it. */
1952 if (!time_after(rcu_state.jiffies_force_qs, jiffies) ||
1953 (gf & (RCU_GP_FLAG_FQS | RCU_GP_FLAG_OVLD))) {
1954 trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
1956 rcu_gp_fqs(first_gp_fqs);
1959 first_gp_fqs = false;
1960 gf = rcu_state.cbovld ? RCU_GP_FLAG_OVLD : 0;
1962 trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
1964 cond_resched_tasks_rcu_qs();
1965 WRITE_ONCE(rcu_state.gp_activity, jiffies);
1966 ret = 0; /* Force full wait till next FQS. */
1967 j = READ_ONCE(jiffies_till_next_fqs);
1969 /* Deal with stray signal. */
1970 cond_resched_tasks_rcu_qs();
1971 WRITE_ONCE(rcu_state.gp_activity, jiffies);
1972 WARN_ON(signal_pending(current));
1973 trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
1975 ret = 1; /* Keep old FQS timing. */
1977 if (time_after(jiffies, rcu_state.jiffies_force_qs))
1980 j = rcu_state.jiffies_force_qs - j;
1987 * Clean up after the old grace period.
1989 static void rcu_gp_cleanup(void)
1992 bool needgp = false;
1993 unsigned long gp_duration;
1994 unsigned long new_gp_seq;
1996 struct rcu_data *rdp;
1997 struct rcu_node *rnp = rcu_get_root();
1998 struct swait_queue_head *sq;
2000 WRITE_ONCE(rcu_state.gp_activity, jiffies);
2001 raw_spin_lock_irq_rcu_node(rnp);
2002 rcu_state.gp_end = jiffies;
2003 gp_duration = rcu_state.gp_end - rcu_state.gp_start;
2004 if (gp_duration > rcu_state.gp_max)
2005 rcu_state.gp_max = gp_duration;
2008 * We know the grace period is complete, but to everyone else
2009 * it appears to still be ongoing. But it is also the case
2010 * that to everyone else it looks like there is nothing that
2011 * they can do to advance the grace period. It is therefore
2012 * safe for us to drop the lock in order to mark the grace
2013 * period as completed in all of the rcu_node structures.
2015 raw_spin_unlock_irq_rcu_node(rnp);
2018 * Propagate new ->gp_seq value to rcu_node structures so that
2019 * other CPUs don't have to wait until the start of the next grace
2020 * period to process their callbacks. This also avoids some nasty
2021 * RCU grace-period initialization races by forcing the end of
2022 * the current grace period to be completely recorded in all of
2023 * the rcu_node structures before the beginning of the next grace
2024 * period is recorded in any of the rcu_node structures.
2026 new_gp_seq = rcu_state.gp_seq;
2027 rcu_seq_end(&new_gp_seq);
2028 rcu_for_each_node_breadth_first(rnp) {
2029 raw_spin_lock_irq_rcu_node(rnp);
2030 if (WARN_ON_ONCE(rcu_preempt_blocked_readers_cgp(rnp)))
2031 dump_blkd_tasks(rnp, 10);
2032 WARN_ON_ONCE(rnp->qsmask);
2033 WRITE_ONCE(rnp->gp_seq, new_gp_seq);
2034 rdp = this_cpu_ptr(&rcu_data);
2035 if (rnp == rdp->mynode)
2036 needgp = __note_gp_changes(rnp, rdp) || needgp;
2037 /* smp_mb() provided by prior unlock-lock pair. */
2038 needgp = rcu_future_gp_cleanup(rnp) || needgp;
2039 // Reset overload indication for CPUs no longer overloaded
2040 if (rcu_is_leaf_node(rnp))
2041 for_each_leaf_node_cpu_mask(rnp, cpu, rnp->cbovldmask) {
2042 rdp = per_cpu_ptr(&rcu_data, cpu);
2043 check_cb_ovld_locked(rdp, rnp);
2045 sq = rcu_nocb_gp_get(rnp);
2046 raw_spin_unlock_irq_rcu_node(rnp);
2047 rcu_nocb_gp_cleanup(sq);
2048 cond_resched_tasks_rcu_qs();
2049 WRITE_ONCE(rcu_state.gp_activity, jiffies);
2050 rcu_gp_slow(gp_cleanup_delay);
2052 rnp = rcu_get_root();
2053 raw_spin_lock_irq_rcu_node(rnp); /* GP before ->gp_seq update. */
2055 /* Declare grace period done, trace first to use old GP number. */
2056 trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq, TPS("end"));
2057 rcu_seq_end(&rcu_state.gp_seq);
2058 ASSERT_EXCLUSIVE_WRITER(rcu_state.gp_seq);
2059 rcu_state.gp_state = RCU_GP_IDLE;
2060 /* Check for GP requests since above loop. */
2061 rdp = this_cpu_ptr(&rcu_data);
2062 if (!needgp && ULONG_CMP_LT(rnp->gp_seq, rnp->gp_seq_needed)) {
2063 trace_rcu_this_gp(rnp, rdp, rnp->gp_seq_needed,
2064 TPS("CleanupMore"));
2067 /* Advance CBs to reduce false positives below. */
2068 offloaded = rcu_segcblist_is_offloaded(&rdp->cblist);
2069 if ((offloaded || !rcu_accelerate_cbs(rnp, rdp)) && needgp) {
2070 WRITE_ONCE(rcu_state.gp_flags, RCU_GP_FLAG_INIT);
2071 WRITE_ONCE(rcu_state.gp_req_activity, jiffies);
2072 trace_rcu_grace_period(rcu_state.name,
2076 WRITE_ONCE(rcu_state.gp_flags,
2077 rcu_state.gp_flags & RCU_GP_FLAG_INIT);
2079 raw_spin_unlock_irq_rcu_node(rnp);
2081 // If strict, make all CPUs aware of the end of the old grace period.
2082 if (IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD))
2083 on_each_cpu(rcu_strict_gp_boundary, NULL, 0);
2087 * Body of kthread that handles grace periods.
2089 static int __noreturn rcu_gp_kthread(void *unused)
2091 rcu_bind_gp_kthread();
2094 /* Handle grace-period start. */
2096 trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
2098 rcu_state.gp_state = RCU_GP_WAIT_GPS;
2099 swait_event_idle_exclusive(rcu_state.gp_wq,
2100 READ_ONCE(rcu_state.gp_flags) &
2102 rcu_gp_torture_wait();
2103 rcu_state.gp_state = RCU_GP_DONE_GPS;
2104 /* Locking provides needed memory barrier. */
2107 cond_resched_tasks_rcu_qs();
2108 WRITE_ONCE(rcu_state.gp_activity, jiffies);
2109 WARN_ON(signal_pending(current));
2110 trace_rcu_grace_period(rcu_state.name, rcu_state.gp_seq,
2114 /* Handle quiescent-state forcing. */
2117 /* Handle grace-period end. */
2118 rcu_state.gp_state = RCU_GP_CLEANUP;
2120 rcu_state.gp_state = RCU_GP_CLEANED;
2125 * Report a full set of quiescent states to the rcu_state data structure.
2126 * Invoke rcu_gp_kthread_wake() to awaken the grace-period kthread if
2127 * another grace period is required. Whether we wake the grace-period
2128 * kthread or it awakens itself for the next round of quiescent-state
2129 * forcing, that kthread will clean up after the just-completed grace
2130 * period. Note that the caller must hold rnp->lock, which is released
2133 static void rcu_report_qs_rsp(unsigned long flags)
2134 __releases(rcu_get_root()->lock)
2136 raw_lockdep_assert_held_rcu_node(rcu_get_root());
2137 WARN_ON_ONCE(!rcu_gp_in_progress());
2138 WRITE_ONCE(rcu_state.gp_flags,
2139 READ_ONCE(rcu_state.gp_flags) | RCU_GP_FLAG_FQS);
2140 raw_spin_unlock_irqrestore_rcu_node(rcu_get_root(), flags);
2141 rcu_gp_kthread_wake();
2145 * Similar to rcu_report_qs_rdp(), for which it is a helper function.
2146 * Allows quiescent states for a group of CPUs to be reported at one go
2147 * to the specified rcu_node structure, though all the CPUs in the group
2148 * must be represented by the same rcu_node structure (which need not be a
2149 * leaf rcu_node structure, though it often will be). The gps parameter
2150 * is the grace-period snapshot, which means that the quiescent states
2151 * are valid only if rnp->gp_seq is equal to gps. That structure's lock
2152 * must be held upon entry, and it is released before return.
2154 * As a special case, if mask is zero, the bit-already-cleared check is
2155 * disabled. This allows propagating quiescent state due to resumed tasks
2156 * during grace-period initialization.
2158 static void rcu_report_qs_rnp(unsigned long mask, struct rcu_node *rnp,
2159 unsigned long gps, unsigned long flags)
2160 __releases(rnp->lock)
2162 unsigned long oldmask = 0;
2163 struct rcu_node *rnp_c;
2165 raw_lockdep_assert_held_rcu_node(rnp);
2167 /* Walk up the rcu_node hierarchy. */
2169 if ((!(rnp->qsmask & mask) && mask) || rnp->gp_seq != gps) {
2172 * Our bit has already been cleared, or the
2173 * relevant grace period is already over, so done.
2175 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2178 WARN_ON_ONCE(oldmask); /* Any child must be all zeroed! */
2179 WARN_ON_ONCE(!rcu_is_leaf_node(rnp) &&
2180 rcu_preempt_blocked_readers_cgp(rnp));
2181 WRITE_ONCE(rnp->qsmask, rnp->qsmask & ~mask);
2182 trace_rcu_quiescent_state_report(rcu_state.name, rnp->gp_seq,
2183 mask, rnp->qsmask, rnp->level,
2184 rnp->grplo, rnp->grphi,
2186 if (rnp->qsmask != 0 || rcu_preempt_blocked_readers_cgp(rnp)) {
2188 /* Other bits still set at this level, so done. */
2189 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2192 rnp->completedqs = rnp->gp_seq;
2193 mask = rnp->grpmask;
2194 if (rnp->parent == NULL) {
2196 /* No more levels. Exit loop holding root lock. */
2200 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2203 raw_spin_lock_irqsave_rcu_node(rnp, flags);
2204 oldmask = READ_ONCE(rnp_c->qsmask);
2208 * Get here if we are the last CPU to pass through a quiescent
2209 * state for this grace period. Invoke rcu_report_qs_rsp()
2210 * to clean up and start the next grace period if one is needed.
2212 rcu_report_qs_rsp(flags); /* releases rnp->lock. */
2216 * Record a quiescent state for all tasks that were previously queued
2217 * on the specified rcu_node structure and that were blocking the current
2218 * RCU grace period. The caller must hold the corresponding rnp->lock with
2219 * irqs disabled, and this lock is released upon return, but irqs remain
2222 static void __maybe_unused
2223 rcu_report_unblock_qs_rnp(struct rcu_node *rnp, unsigned long flags)
2224 __releases(rnp->lock)
2228 struct rcu_node *rnp_p;
2230 raw_lockdep_assert_held_rcu_node(rnp);
2231 if (WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT_RCU)) ||
2232 WARN_ON_ONCE(rcu_preempt_blocked_readers_cgp(rnp)) ||
2234 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2235 return; /* Still need more quiescent states! */
2238 rnp->completedqs = rnp->gp_seq;
2239 rnp_p = rnp->parent;
2240 if (rnp_p == NULL) {
2242 * Only one rcu_node structure in the tree, so don't
2243 * try to report up to its nonexistent parent!
2245 rcu_report_qs_rsp(flags);
2249 /* Report up the rest of the hierarchy, tracking current ->gp_seq. */
2251 mask = rnp->grpmask;
2252 raw_spin_unlock_rcu_node(rnp); /* irqs remain disabled. */
2253 raw_spin_lock_rcu_node(rnp_p); /* irqs already disabled. */
2254 rcu_report_qs_rnp(mask, rnp_p, gps, flags);
2258 * Record a quiescent state for the specified CPU to that CPU's rcu_data
2259 * structure. This must be called from the specified CPU.
2262 rcu_report_qs_rdp(struct rcu_data *rdp)
2264 unsigned long flags;
2266 bool needwake = false;
2267 const bool offloaded = rcu_segcblist_is_offloaded(&rdp->cblist);
2268 struct rcu_node *rnp;
2270 WARN_ON_ONCE(rdp->cpu != smp_processor_id());
2272 raw_spin_lock_irqsave_rcu_node(rnp, flags);
2273 if (rdp->cpu_no_qs.b.norm || rdp->gp_seq != rnp->gp_seq ||
2277 * The grace period in which this quiescent state was
2278 * recorded has ended, so don't report it upwards.
2279 * We will instead need a new quiescent state that lies
2280 * within the current grace period.
2282 rdp->cpu_no_qs.b.norm = true; /* need qs for new gp. */
2283 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2286 mask = rdp->grpmask;
2287 rdp->core_needs_qs = false;
2288 if ((rnp->qsmask & mask) == 0) {
2289 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2292 * This GP can't end until cpu checks in, so all of our
2293 * callbacks can be processed during the next GP.
2296 needwake = rcu_accelerate_cbs(rnp, rdp);
2298 rcu_disable_urgency_upon_qs(rdp);
2299 rcu_report_qs_rnp(mask, rnp, rnp->gp_seq, flags);
2300 /* ^^^ Released rnp->lock */
2302 rcu_gp_kthread_wake();
2307 * Check to see if there is a new grace period of which this CPU
2308 * is not yet aware, and if so, set up local rcu_data state for it.
2309 * Otherwise, see if this CPU has just passed through its first
2310 * quiescent state for this grace period, and record that fact if so.
2313 rcu_check_quiescent_state(struct rcu_data *rdp)
2315 /* Check for grace-period ends and beginnings. */
2316 note_gp_changes(rdp);
2319 * Does this CPU still need to do its part for current grace period?
2320 * If no, return and let the other CPUs do their part as well.
2322 if (!rdp->core_needs_qs)
2326 * Was there a quiescent state since the beginning of the grace
2327 * period? If no, then exit and wait for the next call.
2329 if (rdp->cpu_no_qs.b.norm)
2333 * Tell RCU we are done (but rcu_report_qs_rdp() will be the
2336 rcu_report_qs_rdp(rdp);
2340 * Near the end of the offline process. Trace the fact that this CPU
2343 int rcutree_dying_cpu(unsigned int cpu)
2346 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
2347 struct rcu_node *rnp = rdp->mynode;
2349 if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))
2352 blkd = !!(rnp->qsmask & rdp->grpmask);
2353 trace_rcu_grace_period(rcu_state.name, READ_ONCE(rnp->gp_seq),
2354 blkd ? TPS("cpuofl") : TPS("cpuofl-bgp"));
2359 * All CPUs for the specified rcu_node structure have gone offline,
2360 * and all tasks that were preempted within an RCU read-side critical
2361 * section while running on one of those CPUs have since exited their RCU
2362 * read-side critical section. Some other CPU is reporting this fact with
2363 * the specified rcu_node structure's ->lock held and interrupts disabled.
2364 * This function therefore goes up the tree of rcu_node structures,
2365 * clearing the corresponding bits in the ->qsmaskinit fields. Note that
2366 * the leaf rcu_node structure's ->qsmaskinit field has already been
2369 * This function does check that the specified rcu_node structure has
2370 * all CPUs offline and no blocked tasks, so it is OK to invoke it
2371 * prematurely. That said, invoking it after the fact will cost you
2372 * a needless lock acquisition. So once it has done its work, don't
2375 static void rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf)
2378 struct rcu_node *rnp = rnp_leaf;
2380 raw_lockdep_assert_held_rcu_node(rnp_leaf);
2381 if (!IS_ENABLED(CONFIG_HOTPLUG_CPU) ||
2382 WARN_ON_ONCE(rnp_leaf->qsmaskinit) ||
2383 WARN_ON_ONCE(rcu_preempt_has_tasks(rnp_leaf)))
2386 mask = rnp->grpmask;
2390 raw_spin_lock_rcu_node(rnp); /* irqs already disabled. */
2391 rnp->qsmaskinit &= ~mask;
2392 /* Between grace periods, so better already be zero! */
2393 WARN_ON_ONCE(rnp->qsmask);
2394 if (rnp->qsmaskinit) {
2395 raw_spin_unlock_rcu_node(rnp);
2396 /* irqs remain disabled. */
2399 raw_spin_unlock_rcu_node(rnp); /* irqs remain disabled. */
2404 * The CPU has been completely removed, and some other CPU is reporting
2405 * this fact from process context. Do the remainder of the cleanup.
2406 * There can only be one CPU hotplug operation at a time, so no need for
2409 int rcutree_dead_cpu(unsigned int cpu)
2411 struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
2412 struct rcu_node *rnp = rdp->mynode; /* Outgoing CPU's rdp & rnp. */
2414 if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))
2417 WRITE_ONCE(rcu_state.n_online_cpus, rcu_state.n_online_cpus - 1);
2418 /* Adjust any no-longer-needed kthreads. */
2419 rcu_boost_kthread_setaffinity(rnp, -1);
2420 /* Do any needed no-CB deferred wakeups from this CPU. */
2421 do_nocb_deferred_wakeup(per_cpu_ptr(&rcu_data, cpu));
2423 // Stop-machine done, so allow nohz_full to disable tick.
2424 tick_dep_clear(TICK_DEP_BIT_RCU);
2429 * Invoke any RCU callbacks that have made it to the end of their grace
2430 * period. Thottle as specified by rdp->blimit.
2432 static void rcu_do_batch(struct rcu_data *rdp)
2435 unsigned long flags;
2436 const bool offloaded = rcu_segcblist_is_offloaded(&rdp->cblist);
2437 struct rcu_head *rhp;
2438 struct rcu_cblist rcl = RCU_CBLIST_INITIALIZER(rcl);
2440 long pending, tlimit = 0;
2442 /* If no callbacks are ready, just return. */
2443 if (!rcu_segcblist_ready_cbs(&rdp->cblist)) {
2444 trace_rcu_batch_start(rcu_state.name,
2445 rcu_segcblist_n_cbs(&rdp->cblist), 0);
2446 trace_rcu_batch_end(rcu_state.name, 0,
2447 !rcu_segcblist_empty(&rdp->cblist),
2448 need_resched(), is_idle_task(current),
2449 rcu_is_callbacks_kthread());
2454 * Extract the list of ready callbacks, disabling to prevent
2455 * races with call_rcu() from interrupt handlers. Leave the
2456 * callback counts, as rcu_barrier() needs to be conservative.
2458 local_irq_save(flags);
2460 WARN_ON_ONCE(cpu_is_offline(smp_processor_id()));
2461 pending = rcu_segcblist_n_cbs(&rdp->cblist);
2462 div = READ_ONCE(rcu_divisor);
2463 div = div < 0 ? 7 : div > sizeof(long) * 8 - 2 ? sizeof(long) * 8 - 2 : div;
2464 bl = max(rdp->blimit, pending >> div);
2465 if (unlikely(bl > 100)) {
2466 long rrn = READ_ONCE(rcu_resched_ns);
2468 rrn = rrn < NSEC_PER_MSEC ? NSEC_PER_MSEC : rrn > NSEC_PER_SEC ? NSEC_PER_SEC : rrn;
2469 tlimit = local_clock() + rrn;
2471 trace_rcu_batch_start(rcu_state.name,
2472 rcu_segcblist_n_cbs(&rdp->cblist), bl);
2473 rcu_segcblist_extract_done_cbs(&rdp->cblist, &rcl);
2475 rdp->qlen_last_fqs_check = rcu_segcblist_n_cbs(&rdp->cblist);
2476 rcu_nocb_unlock_irqrestore(rdp, flags);
2478 /* Invoke callbacks. */
2479 tick_dep_set_task(current, TICK_DEP_BIT_RCU);
2480 rhp = rcu_cblist_dequeue(&rcl);
2481 for (; rhp; rhp = rcu_cblist_dequeue(&rcl)) {
2484 debug_rcu_head_unqueue(rhp);
2486 rcu_lock_acquire(&rcu_callback_map);
2487 trace_rcu_invoke_callback(rcu_state.name, rhp);
2490 WRITE_ONCE(rhp->func, (rcu_callback_t)0L);
2493 rcu_lock_release(&rcu_callback_map);
2496 * Stop only if limit reached and CPU has something to do.
2497 * Note: The rcl structure counts down from zero.
2499 if (-rcl.len >= bl && !offloaded &&
2501 (!is_idle_task(current) && !rcu_is_callbacks_kthread())))
2503 if (unlikely(tlimit)) {
2504 /* only call local_clock() every 32 callbacks */
2505 if (likely((-rcl.len & 31) || local_clock() < tlimit))
2507 /* Exceeded the time limit, so leave. */
2511 WARN_ON_ONCE(in_serving_softirq());
2513 lockdep_assert_irqs_enabled();
2514 cond_resched_tasks_rcu_qs();
2515 lockdep_assert_irqs_enabled();
2520 local_irq_save(flags);
2523 rdp->n_cbs_invoked += count;
2524 trace_rcu_batch_end(rcu_state.name, count, !!rcl.head, need_resched(),
2525 is_idle_task(current), rcu_is_callbacks_kthread());
2527 /* Update counts and requeue any remaining callbacks. */
2528 rcu_segcblist_insert_done_cbs(&rdp->cblist, &rcl);
2529 smp_mb(); /* List handling before counting for rcu_barrier(). */
2530 rcu_segcblist_insert_count(&rdp->cblist, &rcl);
2532 /* Reinstate batch limit if we have worked down the excess. */
2533 count = rcu_segcblist_n_cbs(&rdp->cblist);
2534 if (rdp->blimit >= DEFAULT_MAX_RCU_BLIMIT && count <= qlowmark)
2535 rdp->blimit = blimit;
2537 /* Reset ->qlen_last_fqs_check trigger if enough CBs have drained. */
2538 if (count == 0 && rdp->qlen_last_fqs_check != 0) {
2539 rdp->qlen_last_fqs_check = 0;
2540 rdp->n_force_qs_snap = rcu_state.n_force_qs;
2541 } else if (count < rdp->qlen_last_fqs_check - qhimark)
2542 rdp->qlen_last_fqs_check = count;
2545 * The following usually indicates a double call_rcu(). To track
2546 * this down, try building with CONFIG_DEBUG_OBJECTS_RCU_HEAD=y.
2548 WARN_ON_ONCE(count == 0 && !rcu_segcblist_empty(&rdp->cblist));
2549 WARN_ON_ONCE(!IS_ENABLED(CONFIG_RCU_NOCB_CPU) &&
2550 count != 0 && rcu_segcblist_empty(&rdp->cblist));
2552 rcu_nocb_unlock_irqrestore(rdp, flags);
2554 /* Re-invoke RCU core processing if there are callbacks remaining. */
2555 if (!offloaded && rcu_segcblist_ready_cbs(&rdp->cblist))
2557 tick_dep_clear_task(current, TICK_DEP_BIT_RCU);
2561 * This function is invoked from each scheduling-clock interrupt,
2562 * and checks to see if this CPU is in a non-context-switch quiescent
2563 * state, for example, user mode or idle loop. It also schedules RCU
2564 * core processing. If the current grace period has gone on too long,
2565 * it will ask the scheduler to manufacture a context switch for the sole
2566 * purpose of providing a providing the needed quiescent state.
2568 void rcu_sched_clock_irq(int user)
2570 trace_rcu_utilization(TPS("Start scheduler-tick"));
2571 raw_cpu_inc(rcu_data.ticks_this_gp);
2572 /* The load-acquire pairs with the store-release setting to true. */
2573 if (smp_load_acquire(this_cpu_ptr(&rcu_data.rcu_urgent_qs))) {
2574 /* Idle and userspace execution already are quiescent states. */
2575 if (!rcu_is_cpu_rrupt_from_idle() && !user) {
2576 set_tsk_need_resched(current);
2577 set_preempt_need_resched();
2579 __this_cpu_write(rcu_data.rcu_urgent_qs, false);
2581 rcu_flavor_sched_clock_irq(user);
2582 if (rcu_pending(user))
2585 trace_rcu_utilization(TPS("End scheduler-tick"));
2589 * Scan the leaf rcu_node structures. For each structure on which all
2590 * CPUs have reported a quiescent state and on which there are tasks
2591 * blocking the current grace period, initiate RCU priority boosting.
2592 * Otherwise, invoke the specified function to check dyntick state for
2593 * each CPU that has not yet reported a quiescent state.
2595 static void force_qs_rnp(int (*f)(struct rcu_data *rdp))
2598 unsigned long flags;
2600 struct rcu_data *rdp;
2601 struct rcu_node *rnp;
2603 rcu_state.cbovld = rcu_state.cbovldnext;
2604 rcu_state.cbovldnext = false;
2605 rcu_for_each_leaf_node(rnp) {
2606 cond_resched_tasks_rcu_qs();
2608 raw_spin_lock_irqsave_rcu_node(rnp, flags);
2609 rcu_state.cbovldnext |= !!rnp->cbovldmask;
2610 if (rnp->qsmask == 0) {
2611 if (rcu_preempt_blocked_readers_cgp(rnp)) {
2613 * No point in scanning bits because they
2614 * are all zero. But we might need to
2615 * priority-boost blocked readers.
2617 rcu_initiate_boost(rnp, flags);
2618 /* rcu_initiate_boost() releases rnp->lock */
2621 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2624 for_each_leaf_node_cpu_mask(rnp, cpu, rnp->qsmask) {
2625 rdp = per_cpu_ptr(&rcu_data, cpu);
2627 mask |= rdp->grpmask;
2628 rcu_disable_urgency_upon_qs(rdp);
2632 /* Idle/offline CPUs, report (releases rnp->lock). */
2633 rcu_report_qs_rnp(mask, rnp, rnp->gp_seq, flags);
2635 /* Nothing to do here, so just drop the lock. */
2636 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2642 * Force quiescent states on reluctant CPUs, and also detect which
2643 * CPUs are in dyntick-idle mode.
2645 void rcu_force_quiescent_state(void)
2647 unsigned long flags;
2649 struct rcu_node *rnp;
2650 struct rcu_node *rnp_old = NULL;
2652 /* Funnel through hierarchy to reduce memory contention. */
2653 rnp = __this_cpu_read(rcu_data.mynode);
2654 for (; rnp != NULL; rnp = rnp->parent) {
2655 ret = (READ_ONCE(rcu_state.gp_flags) & RCU_GP_FLAG_FQS) ||
2656 !raw_spin_trylock(&rnp->fqslock);
2657 if (rnp_old != NULL)
2658 raw_spin_unlock(&rnp_old->fqslock);
2663 /* rnp_old == rcu_get_root(), rnp == NULL. */
2665 /* Reached the root of the rcu_node tree, acquire lock. */
2666 raw_spin_lock_irqsave_rcu_node(rnp_old, flags);
2667 raw_spin_unlock(&rnp_old->fqslock);
2668 if (READ_ONCE(rcu_state.gp_flags) & RCU_GP_FLAG_FQS) {
2669 raw_spin_unlock_irqrestore_rcu_node(rnp_old, flags);
2670 return; /* Someone beat us to it. */
2672 WRITE_ONCE(rcu_state.gp_flags,
2673 READ_ONCE(rcu_state.gp_flags) | RCU_GP_FLAG_FQS);
2674 raw_spin_unlock_irqrestore_rcu_node(rnp_old, flags);
2675 rcu_gp_kthread_wake();
2677 EXPORT_SYMBOL_GPL(rcu_force_quiescent_state);
2679 // Workqueue handler for an RCU reader for kernels enforcing struct RCU
2681 static void strict_work_handler(struct work_struct *work)
2687 /* Perform RCU core processing work for the current CPU. */
2688 static __latent_entropy void rcu_core(void)
2690 unsigned long flags;
2691 struct rcu_data *rdp = raw_cpu_ptr(&rcu_data);
2692 struct rcu_node *rnp = rdp->mynode;
2693 const bool offloaded = rcu_segcblist_is_offloaded(&rdp->cblist);
2695 if (cpu_is_offline(smp_processor_id()))
2697 trace_rcu_utilization(TPS("Start RCU core"));
2698 WARN_ON_ONCE(!rdp->beenonline);
2700 /* Report any deferred quiescent states if preemption enabled. */
2701 if (!(preempt_count() & PREEMPT_MASK)) {
2702 rcu_preempt_deferred_qs(current);
2703 } else if (rcu_preempt_need_deferred_qs(current)) {
2704 set_tsk_need_resched(current);
2705 set_preempt_need_resched();
2708 /* Update RCU state based on any recent quiescent states. */
2709 rcu_check_quiescent_state(rdp);
2711 /* No grace period and unregistered callbacks? */
2712 if (!rcu_gp_in_progress() &&
2713 rcu_segcblist_is_enabled(&rdp->cblist) && !offloaded) {
2714 local_irq_save(flags);
2715 if (!rcu_segcblist_restempty(&rdp->cblist, RCU_NEXT_READY_TAIL))
2716 rcu_accelerate_cbs_unlocked(rnp, rdp);
2717 local_irq_restore(flags);
2720 rcu_check_gp_start_stall(rnp, rdp, rcu_jiffies_till_stall_check());
2722 /* If there are callbacks ready, invoke them. */
2723 if (!offloaded && rcu_segcblist_ready_cbs(&rdp->cblist) &&
2724 likely(READ_ONCE(rcu_scheduler_fully_active)))
2727 /* Do any needed deferred wakeups of rcuo kthreads. */
2728 do_nocb_deferred_wakeup(rdp);
2729 trace_rcu_utilization(TPS("End RCU core"));
2731 // If strict GPs, schedule an RCU reader in a clean environment.
2732 if (IS_ENABLED(CONFIG_RCU_STRICT_GRACE_PERIOD))
2733 queue_work_on(rdp->cpu, rcu_gp_wq, &rdp->strict_work);
2736 static void rcu_core_si(struct softirq_action *h)
2741 static void rcu_wake_cond(struct task_struct *t, int status)
2744 * If the thread is yielding, only wake it when this
2745 * is invoked from idle
2747 if (t && (status != RCU_KTHREAD_YIELDING || is_idle_task(current)))
2751 static void invoke_rcu_core_kthread(void)
2753 struct task_struct *t;
2754 unsigned long flags;
2756 local_irq_save(flags);
2757 __this_cpu_write(rcu_data.rcu_cpu_has_work, 1);
2758 t = __this_cpu_read(rcu_data.rcu_cpu_kthread_task);
2759 if (t != NULL && t != current)
2760 rcu_wake_cond(t, __this_cpu_read(rcu_data.rcu_cpu_kthread_status));
2761 local_irq_restore(flags);
2765 * Wake up this CPU's rcuc kthread to do RCU core processing.
2767 static void invoke_rcu_core(void)
2769 if (!cpu_online(smp_processor_id()))
2772 raise_softirq(RCU_SOFTIRQ);
2774 invoke_rcu_core_kthread();
2777 static void rcu_cpu_kthread_park(unsigned int cpu)
2779 per_cpu(rcu_data.rcu_cpu_kthread_status, cpu) = RCU_KTHREAD_OFFCPU;
2782 static int rcu_cpu_kthread_should_run(unsigned int cpu)
2784 return __this_cpu_read(rcu_data.rcu_cpu_has_work);
2788 * Per-CPU kernel thread that invokes RCU callbacks. This replaces
2789 * the RCU softirq used in configurations of RCU that do not support RCU
2790 * priority boosting.
2792 static void rcu_cpu_kthread(unsigned int cpu)
2794 unsigned int *statusp = this_cpu_ptr(&rcu_data.rcu_cpu_kthread_status);
2795 char work, *workp = this_cpu_ptr(&rcu_data.rcu_cpu_has_work);
2798 trace_rcu_utilization(TPS("Start CPU kthread@rcu_run"));
2799 for (spincnt = 0; spincnt < 10; spincnt++) {
2801 *statusp = RCU_KTHREAD_RUNNING;
2802 local_irq_disable();
2810 trace_rcu_utilization(TPS("End CPU kthread@rcu_wait"));
2811 *statusp = RCU_KTHREAD_WAITING;
2815 *statusp = RCU_KTHREAD_YIELDING;
2816 trace_rcu_utilization(TPS("Start CPU kthread@rcu_yield"));
2817 schedule_timeout_idle(2);
2818 trace_rcu_utilization(TPS("End CPU kthread@rcu_yield"));
2819 *statusp = RCU_KTHREAD_WAITING;
2822 static struct smp_hotplug_thread rcu_cpu_thread_spec = {
2823 .store = &rcu_data.rcu_cpu_kthread_task,
2824 .thread_should_run = rcu_cpu_kthread_should_run,
2825 .thread_fn = rcu_cpu_kthread,
2826 .thread_comm = "rcuc/%u",
2827 .setup = rcu_cpu_kthread_setup,
2828 .park = rcu_cpu_kthread_park,
2832 * Spawn per-CPU RCU core processing kthreads.
2834 static int __init rcu_spawn_core_kthreads(void)
2838 for_each_possible_cpu(cpu)
2839 per_cpu(rcu_data.rcu_cpu_has_work, cpu) = 0;
2840 if (!IS_ENABLED(CONFIG_RCU_BOOST) && use_softirq)
2842 WARN_ONCE(smpboot_register_percpu_thread(&rcu_cpu_thread_spec),
2843 "%s: Could not start rcuc kthread, OOM is now expected behavior\n", __func__);
2846 early_initcall(rcu_spawn_core_kthreads);
2849 * Handle any core-RCU processing required by a call_rcu() invocation.
2851 static void __call_rcu_core(struct rcu_data *rdp, struct rcu_head *head,
2852 unsigned long flags)
2855 * If called from an extended quiescent state, invoke the RCU
2856 * core in order to force a re-evaluation of RCU's idleness.
2858 if (!rcu_is_watching())
2861 /* If interrupts were disabled or CPU offline, don't invoke RCU core. */
2862 if (irqs_disabled_flags(flags) || cpu_is_offline(smp_processor_id()))
2866 * Force the grace period if too many callbacks or too long waiting.
2867 * Enforce hysteresis, and don't invoke rcu_force_quiescent_state()
2868 * if some other CPU has recently done so. Also, don't bother
2869 * invoking rcu_force_quiescent_state() if the newly enqueued callback
2870 * is the only one waiting for a grace period to complete.
2872 if (unlikely(rcu_segcblist_n_cbs(&rdp->cblist) >
2873 rdp->qlen_last_fqs_check + qhimark)) {
2875 /* Are we ignoring a completed grace period? */
2876 note_gp_changes(rdp);
2878 /* Start a new grace period if one not already started. */
2879 if (!rcu_gp_in_progress()) {
2880 rcu_accelerate_cbs_unlocked(rdp->mynode, rdp);
2882 /* Give the grace period a kick. */
2883 rdp->blimit = DEFAULT_MAX_RCU_BLIMIT;
2884 if (rcu_state.n_force_qs == rdp->n_force_qs_snap &&
2885 rcu_segcblist_first_pend_cb(&rdp->cblist) != head)
2886 rcu_force_quiescent_state();
2887 rdp->n_force_qs_snap = rcu_state.n_force_qs;
2888 rdp->qlen_last_fqs_check = rcu_segcblist_n_cbs(&rdp->cblist);
2894 * RCU callback function to leak a callback.
2896 static void rcu_leak_callback(struct rcu_head *rhp)
2901 * Check and if necessary update the leaf rcu_node structure's
2902 * ->cbovldmask bit corresponding to the current CPU based on that CPU's
2903 * number of queued RCU callbacks. The caller must hold the leaf rcu_node
2904 * structure's ->lock.
2906 static void check_cb_ovld_locked(struct rcu_data *rdp, struct rcu_node *rnp)
2908 raw_lockdep_assert_held_rcu_node(rnp);
2909 if (qovld_calc <= 0)
2910 return; // Early boot and wildcard value set.
2911 if (rcu_segcblist_n_cbs(&rdp->cblist) >= qovld_calc)
2912 WRITE_ONCE(rnp->cbovldmask, rnp->cbovldmask | rdp->grpmask);
2914 WRITE_ONCE(rnp->cbovldmask, rnp->cbovldmask & ~rdp->grpmask);
2918 * Check and if necessary update the leaf rcu_node structure's
2919 * ->cbovldmask bit corresponding to the current CPU based on that CPU's
2920 * number of queued RCU callbacks. No locks need be held, but the
2921 * caller must have disabled interrupts.
2923 * Note that this function ignores the possibility that there are a lot
2924 * of callbacks all of which have already seen the end of their respective
2925 * grace periods. This omission is due to the need for no-CBs CPUs to
2926 * be holding ->nocb_lock to do this check, which is too heavy for a
2927 * common-case operation.
2929 static void check_cb_ovld(struct rcu_data *rdp)
2931 struct rcu_node *const rnp = rdp->mynode;
2933 if (qovld_calc <= 0 ||
2934 ((rcu_segcblist_n_cbs(&rdp->cblist) >= qovld_calc) ==
2935 !!(READ_ONCE(rnp->cbovldmask) & rdp->grpmask)))
2936 return; // Early boot wildcard value or already set correctly.
2937 raw_spin_lock_rcu_node(rnp);
2938 check_cb_ovld_locked(rdp, rnp);
2939 raw_spin_unlock_rcu_node(rnp);
2942 /* Helper function for call_rcu() and friends. */
2944 __call_rcu(struct rcu_head *head, rcu_callback_t func)
2946 unsigned long flags;
2947 struct rcu_data *rdp;
2950 /* Misaligned rcu_head! */
2951 WARN_ON_ONCE((unsigned long)head & (sizeof(void *) - 1));
2953 if (debug_rcu_head_queue(head)) {
2955 * Probable double call_rcu(), so leak the callback.
2956 * Use rcu:rcu_callback trace event to find the previous
2957 * time callback was passed to __call_rcu().
2959 WARN_ONCE(1, "__call_rcu(): Double-freed CB %p->%pS()!!!\n",
2961 WRITE_ONCE(head->func, rcu_leak_callback);
2966 local_irq_save(flags);
2967 kasan_record_aux_stack(head);
2968 rdp = this_cpu_ptr(&rcu_data);
2970 /* Add the callback to our list. */
2971 if (unlikely(!rcu_segcblist_is_enabled(&rdp->cblist))) {
2972 // This can trigger due to call_rcu() from offline CPU:
2973 WARN_ON_ONCE(rcu_scheduler_active != RCU_SCHEDULER_INACTIVE);
2974 WARN_ON_ONCE(!rcu_is_watching());
2975 // Very early boot, before rcu_init(). Initialize if needed
2976 // and then drop through to queue the callback.
2977 if (rcu_segcblist_empty(&rdp->cblist))
2978 rcu_segcblist_init(&rdp->cblist);
2982 if (rcu_nocb_try_bypass(rdp, head, &was_alldone, flags))
2983 return; // Enqueued onto ->nocb_bypass, so just leave.
2984 // If no-CBs CPU gets here, rcu_nocb_try_bypass() acquired ->nocb_lock.
2985 rcu_segcblist_enqueue(&rdp->cblist, head);
2986 if (__is_kvfree_rcu_offset((unsigned long)func))
2987 trace_rcu_kvfree_callback(rcu_state.name, head,
2988 (unsigned long)func,
2989 rcu_segcblist_n_cbs(&rdp->cblist));
2991 trace_rcu_callback(rcu_state.name, head,
2992 rcu_segcblist_n_cbs(&rdp->cblist));
2994 /* Go handle any RCU core processing required. */
2995 if (unlikely(rcu_segcblist_is_offloaded(&rdp->cblist))) {
2996 __call_rcu_nocb_wake(rdp, was_alldone, flags); /* unlocks */
2998 __call_rcu_core(rdp, head, flags);
2999 local_irq_restore(flags);
3004 * call_rcu() - Queue an RCU callback for invocation after a grace period.
3005 * @head: structure to be used for queueing the RCU updates.
3006 * @func: actual callback function to be invoked after the grace period
3008 * The callback function will be invoked some time after a full grace
3009 * period elapses, in other words after all pre-existing RCU read-side
3010 * critical sections have completed. However, the callback function
3011 * might well execute concurrently with RCU read-side critical sections
3012 * that started after call_rcu() was invoked. RCU read-side critical
3013 * sections are delimited by rcu_read_lock() and rcu_read_unlock(), and
3014 * may be nested. In addition, regions of code across which interrupts,
3015 * preemption, or softirqs have been disabled also serve as RCU read-side
3016 * critical sections. This includes hardware interrupt handlers, softirq
3017 * handlers, and NMI handlers.
3019 * Note that all CPUs must agree that the grace period extended beyond
3020 * all pre-existing RCU read-side critical section. On systems with more
3021 * than one CPU, this means that when "func()" is invoked, each CPU is
3022 * guaranteed to have executed a full memory barrier since the end of its
3023 * last RCU read-side critical section whose beginning preceded the call
3024 * to call_rcu(). It also means that each CPU executing an RCU read-side
3025 * critical section that continues beyond the start of "func()" must have
3026 * executed a memory barrier after the call_rcu() but before the beginning
3027 * of that RCU read-side critical section. Note that these guarantees
3028 * include CPUs that are offline, idle, or executing in user mode, as
3029 * well as CPUs that are executing in the kernel.
3031 * Furthermore, if CPU A invoked call_rcu() and CPU B invoked the
3032 * resulting RCU callback function "func()", then both CPU A and CPU B are
3033 * guaranteed to execute a full memory barrier during the time interval
3034 * between the call to call_rcu() and the invocation of "func()" -- even
3035 * if CPU A and CPU B are the same CPU (but again only if the system has
3036 * more than one CPU).
3038 void call_rcu(struct rcu_head *head, rcu_callback_t func)
3040 __call_rcu(head, func);
3042 EXPORT_SYMBOL_GPL(call_rcu);
3045 /* Maximum number of jiffies to wait before draining a batch. */
3046 #define KFREE_DRAIN_JIFFIES (HZ / 50)
3047 #define KFREE_N_BATCHES 2
3048 #define FREE_N_CHANNELS 2
3051 * struct kvfree_rcu_bulk_data - single block to store kvfree_rcu() pointers
3052 * @nr_records: Number of active pointers in the array
3053 * @next: Next bulk object in the block chain
3054 * @records: Array of the kvfree_rcu() pointers
3056 struct kvfree_rcu_bulk_data {
3057 unsigned long nr_records;
3058 struct kvfree_rcu_bulk_data *next;
3063 * This macro defines how many entries the "records" array
3064 * will contain. It is based on the fact that the size of
3065 * kvfree_rcu_bulk_data structure becomes exactly one page.
3067 #define KVFREE_BULK_MAX_ENTR \
3068 ((PAGE_SIZE - sizeof(struct kvfree_rcu_bulk_data)) / sizeof(void *))
3071 * struct kfree_rcu_cpu_work - single batch of kfree_rcu() requests
3072 * @rcu_work: Let queue_rcu_work() invoke workqueue handler after grace period
3073 * @head_free: List of kfree_rcu() objects waiting for a grace period
3074 * @bkvhead_free: Bulk-List of kvfree_rcu() objects waiting for a grace period
3075 * @krcp: Pointer to @kfree_rcu_cpu structure
3078 struct kfree_rcu_cpu_work {
3079 struct rcu_work rcu_work;
3080 struct rcu_head *head_free;
3081 struct kvfree_rcu_bulk_data *bkvhead_free[FREE_N_CHANNELS];
3082 struct kfree_rcu_cpu *krcp;
3086 * struct kfree_rcu_cpu - batch up kfree_rcu() requests for RCU grace period
3087 * @head: List of kfree_rcu() objects not yet waiting for a grace period
3088 * @bkvhead: Bulk-List of kvfree_rcu() objects not yet waiting for a grace period
3089 * @krw_arr: Array of batches of kfree_rcu() objects waiting for a grace period
3090 * @lock: Synchronize access to this structure
3091 * @monitor_work: Promote @head to @head_free after KFREE_DRAIN_JIFFIES
3092 * @monitor_todo: Tracks whether a @monitor_work delayed work is pending
3093 * @initialized: The @rcu_work fields have been initialized
3094 * @count: Number of objects for which GP not started
3096 * A simple cache list that contains objects for reuse purpose.
3097 * In order to save some per-cpu space the list is singular.
3098 * Even though it is lockless an access has to be protected by the
3100 * @page_cache_work: A work to refill the cache when it is empty
3101 * @work_in_progress: Indicates that page_cache_work is running
3102 * @hrtimer: A hrtimer for scheduling a page_cache_work
3103 * @nr_bkv_objs: number of allocated objects at @bkvcache.
3105 * This is a per-CPU structure. The reason that it is not included in
3106 * the rcu_data structure is to permit this code to be extracted from
3107 * the RCU files. Such extraction could allow further optimization of
3108 * the interactions with the slab allocators.
3110 struct kfree_rcu_cpu {
3111 struct rcu_head *head;
3112 struct kvfree_rcu_bulk_data *bkvhead[FREE_N_CHANNELS];
3113 struct kfree_rcu_cpu_work krw_arr[KFREE_N_BATCHES];
3114 raw_spinlock_t lock;
3115 struct delayed_work monitor_work;
3120 struct work_struct page_cache_work;
3121 atomic_t work_in_progress;
3122 struct hrtimer hrtimer;
3124 struct llist_head bkvcache;
3128 static DEFINE_PER_CPU(struct kfree_rcu_cpu, krc) = {
3129 .lock = __RAW_SPIN_LOCK_UNLOCKED(krc.lock),
3132 static __always_inline void
3133 debug_rcu_bhead_unqueue(struct kvfree_rcu_bulk_data *bhead)
3135 #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD
3138 for (i = 0; i < bhead->nr_records; i++)
3139 debug_rcu_head_unqueue((struct rcu_head *)(bhead->records[i]));
3143 static inline struct kfree_rcu_cpu *
3144 krc_this_cpu_lock(unsigned long *flags)
3146 struct kfree_rcu_cpu *krcp;
3148 local_irq_save(*flags); // For safely calling this_cpu_ptr().
3149 krcp = this_cpu_ptr(&krc);
3150 raw_spin_lock(&krcp->lock);
3156 krc_this_cpu_unlock(struct kfree_rcu_cpu *krcp, unsigned long flags)
3158 raw_spin_unlock(&krcp->lock);
3159 local_irq_restore(flags);
3162 static inline struct kvfree_rcu_bulk_data *
3163 get_cached_bnode(struct kfree_rcu_cpu *krcp)
3165 if (!krcp->nr_bkv_objs)
3168 krcp->nr_bkv_objs--;
3169 return (struct kvfree_rcu_bulk_data *)
3170 llist_del_first(&krcp->bkvcache);
3174 put_cached_bnode(struct kfree_rcu_cpu *krcp,
3175 struct kvfree_rcu_bulk_data *bnode)
3178 if (krcp->nr_bkv_objs >= rcu_min_cached_objs)
3181 llist_add((struct llist_node *) bnode, &krcp->bkvcache);
3182 krcp->nr_bkv_objs++;
3188 * This function is invoked in workqueue context after a grace period.
3189 * It frees all the objects queued on ->bhead_free or ->head_free.
3191 static void kfree_rcu_work(struct work_struct *work)
3193 unsigned long flags;
3194 struct kvfree_rcu_bulk_data *bkvhead[FREE_N_CHANNELS], *bnext;
3195 struct rcu_head *head, *next;
3196 struct kfree_rcu_cpu *krcp;
3197 struct kfree_rcu_cpu_work *krwp;
3200 krwp = container_of(to_rcu_work(work),
3201 struct kfree_rcu_cpu_work, rcu_work);
3204 raw_spin_lock_irqsave(&krcp->lock, flags);
3205 // Channels 1 and 2.
3206 for (i = 0; i < FREE_N_CHANNELS; i++) {
3207 bkvhead[i] = krwp->bkvhead_free[i];
3208 krwp->bkvhead_free[i] = NULL;
3212 head = krwp->head_free;
3213 krwp->head_free = NULL;
3214 raw_spin_unlock_irqrestore(&krcp->lock, flags);
3216 // Handle two first channels.
3217 for (i = 0; i < FREE_N_CHANNELS; i++) {
3218 for (; bkvhead[i]; bkvhead[i] = bnext) {
3219 bnext = bkvhead[i]->next;
3220 debug_rcu_bhead_unqueue(bkvhead[i]);
3222 rcu_lock_acquire(&rcu_callback_map);
3223 if (i == 0) { // kmalloc() / kfree().
3224 trace_rcu_invoke_kfree_bulk_callback(
3225 rcu_state.name, bkvhead[i]->nr_records,
3226 bkvhead[i]->records);
3228 kfree_bulk(bkvhead[i]->nr_records,
3229 bkvhead[i]->records);
3230 } else { // vmalloc() / vfree().
3231 for (j = 0; j < bkvhead[i]->nr_records; j++) {
3232 trace_rcu_invoke_kvfree_callback(
3234 bkvhead[i]->records[j], 0);
3236 vfree(bkvhead[i]->records[j]);
3239 rcu_lock_release(&rcu_callback_map);
3241 raw_spin_lock_irqsave(&krcp->lock, flags);
3242 if (put_cached_bnode(krcp, bkvhead[i]))
3244 raw_spin_unlock_irqrestore(&krcp->lock, flags);
3247 free_page((unsigned long) bkvhead[i]);
3249 cond_resched_tasks_rcu_qs();
3254 * Emergency case only. It can happen under low memory
3255 * condition when an allocation gets failed, so the "bulk"
3256 * path can not be temporary maintained.
3258 for (; head; head = next) {
3259 unsigned long offset = (unsigned long)head->func;
3260 void *ptr = (void *)head - offset;
3263 debug_rcu_head_unqueue((struct rcu_head *)ptr);
3264 rcu_lock_acquire(&rcu_callback_map);
3265 trace_rcu_invoke_kvfree_callback(rcu_state.name, head, offset);
3267 if (!WARN_ON_ONCE(!__is_kvfree_rcu_offset(offset)))
3270 rcu_lock_release(&rcu_callback_map);
3271 cond_resched_tasks_rcu_qs();
3276 * Schedule the kfree batch RCU work to run in workqueue context after a GP.
3278 * This function is invoked by kfree_rcu_monitor() when the KFREE_DRAIN_JIFFIES
3279 * timeout has been reached.
3281 static inline bool queue_kfree_rcu_work(struct kfree_rcu_cpu *krcp)
3283 struct kfree_rcu_cpu_work *krwp;
3284 bool repeat = false;
3287 lockdep_assert_held(&krcp->lock);
3289 for (i = 0; i < KFREE_N_BATCHES; i++) {
3290 krwp = &(krcp->krw_arr[i]);
3293 * Try to detach bkvhead or head and attach it over any
3294 * available corresponding free channel. It can be that
3295 * a previous RCU batch is in progress, it means that
3296 * immediately to queue another one is not possible so
3297 * return false to tell caller to retry.
3299 if ((krcp->bkvhead[0] && !krwp->bkvhead_free[0]) ||
3300 (krcp->bkvhead[1] && !krwp->bkvhead_free[1]) ||
3301 (krcp->head && !krwp->head_free)) {
3302 // Channel 1 corresponds to SLAB ptrs.
3303 // Channel 2 corresponds to vmalloc ptrs.
3304 for (j = 0; j < FREE_N_CHANNELS; j++) {
3305 if (!krwp->bkvhead_free[j]) {
3306 krwp->bkvhead_free[j] = krcp->bkvhead[j];
3307 krcp->bkvhead[j] = NULL;
3311 // Channel 3 corresponds to emergency path.
3312 if (!krwp->head_free) {
3313 krwp->head_free = krcp->head;
3317 WRITE_ONCE(krcp->count, 0);
3320 * One work is per one batch, so there are three
3321 * "free channels", the batch can handle. It can
3322 * be that the work is in the pending state when
3323 * channels have been detached following by each
3326 queue_rcu_work(system_wq, &krwp->rcu_work);
3329 // Repeat if any "free" corresponding channel is still busy.
3330 if (krcp->bkvhead[0] || krcp->bkvhead[1] || krcp->head)
3337 static inline void kfree_rcu_drain_unlock(struct kfree_rcu_cpu *krcp,
3338 unsigned long flags)
3340 // Attempt to start a new batch.
3341 krcp->monitor_todo = false;
3342 if (queue_kfree_rcu_work(krcp)) {
3343 // Success! Our job is done here.
3344 raw_spin_unlock_irqrestore(&krcp->lock, flags);
3348 // Previous RCU batch still in progress, try again later.
3349 krcp->monitor_todo = true;
3350 schedule_delayed_work(&krcp->monitor_work, KFREE_DRAIN_JIFFIES);
3351 raw_spin_unlock_irqrestore(&krcp->lock, flags);
3355 * This function is invoked after the KFREE_DRAIN_JIFFIES timeout.
3356 * It invokes kfree_rcu_drain_unlock() to attempt to start another batch.
3358 static void kfree_rcu_monitor(struct work_struct *work)
3360 unsigned long flags;
3361 struct kfree_rcu_cpu *krcp = container_of(work, struct kfree_rcu_cpu,
3364 raw_spin_lock_irqsave(&krcp->lock, flags);
3365 if (krcp->monitor_todo)
3366 kfree_rcu_drain_unlock(krcp, flags);
3368 raw_spin_unlock_irqrestore(&krcp->lock, flags);
3371 static enum hrtimer_restart
3372 schedule_page_work_fn(struct hrtimer *t)
3374 struct kfree_rcu_cpu *krcp =
3375 container_of(t, struct kfree_rcu_cpu, hrtimer);
3377 queue_work(system_highpri_wq, &krcp->page_cache_work);
3378 return HRTIMER_NORESTART;
3381 static void fill_page_cache_func(struct work_struct *work)
3383 struct kvfree_rcu_bulk_data *bnode;
3384 struct kfree_rcu_cpu *krcp =
3385 container_of(work, struct kfree_rcu_cpu,
3387 unsigned long flags;
3391 for (i = 0; i < rcu_min_cached_objs; i++) {
3392 bnode = (struct kvfree_rcu_bulk_data *)
3393 __get_free_page(GFP_KERNEL | __GFP_NOWARN);
3396 raw_spin_lock_irqsave(&krcp->lock, flags);
3397 pushed = put_cached_bnode(krcp, bnode);
3398 raw_spin_unlock_irqrestore(&krcp->lock, flags);
3401 free_page((unsigned long) bnode);
3407 atomic_set(&krcp->work_in_progress, 0);
3411 run_page_cache_worker(struct kfree_rcu_cpu *krcp)
3413 if (rcu_scheduler_active == RCU_SCHEDULER_RUNNING &&
3414 !atomic_xchg(&krcp->work_in_progress, 1)) {
3415 hrtimer_init(&krcp->hrtimer, CLOCK_MONOTONIC,
3417 krcp->hrtimer.function = schedule_page_work_fn;
3418 hrtimer_start(&krcp->hrtimer, 0, HRTIMER_MODE_REL);
3423 kvfree_call_rcu_add_ptr_to_bulk(struct kfree_rcu_cpu *krcp, void *ptr)
3425 struct kvfree_rcu_bulk_data *bnode;
3428 if (unlikely(!krcp->initialized))
3431 lockdep_assert_held(&krcp->lock);
3432 idx = !!is_vmalloc_addr(ptr);
3434 /* Check if a new block is required. */
3435 if (!krcp->bkvhead[idx] ||
3436 krcp->bkvhead[idx]->nr_records == KVFREE_BULK_MAX_ENTR) {
3437 bnode = get_cached_bnode(krcp);
3438 /* Switch to emergency path. */
3442 /* Initialize the new block. */
3443 bnode->nr_records = 0;
3444 bnode->next = krcp->bkvhead[idx];
3446 /* Attach it to the head. */
3447 krcp->bkvhead[idx] = bnode;
3450 /* Finally insert. */
3451 krcp->bkvhead[idx]->records
3452 [krcp->bkvhead[idx]->nr_records++] = ptr;
3458 * Queue a request for lazy invocation of appropriate free routine after a
3459 * grace period. Please note there are three paths are maintained, two are the
3460 * main ones that use array of pointers interface and third one is emergency
3461 * one, that is used only when the main path can not be maintained temporary,
3462 * due to memory pressure.
3464 * Each kvfree_call_rcu() request is added to a batch. The batch will be drained
3465 * every KFREE_DRAIN_JIFFIES number of jiffies. All the objects in the batch will
3466 * be free'd in workqueue context. This allows us to: batch requests together to
3467 * reduce the number of grace periods during heavy kfree_rcu()/kvfree_rcu() load.
3469 void kvfree_call_rcu(struct rcu_head *head, rcu_callback_t func)
3471 unsigned long flags;
3472 struct kfree_rcu_cpu *krcp;
3477 ptr = (void *) head - (unsigned long) func;
3480 * Please note there is a limitation for the head-less
3481 * variant, that is why there is a clear rule for such
3482 * objects: it can be used from might_sleep() context
3483 * only. For other places please embed an rcu_head to
3487 ptr = (unsigned long *) func;
3490 krcp = krc_this_cpu_lock(&flags);
3492 // Queue the object but don't yet schedule the batch.
3493 if (debug_rcu_head_queue(ptr)) {
3494 // Probable double kfree_rcu(), just leak.
3495 WARN_ONCE(1, "%s(): Double-freed call. rcu_head %p\n",
3498 // Mark as success and leave.
3503 success = kvfree_call_rcu_add_ptr_to_bulk(krcp, ptr);
3505 run_page_cache_worker(krcp);
3508 // Inline if kvfree_rcu(one_arg) call.
3512 head->next = krcp->head;
3517 WRITE_ONCE(krcp->count, krcp->count + 1);
3519 // Set timer to drain after KFREE_DRAIN_JIFFIES.
3520 if (rcu_scheduler_active == RCU_SCHEDULER_RUNNING &&
3521 !krcp->monitor_todo) {
3522 krcp->monitor_todo = true;
3523 schedule_delayed_work(&krcp->monitor_work, KFREE_DRAIN_JIFFIES);
3527 krc_this_cpu_unlock(krcp, flags);
3530 * Inline kvfree() after synchronize_rcu(). We can do
3531 * it from might_sleep() context only, so the current
3532 * CPU can pass the QS state.
3535 debug_rcu_head_unqueue((struct rcu_head *) ptr);
3540 EXPORT_SYMBOL_GPL(kvfree_call_rcu);
3542 static unsigned long
3543 kfree_rcu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
3546 unsigned long count = 0;
3548 /* Snapshot count of all CPUs */
3549 for_each_possible_cpu(cpu) {
3550 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu);
3552 count += READ_ONCE(krcp->count);
3558 static unsigned long
3559 kfree_rcu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
3562 unsigned long flags;
3564 for_each_possible_cpu(cpu) {
3566 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu);
3568 count = krcp->count;
3569 raw_spin_lock_irqsave(&krcp->lock, flags);
3570 if (krcp->monitor_todo)
3571 kfree_rcu_drain_unlock(krcp, flags);
3573 raw_spin_unlock_irqrestore(&krcp->lock, flags);
3575 sc->nr_to_scan -= count;
3578 if (sc->nr_to_scan <= 0)
3582 return freed == 0 ? SHRINK_STOP : freed;
3585 static struct shrinker kfree_rcu_shrinker = {
3586 .count_objects = kfree_rcu_shrink_count,
3587 .scan_objects = kfree_rcu_shrink_scan,
3589 .seeks = DEFAULT_SEEKS,
3592 void __init kfree_rcu_scheduler_running(void)
3595 unsigned long flags;
3597 for_each_possible_cpu(cpu) {
3598 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu);
3600 raw_spin_lock_irqsave(&krcp->lock, flags);
3601 if (!krcp->head || krcp->monitor_todo) {
3602 raw_spin_unlock_irqrestore(&krcp->lock, flags);
3605 krcp->monitor_todo = true;
3606 schedule_delayed_work_on(cpu, &krcp->monitor_work,
3607 KFREE_DRAIN_JIFFIES);
3608 raw_spin_unlock_irqrestore(&krcp->lock, flags);
3613 * During early boot, any blocking grace-period wait automatically
3614 * implies a grace period. Later on, this is never the case for PREEMPTION.
3616 * However, because a context switch is a grace period for !PREEMPTION, any
3617 * blocking grace-period wait automatically implies a grace period if
3618 * there is only one CPU online at any point time during execution of
3619 * either synchronize_rcu() or synchronize_rcu_expedited(). It is OK to
3620 * occasionally incorrectly indicate that there are multiple CPUs online
3621 * when there was in fact only one the whole time, as this just adds some
3622 * overhead: RCU still operates correctly.
3624 static int rcu_blocking_is_gp(void)
3628 if (IS_ENABLED(CONFIG_PREEMPTION))
3629 return rcu_scheduler_active == RCU_SCHEDULER_INACTIVE;
3630 might_sleep(); /* Check for RCU read-side critical section. */
3633 * If the rcu_state.n_online_cpus counter is equal to one,
3634 * there is only one CPU, and that CPU sees all prior accesses
3635 * made by any CPU that was online at the time of its access.
3636 * Furthermore, if this counter is equal to one, its value cannot
3637 * change until after the preempt_enable() below.
3639 * Furthermore, if rcu_state.n_online_cpus is equal to one here,
3640 * all later CPUs (both this one and any that come online later
3641 * on) are guaranteed to see all accesses prior to this point
3642 * in the code, without the need for additional memory barriers.
3643 * Those memory barriers are provided by CPU-hotplug code.
3645 ret = READ_ONCE(rcu_state.n_online_cpus) <= 1;
3651 * synchronize_rcu - wait until a grace period has elapsed.
3653 * Control will return to the caller some time after a full grace
3654 * period has elapsed, in other words after all currently executing RCU
3655 * read-side critical sections have completed. Note, however, that
3656 * upon return from synchronize_rcu(), the caller might well be executing
3657 * concurrently with new RCU read-side critical sections that began while
3658 * synchronize_rcu() was waiting. RCU read-side critical sections are
3659 * delimited by rcu_read_lock() and rcu_read_unlock(), and may be nested.
3660 * In addition, regions of code across which interrupts, preemption, or
3661 * softirqs have been disabled also serve as RCU read-side critical
3662 * sections. This includes hardware interrupt handlers, softirq handlers,
3665 * Note that this guarantee implies further memory-ordering guarantees.
3666 * On systems with more than one CPU, when synchronize_rcu() returns,
3667 * each CPU is guaranteed to have executed a full memory barrier since
3668 * the end of its last RCU read-side critical section whose beginning
3669 * preceded the call to synchronize_rcu(). In addition, each CPU having
3670 * an RCU read-side critical section that extends beyond the return from
3671 * synchronize_rcu() is guaranteed to have executed a full memory barrier
3672 * after the beginning of synchronize_rcu() and before the beginning of
3673 * that RCU read-side critical section. Note that these guarantees include
3674 * CPUs that are offline, idle, or executing in user mode, as well as CPUs
3675 * that are executing in the kernel.
3677 * Furthermore, if CPU A invoked synchronize_rcu(), which returned
3678 * to its caller on CPU B, then both CPU A and CPU B are guaranteed
3679 * to have executed a full memory barrier during the execution of
3680 * synchronize_rcu() -- even if CPU A and CPU B are the same CPU (but
3681 * again only if the system has more than one CPU).
3683 void synchronize_rcu(void)
3685 RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map) ||
3686 lock_is_held(&rcu_lock_map) ||
3687 lock_is_held(&rcu_sched_lock_map),
3688 "Illegal synchronize_rcu() in RCU read-side critical section");
3689 if (rcu_blocking_is_gp())
3690 return; // Context allows vacuous grace periods.
3691 if (rcu_gp_is_expedited())
3692 synchronize_rcu_expedited();
3694 wait_rcu_gp(call_rcu);
3696 EXPORT_SYMBOL_GPL(synchronize_rcu);
3699 * get_state_synchronize_rcu - Snapshot current RCU state
3701 * Returns a cookie that is used by a later call to cond_synchronize_rcu()
3702 * to determine whether or not a full grace period has elapsed in the
3705 unsigned long get_state_synchronize_rcu(void)
3708 * Any prior manipulation of RCU-protected data must happen
3709 * before the load from ->gp_seq.
3712 return rcu_seq_snap(&rcu_state.gp_seq);
3714 EXPORT_SYMBOL_GPL(get_state_synchronize_rcu);
3717 * cond_synchronize_rcu - Conditionally wait for an RCU grace period
3719 * @oldstate: return value from earlier call to get_state_synchronize_rcu()
3721 * If a full RCU grace period has elapsed since the earlier call to
3722 * get_state_synchronize_rcu(), just return. Otherwise, invoke
3723 * synchronize_rcu() to wait for a full grace period.
3725 * Yes, this function does not take counter wrap into account. But
3726 * counter wrap is harmless. If the counter wraps, we have waited for
3727 * more than 2 billion grace periods (and way more on a 64-bit system!),
3728 * so waiting for one additional grace period should be just fine.
3730 void cond_synchronize_rcu(unsigned long oldstate)
3732 if (!rcu_seq_done(&rcu_state.gp_seq, oldstate))
3735 smp_mb(); /* Ensure GP ends before subsequent accesses. */
3737 EXPORT_SYMBOL_GPL(cond_synchronize_rcu);
3740 * Check to see if there is any immediate RCU-related work to be done by
3741 * the current CPU, returning 1 if so and zero otherwise. The checks are
3742 * in order of increasing expense: checks that can be carried out against
3743 * CPU-local state are performed first. However, we must check for CPU
3744 * stalls first, else we might not get a chance.
3746 static int rcu_pending(int user)
3748 bool gp_in_progress;
3749 struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
3750 struct rcu_node *rnp = rdp->mynode;
3752 /* Check for CPU stalls, if enabled. */
3753 check_cpu_stall(rdp);
3755 /* Does this CPU need a deferred NOCB wakeup? */
3756 if (rcu_nocb_need_deferred_wakeup(rdp))
3759 /* Is this a nohz_full CPU in userspace or idle? (Ignore RCU if so.) */
3760 if ((user || rcu_is_cpu_rrupt_from_idle()) && rcu_nohz_full_cpu())
3763 /* Is the RCU core waiting for a quiescent state from this CPU? */
3764 gp_in_progress = rcu_gp_in_progress();
3765 if (rdp->core_needs_qs && !rdp->cpu_no_qs.b.norm && gp_in_progress)
3768 /* Does this CPU have callbacks ready to invoke? */
3769 if (!rcu_segcblist_is_offloaded(&rdp->cblist) &&
3770 rcu_segcblist_ready_cbs(&rdp->cblist))
3773 /* Has RCU gone idle with this CPU needing another grace period? */
3774 if (!gp_in_progress && rcu_segcblist_is_enabled(&rdp->cblist) &&
3775 !rcu_segcblist_is_offloaded(&rdp->cblist) &&
3776 !rcu_segcblist_restempty(&rdp->cblist, RCU_NEXT_READY_TAIL))
3779 /* Have RCU grace period completed or started? */
3780 if (rcu_seq_current(&rnp->gp_seq) != rdp->gp_seq ||
3781 unlikely(READ_ONCE(rdp->gpwrap))) /* outside lock */
3789 * Helper function for rcu_barrier() tracing. If tracing is disabled,
3790 * the compiler is expected to optimize this away.
3792 static void rcu_barrier_trace(const char *s, int cpu, unsigned long done)
3794 trace_rcu_barrier(rcu_state.name, s, cpu,
3795 atomic_read(&rcu_state.barrier_cpu_count), done);
3799 * RCU callback function for rcu_barrier(). If we are last, wake
3800 * up the task executing rcu_barrier().
3802 * Note that the value of rcu_state.barrier_sequence must be captured
3803 * before the atomic_dec_and_test(). Otherwise, if this CPU is not last,
3804 * other CPUs might count the value down to zero before this CPU gets
3805 * around to invoking rcu_barrier_trace(), which might result in bogus
3806 * data from the next instance of rcu_barrier().
3808 static void rcu_barrier_callback(struct rcu_head *rhp)
3810 unsigned long __maybe_unused s = rcu_state.barrier_sequence;
3812 if (atomic_dec_and_test(&rcu_state.barrier_cpu_count)) {
3813 rcu_barrier_trace(TPS("LastCB"), -1, s);
3814 complete(&rcu_state.barrier_completion);
3816 rcu_barrier_trace(TPS("CB"), -1, s);
3821 * Called with preemption disabled, and from cross-cpu IRQ context.
3823 static void rcu_barrier_func(void *cpu_in)
3825 uintptr_t cpu = (uintptr_t)cpu_in;
3826 struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
3828 rcu_barrier_trace(TPS("IRQ"), -1, rcu_state.barrier_sequence);
3829 rdp->barrier_head.func = rcu_barrier_callback;
3830 debug_rcu_head_queue(&rdp->barrier_head);
3832 WARN_ON_ONCE(!rcu_nocb_flush_bypass(rdp, NULL, jiffies));
3833 if (rcu_segcblist_entrain(&rdp->cblist, &rdp->barrier_head)) {
3834 atomic_inc(&rcu_state.barrier_cpu_count);
3836 debug_rcu_head_unqueue(&rdp->barrier_head);
3837 rcu_barrier_trace(TPS("IRQNQ"), -1,
3838 rcu_state.barrier_sequence);
3840 rcu_nocb_unlock(rdp);
3844 * rcu_barrier - Wait until all in-flight call_rcu() callbacks complete.
3846 * Note that this primitive does not necessarily wait for an RCU grace period
3847 * to complete. For example, if there are no RCU callbacks queued anywhere
3848 * in the system, then rcu_barrier() is within its rights to return
3849 * immediately, without waiting for anything, much less an RCU grace period.
3851 void rcu_barrier(void)
3854 struct rcu_data *rdp;
3855 unsigned long s = rcu_seq_snap(&rcu_state.barrier_sequence);
3857 rcu_barrier_trace(TPS("Begin"), -1, s);
3859 /* Take mutex to serialize concurrent rcu_barrier() requests. */
3860 mutex_lock(&rcu_state.barrier_mutex);
3862 /* Did someone else do our work for us? */
3863 if (rcu_seq_done(&rcu_state.barrier_sequence, s)) {
3864 rcu_barrier_trace(TPS("EarlyExit"), -1,
3865 rcu_state.barrier_sequence);
3866 smp_mb(); /* caller's subsequent code after above check. */
3867 mutex_unlock(&rcu_state.barrier_mutex);
3871 /* Mark the start of the barrier operation. */
3872 rcu_seq_start(&rcu_state.barrier_sequence);
3873 rcu_barrier_trace(TPS("Inc1"), -1, rcu_state.barrier_sequence);
3876 * Initialize the count to two rather than to zero in order
3877 * to avoid a too-soon return to zero in case of an immediate
3878 * invocation of the just-enqueued callback (or preemption of
3879 * this task). Exclude CPU-hotplug operations to ensure that no
3880 * offline non-offloaded CPU has callbacks queued.
3882 init_completion(&rcu_state.barrier_completion);
3883 atomic_set(&rcu_state.barrier_cpu_count, 2);
3887 * Force each CPU with callbacks to register a new callback.
3888 * When that callback is invoked, we will know that all of the
3889 * corresponding CPU's preceding callbacks have been invoked.
3891 for_each_possible_cpu(cpu) {
3892 rdp = per_cpu_ptr(&rcu_data, cpu);
3893 if (cpu_is_offline(cpu) &&
3894 !rcu_segcblist_is_offloaded(&rdp->cblist))
3896 if (rcu_segcblist_n_cbs(&rdp->cblist) && cpu_online(cpu)) {
3897 rcu_barrier_trace(TPS("OnlineQ"), cpu,
3898 rcu_state.barrier_sequence);
3899 smp_call_function_single(cpu, rcu_barrier_func, (void *)cpu, 1);
3900 } else if (rcu_segcblist_n_cbs(&rdp->cblist) &&
3901 cpu_is_offline(cpu)) {
3902 rcu_barrier_trace(TPS("OfflineNoCBQ"), cpu,
3903 rcu_state.barrier_sequence);
3904 local_irq_disable();
3905 rcu_barrier_func((void *)cpu);
3907 } else if (cpu_is_offline(cpu)) {
3908 rcu_barrier_trace(TPS("OfflineNoCBNoQ"), cpu,
3909 rcu_state.barrier_sequence);
3911 rcu_barrier_trace(TPS("OnlineNQ"), cpu,
3912 rcu_state.barrier_sequence);
3918 * Now that we have an rcu_barrier_callback() callback on each
3919 * CPU, and thus each counted, remove the initial count.
3921 if (atomic_sub_and_test(2, &rcu_state.barrier_cpu_count))
3922 complete(&rcu_state.barrier_completion);
3924 /* Wait for all rcu_barrier_callback() callbacks to be invoked. */
3925 wait_for_completion(&rcu_state.barrier_completion);
3927 /* Mark the end of the barrier operation. */
3928 rcu_barrier_trace(TPS("Inc2"), -1, rcu_state.barrier_sequence);
3929 rcu_seq_end(&rcu_state.barrier_sequence);
3931 /* Other rcu_barrier() invocations can now safely proceed. */
3932 mutex_unlock(&rcu_state.barrier_mutex);
3934 EXPORT_SYMBOL_GPL(rcu_barrier);
3937 * Propagate ->qsinitmask bits up the rcu_node tree to account for the
3938 * first CPU in a given leaf rcu_node structure coming online. The caller
3939 * must hold the corresponding leaf rcu_node ->lock with interrrupts
3942 static void rcu_init_new_rnp(struct rcu_node *rnp_leaf)
3946 struct rcu_node *rnp = rnp_leaf;
3948 raw_lockdep_assert_held_rcu_node(rnp_leaf);
3949 WARN_ON_ONCE(rnp->wait_blkd_tasks);
3951 mask = rnp->grpmask;
3955 raw_spin_lock_rcu_node(rnp); /* Interrupts already disabled. */
3956 oldmask = rnp->qsmaskinit;
3957 rnp->qsmaskinit |= mask;
3958 raw_spin_unlock_rcu_node(rnp); /* Interrupts remain disabled. */
3965 * Do boot-time initialization of a CPU's per-CPU RCU data.
3968 rcu_boot_init_percpu_data(int cpu)
3970 struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
3972 /* Set up local state, ensuring consistent view of global state. */
3973 rdp->grpmask = leaf_node_cpu_bit(rdp->mynode, cpu);
3974 INIT_WORK(&rdp->strict_work, strict_work_handler);
3975 WARN_ON_ONCE(rdp->dynticks_nesting != 1);
3976 WARN_ON_ONCE(rcu_dynticks_in_eqs(rcu_dynticks_snap(rdp)));
3977 rdp->rcu_ofl_gp_seq = rcu_state.gp_seq;
3978 rdp->rcu_ofl_gp_flags = RCU_GP_CLEANED;
3979 rdp->rcu_onl_gp_seq = rcu_state.gp_seq;
3980 rdp->rcu_onl_gp_flags = RCU_GP_CLEANED;
3982 rcu_boot_init_nocb_percpu_data(rdp);
3986 * Invoked early in the CPU-online process, when pretty much all services
3987 * are available. The incoming CPU is not present.
3989 * Initializes a CPU's per-CPU RCU data. Note that only one online or
3990 * offline event can be happening at a given time. Note also that we can
3991 * accept some slop in the rsp->gp_seq access due to the fact that this
3992 * CPU cannot possibly have any non-offloaded RCU callbacks in flight yet.
3993 * And any offloaded callbacks are being numbered elsewhere.
3995 int rcutree_prepare_cpu(unsigned int cpu)
3997 unsigned long flags;
3998 struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
3999 struct rcu_node *rnp = rcu_get_root();
4001 /* Set up local state, ensuring consistent view of global state. */
4002 raw_spin_lock_irqsave_rcu_node(rnp, flags);
4003 rdp->qlen_last_fqs_check = 0;
4004 rdp->n_force_qs_snap = rcu_state.n_force_qs;
4005 rdp->blimit = blimit;
4006 if (rcu_segcblist_empty(&rdp->cblist) && /* No early-boot CBs? */
4007 !rcu_segcblist_is_offloaded(&rdp->cblist))
4008 rcu_segcblist_init(&rdp->cblist); /* Re-enable callbacks. */
4009 rdp->dynticks_nesting = 1; /* CPU not up, no tearing. */
4010 rcu_dynticks_eqs_online();
4011 raw_spin_unlock_rcu_node(rnp); /* irqs remain disabled. */
4014 * Add CPU to leaf rcu_node pending-online bitmask. Any needed
4015 * propagation up the rcu_node tree will happen at the beginning
4016 * of the next grace period.
4019 raw_spin_lock_rcu_node(rnp); /* irqs already disabled. */
4020 rdp->beenonline = true; /* We have now been online. */
4021 rdp->gp_seq = READ_ONCE(rnp->gp_seq);
4022 rdp->gp_seq_needed = rdp->gp_seq;
4023 rdp->cpu_no_qs.b.norm = true;
4024 rdp->core_needs_qs = false;
4025 rdp->rcu_iw_pending = false;
4026 rdp->rcu_iw = IRQ_WORK_INIT_HARD(rcu_iw_handler);
4027 rdp->rcu_iw_gp_seq = rdp->gp_seq - 1;
4028 trace_rcu_grace_period(rcu_state.name, rdp->gp_seq, TPS("cpuonl"));
4029 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4030 rcu_prepare_kthreads(cpu);
4031 rcu_spawn_cpu_nocb_kthread(cpu);
4032 WRITE_ONCE(rcu_state.n_online_cpus, rcu_state.n_online_cpus + 1);
4038 * Update RCU priority boot kthread affinity for CPU-hotplug changes.
4040 static void rcutree_affinity_setting(unsigned int cpu, int outgoing)
4042 struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
4044 rcu_boost_kthread_setaffinity(rdp->mynode, outgoing);
4048 * Near the end of the CPU-online process. Pretty much all services
4049 * enabled, and the CPU is now very much alive.
4051 int rcutree_online_cpu(unsigned int cpu)
4053 unsigned long flags;
4054 struct rcu_data *rdp;
4055 struct rcu_node *rnp;
4057 rdp = per_cpu_ptr(&rcu_data, cpu);
4059 raw_spin_lock_irqsave_rcu_node(rnp, flags);
4060 rnp->ffmask |= rdp->grpmask;
4061 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4062 if (rcu_scheduler_active == RCU_SCHEDULER_INACTIVE)
4063 return 0; /* Too early in boot for scheduler work. */
4064 sync_sched_exp_online_cleanup(cpu);
4065 rcutree_affinity_setting(cpu, -1);
4067 // Stop-machine done, so allow nohz_full to disable tick.
4068 tick_dep_clear(TICK_DEP_BIT_RCU);
4073 * Near the beginning of the process. The CPU is still very much alive
4074 * with pretty much all services enabled.
4076 int rcutree_offline_cpu(unsigned int cpu)
4078 unsigned long flags;
4079 struct rcu_data *rdp;
4080 struct rcu_node *rnp;
4082 rdp = per_cpu_ptr(&rcu_data, cpu);
4084 raw_spin_lock_irqsave_rcu_node(rnp, flags);
4085 rnp->ffmask &= ~rdp->grpmask;
4086 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4088 rcutree_affinity_setting(cpu, cpu);
4090 // nohz_full CPUs need the tick for stop-machine to work quickly
4091 tick_dep_set(TICK_DEP_BIT_RCU);
4096 * Mark the specified CPU as being online so that subsequent grace periods
4097 * (both expedited and normal) will wait on it. Note that this means that
4098 * incoming CPUs are not allowed to use RCU read-side critical sections
4099 * until this function is called. Failing to observe this restriction
4100 * will result in lockdep splats.
4102 * Note that this function is special in that it is invoked directly
4103 * from the incoming CPU rather than from the cpuhp_step mechanism.
4104 * This is because this function must be invoked at a precise location.
4106 void rcu_cpu_starting(unsigned int cpu)
4108 unsigned long flags;
4110 struct rcu_data *rdp;
4111 struct rcu_node *rnp;
4114 rdp = per_cpu_ptr(&rcu_data, cpu);
4115 if (rdp->cpu_started)
4117 rdp->cpu_started = true;
4120 mask = rdp->grpmask;
4121 WRITE_ONCE(rnp->ofl_seq, rnp->ofl_seq + 1);
4122 WARN_ON_ONCE(!(rnp->ofl_seq & 0x1));
4123 smp_mb(); // Pair with rcu_gp_cleanup()'s ->ofl_seq barrier().
4124 raw_spin_lock_irqsave_rcu_node(rnp, flags);
4125 WRITE_ONCE(rnp->qsmaskinitnext, rnp->qsmaskinitnext | mask);
4126 newcpu = !(rnp->expmaskinitnext & mask);
4127 rnp->expmaskinitnext |= mask;
4128 /* Allow lockless access for expedited grace periods. */
4129 smp_store_release(&rcu_state.ncpus, rcu_state.ncpus + newcpu); /* ^^^ */
4130 ASSERT_EXCLUSIVE_WRITER(rcu_state.ncpus);
4131 rcu_gpnum_ovf(rnp, rdp); /* Offline-induced counter wrap? */
4132 rdp->rcu_onl_gp_seq = READ_ONCE(rcu_state.gp_seq);
4133 rdp->rcu_onl_gp_flags = READ_ONCE(rcu_state.gp_flags);
4135 /* An incoming CPU should never be blocking a grace period. */
4136 if (WARN_ON_ONCE(rnp->qsmask & mask)) { /* RCU waiting on incoming CPU? */
4137 rcu_disable_urgency_upon_qs(rdp);
4138 /* Report QS -after- changing ->qsmaskinitnext! */
4139 rcu_report_qs_rnp(mask, rnp, rnp->gp_seq, flags);
4141 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4143 smp_mb(); // Pair with rcu_gp_cleanup()'s ->ofl_seq barrier().
4144 WRITE_ONCE(rnp->ofl_seq, rnp->ofl_seq + 1);
4145 WARN_ON_ONCE(rnp->ofl_seq & 0x1);
4146 smp_mb(); /* Ensure RCU read-side usage follows above initialization. */
4150 * The outgoing function has no further need of RCU, so remove it from
4151 * the rcu_node tree's ->qsmaskinitnext bit masks.
4153 * Note that this function is special in that it is invoked directly
4154 * from the outgoing CPU rather than from the cpuhp_step mechanism.
4155 * This is because this function must be invoked at a precise location.
4157 void rcu_report_dead(unsigned int cpu)
4159 unsigned long flags;
4161 struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
4162 struct rcu_node *rnp = rdp->mynode; /* Outgoing CPU's rdp & rnp. */
4164 /* QS for any half-done expedited grace period. */
4166 rcu_report_exp_rdp(this_cpu_ptr(&rcu_data));
4168 rcu_preempt_deferred_qs(current);
4170 /* Remove outgoing CPU from mask in the leaf rcu_node structure. */
4171 mask = rdp->grpmask;
4172 WRITE_ONCE(rnp->ofl_seq, rnp->ofl_seq + 1);
4173 WARN_ON_ONCE(!(rnp->ofl_seq & 0x1));
4174 smp_mb(); // Pair with rcu_gp_cleanup()'s ->ofl_seq barrier().
4175 raw_spin_lock(&rcu_state.ofl_lock);
4176 raw_spin_lock_irqsave_rcu_node(rnp, flags); /* Enforce GP memory-order guarantee. */
4177 rdp->rcu_ofl_gp_seq = READ_ONCE(rcu_state.gp_seq);
4178 rdp->rcu_ofl_gp_flags = READ_ONCE(rcu_state.gp_flags);
4179 if (rnp->qsmask & mask) { /* RCU waiting on outgoing CPU? */
4180 /* Report quiescent state -before- changing ->qsmaskinitnext! */
4181 rcu_report_qs_rnp(mask, rnp, rnp->gp_seq, flags);
4182 raw_spin_lock_irqsave_rcu_node(rnp, flags);
4184 WRITE_ONCE(rnp->qsmaskinitnext, rnp->qsmaskinitnext & ~mask);
4185 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4186 raw_spin_unlock(&rcu_state.ofl_lock);
4187 smp_mb(); // Pair with rcu_gp_cleanup()'s ->ofl_seq barrier().
4188 WRITE_ONCE(rnp->ofl_seq, rnp->ofl_seq + 1);
4189 WARN_ON_ONCE(rnp->ofl_seq & 0x1);
4191 rdp->cpu_started = false;
4194 #ifdef CONFIG_HOTPLUG_CPU
4196 * The outgoing CPU has just passed through the dying-idle state, and we
4197 * are being invoked from the CPU that was IPIed to continue the offline
4198 * operation. Migrate the outgoing CPU's callbacks to the current CPU.
4200 void rcutree_migrate_callbacks(int cpu)
4202 unsigned long flags;
4203 struct rcu_data *my_rdp;
4204 struct rcu_node *my_rnp;
4205 struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
4208 if (rcu_segcblist_is_offloaded(&rdp->cblist) ||
4209 rcu_segcblist_empty(&rdp->cblist))
4210 return; /* No callbacks to migrate. */
4212 local_irq_save(flags);
4213 my_rdp = this_cpu_ptr(&rcu_data);
4214 my_rnp = my_rdp->mynode;
4215 rcu_nocb_lock(my_rdp); /* irqs already disabled. */
4216 WARN_ON_ONCE(!rcu_nocb_flush_bypass(my_rdp, NULL, jiffies));
4217 raw_spin_lock_rcu_node(my_rnp); /* irqs already disabled. */
4218 /* Leverage recent GPs and set GP for new callbacks. */
4219 needwake = rcu_advance_cbs(my_rnp, rdp) ||
4220 rcu_advance_cbs(my_rnp, my_rdp);
4221 rcu_segcblist_merge(&my_rdp->cblist, &rdp->cblist);
4222 needwake = needwake || rcu_advance_cbs(my_rnp, my_rdp);
4223 rcu_segcblist_disable(&rdp->cblist);
4224 WARN_ON_ONCE(rcu_segcblist_empty(&my_rdp->cblist) !=
4225 !rcu_segcblist_n_cbs(&my_rdp->cblist));
4226 if (rcu_segcblist_is_offloaded(&my_rdp->cblist)) {
4227 raw_spin_unlock_rcu_node(my_rnp); /* irqs remain disabled. */
4228 __call_rcu_nocb_wake(my_rdp, true, flags);
4230 rcu_nocb_unlock(my_rdp); /* irqs remain disabled. */
4231 raw_spin_unlock_irqrestore_rcu_node(my_rnp, flags);
4234 rcu_gp_kthread_wake();
4235 lockdep_assert_irqs_enabled();
4236 WARN_ONCE(rcu_segcblist_n_cbs(&rdp->cblist) != 0 ||
4237 !rcu_segcblist_empty(&rdp->cblist),
4238 "rcu_cleanup_dead_cpu: Callbacks on offline CPU %d: qlen=%lu, 1stCB=%p\n",
4239 cpu, rcu_segcblist_n_cbs(&rdp->cblist),
4240 rcu_segcblist_first_cb(&rdp->cblist));
4245 * On non-huge systems, use expedited RCU grace periods to make suspend
4246 * and hibernation run faster.
4248 static int rcu_pm_notify(struct notifier_block *self,
4249 unsigned long action, void *hcpu)
4252 case PM_HIBERNATION_PREPARE:
4253 case PM_SUSPEND_PREPARE:
4256 case PM_POST_HIBERNATION:
4257 case PM_POST_SUSPEND:
4258 rcu_unexpedite_gp();
4267 * Spawn the kthreads that handle RCU's grace periods.
4269 static int __init rcu_spawn_gp_kthread(void)
4271 unsigned long flags;
4272 int kthread_prio_in = kthread_prio;
4273 struct rcu_node *rnp;
4274 struct sched_param sp;
4275 struct task_struct *t;
4277 /* Force priority into range. */
4278 if (IS_ENABLED(CONFIG_RCU_BOOST) && kthread_prio < 2
4279 && IS_BUILTIN(CONFIG_RCU_TORTURE_TEST))
4281 else if (IS_ENABLED(CONFIG_RCU_BOOST) && kthread_prio < 1)
4283 else if (kthread_prio < 0)
4285 else if (kthread_prio > 99)
4288 if (kthread_prio != kthread_prio_in)
4289 pr_alert("rcu_spawn_gp_kthread(): Limited prio to %d from %d\n",
4290 kthread_prio, kthread_prio_in);
4292 rcu_scheduler_fully_active = 1;
4293 t = kthread_create(rcu_gp_kthread, NULL, "%s", rcu_state.name);
4294 if (WARN_ONCE(IS_ERR(t), "%s: Could not start grace-period kthread, OOM is now expected behavior\n", __func__))
4297 sp.sched_priority = kthread_prio;
4298 sched_setscheduler_nocheck(t, SCHED_FIFO, &sp);
4300 rnp = rcu_get_root();
4301 raw_spin_lock_irqsave_rcu_node(rnp, flags);
4302 WRITE_ONCE(rcu_state.gp_activity, jiffies);
4303 WRITE_ONCE(rcu_state.gp_req_activity, jiffies);
4304 // Reset .gp_activity and .gp_req_activity before setting .gp_kthread.
4305 smp_store_release(&rcu_state.gp_kthread, t); /* ^^^ */
4306 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
4308 rcu_spawn_nocb_kthreads();
4309 rcu_spawn_boost_kthreads();
4312 early_initcall(rcu_spawn_gp_kthread);
4315 * This function is invoked towards the end of the scheduler's
4316 * initialization process. Before this is called, the idle task might
4317 * contain synchronous grace-period primitives (during which time, this idle
4318 * task is booting the system, and such primitives are no-ops). After this
4319 * function is called, any synchronous grace-period primitives are run as
4320 * expedited, with the requesting task driving the grace period forward.
4321 * A later core_initcall() rcu_set_runtime_mode() will switch to full
4322 * runtime RCU functionality.
4324 void rcu_scheduler_starting(void)
4326 WARN_ON(num_online_cpus() != 1);
4327 WARN_ON(nr_context_switches() > 0);
4328 rcu_test_sync_prims();
4329 rcu_scheduler_active = RCU_SCHEDULER_INIT;
4330 rcu_test_sync_prims();
4334 * Helper function for rcu_init() that initializes the rcu_state structure.
4336 static void __init rcu_init_one(void)
4338 static const char * const buf[] = RCU_NODE_NAME_INIT;
4339 static const char * const fqs[] = RCU_FQS_NAME_INIT;
4340 static struct lock_class_key rcu_node_class[RCU_NUM_LVLS];
4341 static struct lock_class_key rcu_fqs_class[RCU_NUM_LVLS];
4343 int levelspread[RCU_NUM_LVLS]; /* kids/node in each level. */
4347 struct rcu_node *rnp;
4349 BUILD_BUG_ON(RCU_NUM_LVLS > ARRAY_SIZE(buf)); /* Fix buf[] init! */
4351 /* Silence gcc 4.8 false positive about array index out of range. */
4352 if (rcu_num_lvls <= 0 || rcu_num_lvls > RCU_NUM_LVLS)
4353 panic("rcu_init_one: rcu_num_lvls out of range");
4355 /* Initialize the level-tracking arrays. */
4357 for (i = 1; i < rcu_num_lvls; i++)
4358 rcu_state.level[i] =
4359 rcu_state.level[i - 1] + num_rcu_lvl[i - 1];
4360 rcu_init_levelspread(levelspread, num_rcu_lvl);
4362 /* Initialize the elements themselves, starting from the leaves. */
4364 for (i = rcu_num_lvls - 1; i >= 0; i--) {
4365 cpustride *= levelspread[i];
4366 rnp = rcu_state.level[i];
4367 for (j = 0; j < num_rcu_lvl[i]; j++, rnp++) {
4368 raw_spin_lock_init(&ACCESS_PRIVATE(rnp, lock));
4369 lockdep_set_class_and_name(&ACCESS_PRIVATE(rnp, lock),
4370 &rcu_node_class[i], buf[i]);
4371 raw_spin_lock_init(&rnp->fqslock);
4372 lockdep_set_class_and_name(&rnp->fqslock,
4373 &rcu_fqs_class[i], fqs[i]);
4374 rnp->gp_seq = rcu_state.gp_seq;
4375 rnp->gp_seq_needed = rcu_state.gp_seq;
4376 rnp->completedqs = rcu_state.gp_seq;
4378 rnp->qsmaskinit = 0;
4379 rnp->grplo = j * cpustride;
4380 rnp->grphi = (j + 1) * cpustride - 1;
4381 if (rnp->grphi >= nr_cpu_ids)
4382 rnp->grphi = nr_cpu_ids - 1;
4388 rnp->grpnum = j % levelspread[i - 1];
4389 rnp->grpmask = BIT(rnp->grpnum);
4390 rnp->parent = rcu_state.level[i - 1] +
4391 j / levelspread[i - 1];
4394 INIT_LIST_HEAD(&rnp->blkd_tasks);
4395 rcu_init_one_nocb(rnp);
4396 init_waitqueue_head(&rnp->exp_wq[0]);
4397 init_waitqueue_head(&rnp->exp_wq[1]);
4398 init_waitqueue_head(&rnp->exp_wq[2]);
4399 init_waitqueue_head(&rnp->exp_wq[3]);
4400 spin_lock_init(&rnp->exp_lock);
4404 init_swait_queue_head(&rcu_state.gp_wq);
4405 init_swait_queue_head(&rcu_state.expedited_wq);
4406 rnp = rcu_first_leaf_node();
4407 for_each_possible_cpu(i) {
4408 while (i > rnp->grphi)
4410 per_cpu_ptr(&rcu_data, i)->mynode = rnp;
4411 rcu_boot_init_percpu_data(i);
4416 * Compute the rcu_node tree geometry from kernel parameters. This cannot
4417 * replace the definitions in tree.h because those are needed to size
4418 * the ->node array in the rcu_state structure.
4420 static void __init rcu_init_geometry(void)
4424 int rcu_capacity[RCU_NUM_LVLS];
4427 * Initialize any unspecified boot parameters.
4428 * The default values of jiffies_till_first_fqs and
4429 * jiffies_till_next_fqs are set to the RCU_JIFFIES_TILL_FORCE_QS
4430 * value, which is a function of HZ, then adding one for each
4431 * RCU_JIFFIES_FQS_DIV CPUs that might be on the system.
4433 d = RCU_JIFFIES_TILL_FORCE_QS + nr_cpu_ids / RCU_JIFFIES_FQS_DIV;
4434 if (jiffies_till_first_fqs == ULONG_MAX)
4435 jiffies_till_first_fqs = d;
4436 if (jiffies_till_next_fqs == ULONG_MAX)
4437 jiffies_till_next_fqs = d;
4438 adjust_jiffies_till_sched_qs();
4440 /* If the compile-time values are accurate, just leave. */
4441 if (rcu_fanout_leaf == RCU_FANOUT_LEAF &&
4442 nr_cpu_ids == NR_CPUS)
4444 pr_info("Adjusting geometry for rcu_fanout_leaf=%d, nr_cpu_ids=%u\n",
4445 rcu_fanout_leaf, nr_cpu_ids);
4448 * The boot-time rcu_fanout_leaf parameter must be at least two
4449 * and cannot exceed the number of bits in the rcu_node masks.
4450 * Complain and fall back to the compile-time values if this
4451 * limit is exceeded.
4453 if (rcu_fanout_leaf < 2 ||
4454 rcu_fanout_leaf > sizeof(unsigned long) * 8) {
4455 rcu_fanout_leaf = RCU_FANOUT_LEAF;
4461 * Compute number of nodes that can be handled an rcu_node tree
4462 * with the given number of levels.
4464 rcu_capacity[0] = rcu_fanout_leaf;
4465 for (i = 1; i < RCU_NUM_LVLS; i++)
4466 rcu_capacity[i] = rcu_capacity[i - 1] * RCU_FANOUT;
4469 * The tree must be able to accommodate the configured number of CPUs.
4470 * If this limit is exceeded, fall back to the compile-time values.
4472 if (nr_cpu_ids > rcu_capacity[RCU_NUM_LVLS - 1]) {
4473 rcu_fanout_leaf = RCU_FANOUT_LEAF;
4478 /* Calculate the number of levels in the tree. */
4479 for (i = 0; nr_cpu_ids > rcu_capacity[i]; i++) {
4481 rcu_num_lvls = i + 1;
4483 /* Calculate the number of rcu_nodes at each level of the tree. */
4484 for (i = 0; i < rcu_num_lvls; i++) {
4485 int cap = rcu_capacity[(rcu_num_lvls - 1) - i];
4486 num_rcu_lvl[i] = DIV_ROUND_UP(nr_cpu_ids, cap);
4489 /* Calculate the total number of rcu_node structures. */
4491 for (i = 0; i < rcu_num_lvls; i++)
4492 rcu_num_nodes += num_rcu_lvl[i];
4496 * Dump out the structure of the rcu_node combining tree associated
4497 * with the rcu_state structure.
4499 static void __init rcu_dump_rcu_node_tree(void)
4502 struct rcu_node *rnp;
4504 pr_info("rcu_node tree layout dump\n");
4506 rcu_for_each_node_breadth_first(rnp) {
4507 if (rnp->level != level) {
4512 pr_cont("%d:%d ^%d ", rnp->grplo, rnp->grphi, rnp->grpnum);
4517 struct workqueue_struct *rcu_gp_wq;
4518 struct workqueue_struct *rcu_par_gp_wq;
4520 static void __init kfree_rcu_batch_init(void)
4525 for_each_possible_cpu(cpu) {
4526 struct kfree_rcu_cpu *krcp = per_cpu_ptr(&krc, cpu);
4528 for (i = 0; i < KFREE_N_BATCHES; i++) {
4529 INIT_RCU_WORK(&krcp->krw_arr[i].rcu_work, kfree_rcu_work);
4530 krcp->krw_arr[i].krcp = krcp;
4533 INIT_DELAYED_WORK(&krcp->monitor_work, kfree_rcu_monitor);
4534 INIT_WORK(&krcp->page_cache_work, fill_page_cache_func);
4535 krcp->initialized = true;
4537 if (register_shrinker(&kfree_rcu_shrinker))
4538 pr_err("Failed to register kfree_rcu() shrinker!\n");
4541 void __init rcu_init(void)
4545 rcu_early_boot_tests();
4547 kfree_rcu_batch_init();
4548 rcu_bootup_announce();
4549 rcu_init_geometry();
4552 rcu_dump_rcu_node_tree();
4554 open_softirq(RCU_SOFTIRQ, rcu_core_si);
4557 * We don't need protection against CPU-hotplug here because
4558 * this is called early in boot, before either interrupts
4559 * or the scheduler are operational.
4561 pm_notifier(rcu_pm_notify, 0);
4562 for_each_online_cpu(cpu) {
4563 rcutree_prepare_cpu(cpu);
4564 rcu_cpu_starting(cpu);
4565 rcutree_online_cpu(cpu);
4568 /* Create workqueue for expedited GPs and for Tree SRCU. */
4569 rcu_gp_wq = alloc_workqueue("rcu_gp", WQ_MEM_RECLAIM, 0);
4570 WARN_ON(!rcu_gp_wq);
4571 rcu_par_gp_wq = alloc_workqueue("rcu_par_gp", WQ_MEM_RECLAIM, 0);
4572 WARN_ON(!rcu_par_gp_wq);
4575 /* Fill in default value for rcutree.qovld boot parameter. */
4576 /* -After- the rcu_node ->lock fields are initialized! */
4578 qovld_calc = DEFAULT_RCU_QOVLD_MULT * qhimark;
4583 #include "tree_stall.h"
4584 #include "tree_exp.h"
4585 #include "tree_plugin.h"