2 * Read-Copy Update mechanism for mutual exclusion
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, you can access it online at
16 * http://www.gnu.org/licenses/gpl-2.0.html.
18 * Copyright IBM Corporation, 2008
20 * Authors: Dipankar Sarma <dipankar@in.ibm.com>
21 * Manfred Spraul <manfred@colorfullife.com>
22 * Paul E. McKenney <paulmck@linux.vnet.ibm.com> Hierarchical version
24 * Based on the original work by Paul McKenney <paulmck@us.ibm.com>
25 * and inputs from Rusty Russell, Andrea Arcangeli and Andi Kleen.
27 * For detailed explanation of Read-Copy Update mechanism see -
30 #include <linux/types.h>
31 #include <linux/kernel.h>
32 #include <linux/init.h>
33 #include <linux/spinlock.h>
34 #include <linux/smp.h>
35 #include <linux/rcupdate.h>
36 #include <linux/interrupt.h>
37 #include <linux/sched.h>
38 #include <linux/nmi.h>
39 #include <linux/atomic.h>
40 #include <linux/bitops.h>
41 #include <linux/export.h>
42 #include <linux/completion.h>
43 #include <linux/moduleparam.h>
44 #include <linux/module.h>
45 #include <linux/percpu.h>
46 #include <linux/notifier.h>
47 #include <linux/cpu.h>
48 #include <linux/mutex.h>
49 #include <linux/time.h>
50 #include <linux/kernel_stat.h>
51 #include <linux/wait.h>
52 #include <linux/kthread.h>
53 #include <linux/prefetch.h>
54 #include <linux/delay.h>
55 #include <linux/stop_machine.h>
56 #include <linux/random.h>
57 #include <linux/trace_events.h>
58 #include <linux/suspend.h>
63 MODULE_ALIAS("rcutree");
64 #ifdef MODULE_PARAM_PREFIX
65 #undef MODULE_PARAM_PREFIX
67 #define MODULE_PARAM_PREFIX "rcutree."
69 /* Data structures. */
71 static struct lock_class_key rcu_node_class[RCU_NUM_LVLS];
72 static struct lock_class_key rcu_fqs_class[RCU_NUM_LVLS];
73 static struct lock_class_key rcu_exp_class[RCU_NUM_LVLS];
76 * In order to export the rcu_state name to the tracing tools, it
77 * needs to be added in the __tracepoint_string section.
78 * This requires defining a separate variable tp_<sname>_varname
79 * that points to the string being used, and this will allow
80 * the tracing userspace tools to be able to decipher the string
81 * address to the matching string.
84 # define DEFINE_RCU_TPS(sname) \
85 static char sname##_varname[] = #sname; \
86 static const char *tp_##sname##_varname __used __tracepoint_string = sname##_varname;
87 # define RCU_STATE_NAME(sname) sname##_varname
89 # define DEFINE_RCU_TPS(sname)
90 # define RCU_STATE_NAME(sname) __stringify(sname)
93 #define RCU_STATE_INITIALIZER(sname, sabbr, cr) \
94 DEFINE_RCU_TPS(sname) \
95 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rcu_data, sname##_data); \
96 struct rcu_state sname##_state = { \
97 .level = { &sname##_state.node[0] }, \
98 .rda = &sname##_data, \
100 .fqs_state = RCU_GP_IDLE, \
101 .gpnum = 0UL - 300UL, \
102 .completed = 0UL - 300UL, \
103 .orphan_lock = __RAW_SPIN_LOCK_UNLOCKED(&sname##_state.orphan_lock), \
104 .orphan_nxttail = &sname##_state.orphan_nxtlist, \
105 .orphan_donetail = &sname##_state.orphan_donelist, \
106 .barrier_mutex = __MUTEX_INITIALIZER(sname##_state.barrier_mutex), \
107 .name = RCU_STATE_NAME(sname), \
111 RCU_STATE_INITIALIZER(rcu_sched, 's', call_rcu_sched);
112 RCU_STATE_INITIALIZER(rcu_bh, 'b', call_rcu_bh);
114 static struct rcu_state *const rcu_state_p;
115 static struct rcu_data __percpu *const rcu_data_p;
116 LIST_HEAD(rcu_struct_flavors);
118 /* Dump rcu_node combining tree at boot to verify correct setup. */
119 static bool dump_tree;
120 module_param(dump_tree, bool, 0444);
121 /* Control rcu_node-tree auto-balancing at boot time. */
122 static bool rcu_fanout_exact;
123 module_param(rcu_fanout_exact, bool, 0444);
124 /* Increase (but not decrease) the RCU_FANOUT_LEAF at boot time. */
125 static int rcu_fanout_leaf = RCU_FANOUT_LEAF;
126 module_param(rcu_fanout_leaf, int, 0444);
127 int rcu_num_lvls __read_mostly = RCU_NUM_LVLS;
128 /* Number of rcu_nodes at specified level. */
129 static int num_rcu_lvl[] = NUM_RCU_LVL_INIT;
130 int rcu_num_nodes __read_mostly = NUM_RCU_NODES; /* Total # rcu_nodes in use. */
133 * The rcu_scheduler_active variable transitions from zero to one just
134 * before the first task is spawned. So when this variable is zero, RCU
135 * can assume that there is but one task, allowing RCU to (for example)
136 * optimize synchronize_sched() to a simple barrier(). When this variable
137 * is one, RCU must actually do all the hard work required to detect real
138 * grace periods. This variable is also used to suppress boot-time false
139 * positives from lockdep-RCU error checking.
141 int rcu_scheduler_active __read_mostly;
142 EXPORT_SYMBOL_GPL(rcu_scheduler_active);
145 * The rcu_scheduler_fully_active variable transitions from zero to one
146 * during the early_initcall() processing, which is after the scheduler
147 * is capable of creating new tasks. So RCU processing (for example,
148 * creating tasks for RCU priority boosting) must be delayed until after
149 * rcu_scheduler_fully_active transitions from zero to one. We also
150 * currently delay invocation of any RCU callbacks until after this point.
152 * It might later prove better for people registering RCU callbacks during
153 * early boot to take responsibility for these callbacks, but one step at
156 static int rcu_scheduler_fully_active __read_mostly;
158 static void rcu_init_new_rnp(struct rcu_node *rnp_leaf);
159 static void rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf);
160 static void rcu_boost_kthread_setaffinity(struct rcu_node *rnp, int outgoingcpu);
161 static void invoke_rcu_core(void);
162 static void invoke_rcu_callbacks(struct rcu_state *rsp, struct rcu_data *rdp);
163 static void rcu_report_exp_rdp(struct rcu_state *rsp,
164 struct rcu_data *rdp, bool wake);
166 /* rcuc/rcub kthread realtime priority */
167 #ifdef CONFIG_RCU_KTHREAD_PRIO
168 static int kthread_prio = CONFIG_RCU_KTHREAD_PRIO;
169 #else /* #ifdef CONFIG_RCU_KTHREAD_PRIO */
170 static int kthread_prio = IS_ENABLED(CONFIG_RCU_BOOST) ? 1 : 0;
171 #endif /* #else #ifdef CONFIG_RCU_KTHREAD_PRIO */
172 module_param(kthread_prio, int, 0644);
174 /* Delay in jiffies for grace-period initialization delays, debug only. */
176 #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_PREINIT
177 static int gp_preinit_delay = CONFIG_RCU_TORTURE_TEST_SLOW_PREINIT_DELAY;
178 module_param(gp_preinit_delay, int, 0644);
179 #else /* #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_PREINIT */
180 static const int gp_preinit_delay;
181 #endif /* #else #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_PREINIT */
183 #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_INIT
184 static int gp_init_delay = CONFIG_RCU_TORTURE_TEST_SLOW_INIT_DELAY;
185 module_param(gp_init_delay, int, 0644);
186 #else /* #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_INIT */
187 static const int gp_init_delay;
188 #endif /* #else #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_INIT */
190 #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_CLEANUP
191 static int gp_cleanup_delay = CONFIG_RCU_TORTURE_TEST_SLOW_CLEANUP_DELAY;
192 module_param(gp_cleanup_delay, int, 0644);
193 #else /* #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_CLEANUP */
194 static const int gp_cleanup_delay;
195 #endif /* #else #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_CLEANUP */
198 * Number of grace periods between delays, normalized by the duration of
199 * the delay. The longer the the delay, the more the grace periods between
200 * each delay. The reason for this normalization is that it means that,
201 * for non-zero delays, the overall slowdown of grace periods is constant
202 * regardless of the duration of the delay. This arrangement balances
203 * the need for long delays to increase some race probabilities with the
204 * need for fast grace periods to increase other race probabilities.
206 #define PER_RCU_NODE_PERIOD 3 /* Number of grace periods between delays. */
209 * Track the rcutorture test sequence number and the update version
210 * number within a given test. The rcutorture_testseq is incremented
211 * on every rcutorture module load and unload, so has an odd value
212 * when a test is running. The rcutorture_vernum is set to zero
213 * when rcutorture starts and is incremented on each rcutorture update.
214 * These variables enable correlating rcutorture output with the
215 * RCU tracing information.
217 unsigned long rcutorture_testseq;
218 unsigned long rcutorture_vernum;
221 * Compute the mask of online CPUs for the specified rcu_node structure.
222 * This will not be stable unless the rcu_node structure's ->lock is
223 * held, but the bit corresponding to the current CPU will be stable
226 unsigned long rcu_rnp_online_cpus(struct rcu_node *rnp)
228 return READ_ONCE(rnp->qsmaskinitnext);
232 * Return true if an RCU grace period is in progress. The READ_ONCE()s
233 * permit this function to be invoked without holding the root rcu_node
234 * structure's ->lock, but of course results can be subject to change.
236 static int rcu_gp_in_progress(struct rcu_state *rsp)
238 return READ_ONCE(rsp->completed) != READ_ONCE(rsp->gpnum);
242 * Note a quiescent state. Because we do not need to know
243 * how many quiescent states passed, just if there was at least
244 * one since the start of the grace period, this just sets a flag.
245 * The caller must have disabled preemption.
247 void rcu_sched_qs(void)
251 if (__this_cpu_read(rcu_sched_data.cpu_no_qs.s)) {
252 trace_rcu_grace_period(TPS("rcu_sched"),
253 __this_cpu_read(rcu_sched_data.gpnum),
255 __this_cpu_write(rcu_sched_data.cpu_no_qs.b.norm, false);
256 if (!__this_cpu_read(rcu_sched_data.cpu_no_qs.b.exp))
258 local_irq_save(flags);
259 if (__this_cpu_read(rcu_sched_data.cpu_no_qs.b.exp)) {
260 __this_cpu_write(rcu_sched_data.cpu_no_qs.b.exp, false);
261 rcu_report_exp_rdp(&rcu_sched_state,
262 this_cpu_ptr(&rcu_sched_data),
265 local_irq_restore(flags);
271 if (__this_cpu_read(rcu_bh_data.cpu_no_qs.s)) {
272 trace_rcu_grace_period(TPS("rcu_bh"),
273 __this_cpu_read(rcu_bh_data.gpnum),
275 __this_cpu_write(rcu_bh_data.cpu_no_qs.b.norm, false);
279 static DEFINE_PER_CPU(int, rcu_sched_qs_mask);
281 static DEFINE_PER_CPU(struct rcu_dynticks, rcu_dynticks) = {
282 .dynticks_nesting = DYNTICK_TASK_EXIT_IDLE,
283 .dynticks = ATOMIC_INIT(1),
284 #ifdef CONFIG_NO_HZ_FULL_SYSIDLE
285 .dynticks_idle_nesting = DYNTICK_TASK_NEST_VALUE,
286 .dynticks_idle = ATOMIC_INIT(1),
287 #endif /* #ifdef CONFIG_NO_HZ_FULL_SYSIDLE */
290 DEFINE_PER_CPU_SHARED_ALIGNED(unsigned long, rcu_qs_ctr);
291 EXPORT_PER_CPU_SYMBOL_GPL(rcu_qs_ctr);
294 * Let the RCU core know that this CPU has gone through the scheduler,
295 * which is a quiescent state. This is called when the need for a
296 * quiescent state is urgent, so we burn an atomic operation and full
297 * memory barriers to let the RCU core know about it, regardless of what
298 * this CPU might (or might not) do in the near future.
300 * We inform the RCU core by emulating a zero-duration dyntick-idle
301 * period, which we in turn do by incrementing the ->dynticks counter
304 static void rcu_momentary_dyntick_idle(void)
307 struct rcu_data *rdp;
308 struct rcu_dynticks *rdtp;
310 struct rcu_state *rsp;
312 local_irq_save(flags);
315 * Yes, we can lose flag-setting operations. This is OK, because
316 * the flag will be set again after some delay.
318 resched_mask = raw_cpu_read(rcu_sched_qs_mask);
319 raw_cpu_write(rcu_sched_qs_mask, 0);
321 /* Find the flavor that needs a quiescent state. */
322 for_each_rcu_flavor(rsp) {
323 rdp = raw_cpu_ptr(rsp->rda);
324 if (!(resched_mask & rsp->flavor_mask))
326 smp_mb(); /* rcu_sched_qs_mask before cond_resched_completed. */
327 if (READ_ONCE(rdp->mynode->completed) !=
328 READ_ONCE(rdp->cond_resched_completed))
332 * Pretend to be momentarily idle for the quiescent state.
333 * This allows the grace-period kthread to record the
334 * quiescent state, with no need for this CPU to do anything
337 rdtp = this_cpu_ptr(&rcu_dynticks);
338 smp_mb__before_atomic(); /* Earlier stuff before QS. */
339 atomic_add(2, &rdtp->dynticks); /* QS. */
340 smp_mb__after_atomic(); /* Later stuff after QS. */
343 local_irq_restore(flags);
347 * Note a context switch. This is a quiescent state for RCU-sched,
348 * and requires special handling for preemptible RCU.
349 * The caller must have disabled preemption.
351 void rcu_note_context_switch(void)
353 trace_rcu_utilization(TPS("Start context switch"));
355 rcu_preempt_note_context_switch();
356 if (unlikely(raw_cpu_read(rcu_sched_qs_mask)))
357 rcu_momentary_dyntick_idle();
358 trace_rcu_utilization(TPS("End context switch"));
360 EXPORT_SYMBOL_GPL(rcu_note_context_switch);
363 * Register a quiescent state for all RCU flavors. If there is an
364 * emergency, invoke rcu_momentary_dyntick_idle() to do a heavy-weight
365 * dyntick-idle quiescent state visible to other CPUs (but only for those
366 * RCU flavors in desperate need of a quiescent state, which will normally
367 * be none of them). Either way, do a lightweight quiescent state for
370 void rcu_all_qs(void)
372 if (unlikely(raw_cpu_read(rcu_sched_qs_mask)))
373 rcu_momentary_dyntick_idle();
374 this_cpu_inc(rcu_qs_ctr);
376 EXPORT_SYMBOL_GPL(rcu_all_qs);
378 static long blimit = 10; /* Maximum callbacks per rcu_do_batch. */
379 static long qhimark = 10000; /* If this many pending, ignore blimit. */
380 static long qlowmark = 100; /* Once only this many pending, use blimit. */
382 module_param(blimit, long, 0444);
383 module_param(qhimark, long, 0444);
384 module_param(qlowmark, long, 0444);
386 static ulong jiffies_till_first_fqs = ULONG_MAX;
387 static ulong jiffies_till_next_fqs = ULONG_MAX;
389 module_param(jiffies_till_first_fqs, ulong, 0644);
390 module_param(jiffies_till_next_fqs, ulong, 0644);
393 * How long the grace period must be before we start recruiting
394 * quiescent-state help from rcu_note_context_switch().
396 static ulong jiffies_till_sched_qs = HZ / 20;
397 module_param(jiffies_till_sched_qs, ulong, 0644);
399 static bool rcu_start_gp_advanced(struct rcu_state *rsp, struct rcu_node *rnp,
400 struct rcu_data *rdp);
401 static void force_qs_rnp(struct rcu_state *rsp,
402 int (*f)(struct rcu_data *rsp, bool *isidle,
403 unsigned long *maxj),
404 bool *isidle, unsigned long *maxj);
405 static void force_quiescent_state(struct rcu_state *rsp);
406 static int rcu_pending(void);
409 * Return the number of RCU batches started thus far for debug & stats.
411 unsigned long rcu_batches_started(void)
413 return rcu_state_p->gpnum;
415 EXPORT_SYMBOL_GPL(rcu_batches_started);
418 * Return the number of RCU-sched batches started thus far for debug & stats.
420 unsigned long rcu_batches_started_sched(void)
422 return rcu_sched_state.gpnum;
424 EXPORT_SYMBOL_GPL(rcu_batches_started_sched);
427 * Return the number of RCU BH batches started thus far for debug & stats.
429 unsigned long rcu_batches_started_bh(void)
431 return rcu_bh_state.gpnum;
433 EXPORT_SYMBOL_GPL(rcu_batches_started_bh);
436 * Return the number of RCU batches completed thus far for debug & stats.
438 unsigned long rcu_batches_completed(void)
440 return rcu_state_p->completed;
442 EXPORT_SYMBOL_GPL(rcu_batches_completed);
445 * Return the number of RCU-sched batches completed thus far for debug & stats.
447 unsigned long rcu_batches_completed_sched(void)
449 return rcu_sched_state.completed;
451 EXPORT_SYMBOL_GPL(rcu_batches_completed_sched);
454 * Return the number of RCU BH batches completed thus far for debug & stats.
456 unsigned long rcu_batches_completed_bh(void)
458 return rcu_bh_state.completed;
460 EXPORT_SYMBOL_GPL(rcu_batches_completed_bh);
463 * Force a quiescent state.
465 void rcu_force_quiescent_state(void)
467 force_quiescent_state(rcu_state_p);
469 EXPORT_SYMBOL_GPL(rcu_force_quiescent_state);
472 * Force a quiescent state for RCU BH.
474 void rcu_bh_force_quiescent_state(void)
476 force_quiescent_state(&rcu_bh_state);
478 EXPORT_SYMBOL_GPL(rcu_bh_force_quiescent_state);
481 * Force a quiescent state for RCU-sched.
483 void rcu_sched_force_quiescent_state(void)
485 force_quiescent_state(&rcu_sched_state);
487 EXPORT_SYMBOL_GPL(rcu_sched_force_quiescent_state);
490 * Show the state of the grace-period kthreads.
492 void show_rcu_gp_kthreads(void)
494 struct rcu_state *rsp;
496 for_each_rcu_flavor(rsp) {
497 pr_info("%s: wait state: %d ->state: %#lx\n",
498 rsp->name, rsp->gp_state, rsp->gp_kthread->state);
499 /* sched_show_task(rsp->gp_kthread); */
502 EXPORT_SYMBOL_GPL(show_rcu_gp_kthreads);
505 * Record the number of times rcutorture tests have been initiated and
506 * terminated. This information allows the debugfs tracing stats to be
507 * correlated to the rcutorture messages, even when the rcutorture module
508 * is being repeatedly loaded and unloaded. In other words, we cannot
509 * store this state in rcutorture itself.
511 void rcutorture_record_test_transition(void)
513 rcutorture_testseq++;
514 rcutorture_vernum = 0;
516 EXPORT_SYMBOL_GPL(rcutorture_record_test_transition);
519 * Send along grace-period-related data for rcutorture diagnostics.
521 void rcutorture_get_gp_data(enum rcutorture_type test_type, int *flags,
522 unsigned long *gpnum, unsigned long *completed)
524 struct rcu_state *rsp = NULL;
533 case RCU_SCHED_FLAVOR:
534 rsp = &rcu_sched_state;
540 *flags = READ_ONCE(rsp->gp_flags);
541 *gpnum = READ_ONCE(rsp->gpnum);
542 *completed = READ_ONCE(rsp->completed);
549 EXPORT_SYMBOL_GPL(rcutorture_get_gp_data);
552 * Record the number of writer passes through the current rcutorture test.
553 * This is also used to correlate debugfs tracing stats with the rcutorture
556 void rcutorture_record_progress(unsigned long vernum)
560 EXPORT_SYMBOL_GPL(rcutorture_record_progress);
563 * Does the CPU have callbacks ready to be invoked?
566 cpu_has_callbacks_ready_to_invoke(struct rcu_data *rdp)
568 return &rdp->nxtlist != rdp->nxttail[RCU_DONE_TAIL] &&
569 rdp->nxttail[RCU_DONE_TAIL] != NULL;
573 * Return the root node of the specified rcu_state structure.
575 static struct rcu_node *rcu_get_root(struct rcu_state *rsp)
577 return &rsp->node[0];
581 * Is there any need for future grace periods?
582 * Interrupts must be disabled. If the caller does not hold the root
583 * rnp_node structure's ->lock, the results are advisory only.
585 static int rcu_future_needs_gp(struct rcu_state *rsp)
587 struct rcu_node *rnp = rcu_get_root(rsp);
588 int idx = (READ_ONCE(rnp->completed) + 1) & 0x1;
589 int *fp = &rnp->need_future_gp[idx];
591 return READ_ONCE(*fp);
595 * Does the current CPU require a not-yet-started grace period?
596 * The caller must have disabled interrupts to prevent races with
597 * normal callback registry.
600 cpu_needs_another_gp(struct rcu_state *rsp, struct rcu_data *rdp)
604 if (rcu_gp_in_progress(rsp))
605 return 0; /* No, a grace period is already in progress. */
606 if (rcu_future_needs_gp(rsp))
607 return 1; /* Yes, a no-CBs CPU needs one. */
608 if (!rdp->nxttail[RCU_NEXT_TAIL])
609 return 0; /* No, this is a no-CBs (or offline) CPU. */
610 if (*rdp->nxttail[RCU_NEXT_READY_TAIL])
611 return 1; /* Yes, this CPU has newly registered callbacks. */
612 for (i = RCU_WAIT_TAIL; i < RCU_NEXT_TAIL; i++)
613 if (rdp->nxttail[i - 1] != rdp->nxttail[i] &&
614 ULONG_CMP_LT(READ_ONCE(rsp->completed),
615 rdp->nxtcompleted[i]))
616 return 1; /* Yes, CBs for future grace period. */
617 return 0; /* No grace period needed. */
621 * rcu_eqs_enter_common - current CPU is moving towards extended quiescent state
623 * If the new value of the ->dynticks_nesting counter now is zero,
624 * we really have entered idle, and must do the appropriate accounting.
625 * The caller must have disabled interrupts.
627 static void rcu_eqs_enter_common(long long oldval, bool user)
629 struct rcu_state *rsp;
630 struct rcu_data *rdp;
631 struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
633 trace_rcu_dyntick(TPS("Start"), oldval, rdtp->dynticks_nesting);
634 if (IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
635 !user && !is_idle_task(current)) {
636 struct task_struct *idle __maybe_unused =
637 idle_task(smp_processor_id());
639 trace_rcu_dyntick(TPS("Error on entry: not idle task"), oldval, 0);
640 ftrace_dump(DUMP_ORIG);
641 WARN_ONCE(1, "Current pid: %d comm: %s / Idle pid: %d comm: %s",
642 current->pid, current->comm,
643 idle->pid, idle->comm); /* must be idle task! */
645 for_each_rcu_flavor(rsp) {
646 rdp = this_cpu_ptr(rsp->rda);
647 do_nocb_deferred_wakeup(rdp);
649 rcu_prepare_for_idle();
650 /* CPUs seeing atomic_inc() must see prior RCU read-side crit sects */
651 smp_mb__before_atomic(); /* See above. */
652 atomic_inc(&rdtp->dynticks);
653 smp_mb__after_atomic(); /* Force ordering with next sojourn. */
654 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
655 atomic_read(&rdtp->dynticks) & 0x1);
656 rcu_dynticks_task_enter();
659 * It is illegal to enter an extended quiescent state while
660 * in an RCU read-side critical section.
662 RCU_LOCKDEP_WARN(lock_is_held(&rcu_lock_map),
663 "Illegal idle entry in RCU read-side critical section.");
664 RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map),
665 "Illegal idle entry in RCU-bh read-side critical section.");
666 RCU_LOCKDEP_WARN(lock_is_held(&rcu_sched_lock_map),
667 "Illegal idle entry in RCU-sched read-side critical section.");
671 * Enter an RCU extended quiescent state, which can be either the
672 * idle loop or adaptive-tickless usermode execution.
674 static void rcu_eqs_enter(bool user)
677 struct rcu_dynticks *rdtp;
679 rdtp = this_cpu_ptr(&rcu_dynticks);
680 oldval = rdtp->dynticks_nesting;
681 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
682 (oldval & DYNTICK_TASK_NEST_MASK) == 0);
683 if ((oldval & DYNTICK_TASK_NEST_MASK) == DYNTICK_TASK_NEST_VALUE) {
684 rdtp->dynticks_nesting = 0;
685 rcu_eqs_enter_common(oldval, user);
687 rdtp->dynticks_nesting -= DYNTICK_TASK_NEST_VALUE;
692 * rcu_idle_enter - inform RCU that current CPU is entering idle
694 * Enter idle mode, in other words, -leave- the mode in which RCU
695 * read-side critical sections can occur. (Though RCU read-side
696 * critical sections can occur in irq handlers in idle, a possibility
697 * handled by irq_enter() and irq_exit().)
699 * We crowbar the ->dynticks_nesting field to zero to allow for
700 * the possibility of usermode upcalls having messed up our count
701 * of interrupt nesting level during the prior busy period.
703 void rcu_idle_enter(void)
707 local_irq_save(flags);
708 rcu_eqs_enter(false);
709 rcu_sysidle_enter(0);
710 local_irq_restore(flags);
712 EXPORT_SYMBOL_GPL(rcu_idle_enter);
714 #ifdef CONFIG_NO_HZ_FULL
716 * rcu_user_enter - inform RCU that we are resuming userspace.
718 * Enter RCU idle mode right before resuming userspace. No use of RCU
719 * is permitted between this call and rcu_user_exit(). This way the
720 * CPU doesn't need to maintain the tick for RCU maintenance purposes
721 * when the CPU runs in userspace.
723 void rcu_user_enter(void)
727 #endif /* CONFIG_NO_HZ_FULL */
730 * rcu_irq_exit - inform RCU that current CPU is exiting irq towards idle
732 * Exit from an interrupt handler, which might possibly result in entering
733 * idle mode, in other words, leaving the mode in which read-side critical
734 * sections can occur.
736 * This code assumes that the idle loop never does anything that might
737 * result in unbalanced calls to irq_enter() and irq_exit(). If your
738 * architecture violates this assumption, RCU will give you what you
739 * deserve, good and hard. But very infrequently and irreproducibly.
741 * Use things like work queues to work around this limitation.
743 * You have been warned.
745 void rcu_irq_exit(void)
749 struct rcu_dynticks *rdtp;
751 local_irq_save(flags);
752 rdtp = this_cpu_ptr(&rcu_dynticks);
753 oldval = rdtp->dynticks_nesting;
754 rdtp->dynticks_nesting--;
755 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
756 rdtp->dynticks_nesting < 0);
757 if (rdtp->dynticks_nesting)
758 trace_rcu_dyntick(TPS("--="), oldval, rdtp->dynticks_nesting);
760 rcu_eqs_enter_common(oldval, true);
761 rcu_sysidle_enter(1);
762 local_irq_restore(flags);
766 * rcu_eqs_exit_common - current CPU moving away from extended quiescent state
768 * If the new value of the ->dynticks_nesting counter was previously zero,
769 * we really have exited idle, and must do the appropriate accounting.
770 * The caller must have disabled interrupts.
772 static void rcu_eqs_exit_common(long long oldval, int user)
774 struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
776 rcu_dynticks_task_exit();
777 smp_mb__before_atomic(); /* Force ordering w/previous sojourn. */
778 atomic_inc(&rdtp->dynticks);
779 /* CPUs seeing atomic_inc() must see later RCU read-side crit sects */
780 smp_mb__after_atomic(); /* See above. */
781 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
782 !(atomic_read(&rdtp->dynticks) & 0x1));
783 rcu_cleanup_after_idle();
784 trace_rcu_dyntick(TPS("End"), oldval, rdtp->dynticks_nesting);
785 if (IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
786 !user && !is_idle_task(current)) {
787 struct task_struct *idle __maybe_unused =
788 idle_task(smp_processor_id());
790 trace_rcu_dyntick(TPS("Error on exit: not idle task"),
791 oldval, rdtp->dynticks_nesting);
792 ftrace_dump(DUMP_ORIG);
793 WARN_ONCE(1, "Current pid: %d comm: %s / Idle pid: %d comm: %s",
794 current->pid, current->comm,
795 idle->pid, idle->comm); /* must be idle task! */
800 * Exit an RCU extended quiescent state, which can be either the
801 * idle loop or adaptive-tickless usermode execution.
803 static void rcu_eqs_exit(bool user)
805 struct rcu_dynticks *rdtp;
808 rdtp = this_cpu_ptr(&rcu_dynticks);
809 oldval = rdtp->dynticks_nesting;
810 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) && oldval < 0);
811 if (oldval & DYNTICK_TASK_NEST_MASK) {
812 rdtp->dynticks_nesting += DYNTICK_TASK_NEST_VALUE;
814 rdtp->dynticks_nesting = DYNTICK_TASK_EXIT_IDLE;
815 rcu_eqs_exit_common(oldval, user);
820 * rcu_idle_exit - inform RCU that current CPU is leaving idle
822 * Exit idle mode, in other words, -enter- the mode in which RCU
823 * read-side critical sections can occur.
825 * We crowbar the ->dynticks_nesting field to DYNTICK_TASK_NEST to
826 * allow for the possibility of usermode upcalls messing up our count
827 * of interrupt nesting level during the busy period that is just
830 void rcu_idle_exit(void)
834 local_irq_save(flags);
837 local_irq_restore(flags);
839 EXPORT_SYMBOL_GPL(rcu_idle_exit);
841 #ifdef CONFIG_NO_HZ_FULL
843 * rcu_user_exit - inform RCU that we are exiting userspace.
845 * Exit RCU idle mode while entering the kernel because it can
846 * run a RCU read side critical section anytime.
848 void rcu_user_exit(void)
852 #endif /* CONFIG_NO_HZ_FULL */
855 * rcu_irq_enter - inform RCU that current CPU is entering irq away from idle
857 * Enter an interrupt handler, which might possibly result in exiting
858 * idle mode, in other words, entering the mode in which read-side critical
859 * sections can occur.
861 * Note that the Linux kernel is fully capable of entering an interrupt
862 * handler that it never exits, for example when doing upcalls to
863 * user mode! This code assumes that the idle loop never does upcalls to
864 * user mode. If your architecture does do upcalls from the idle loop (or
865 * does anything else that results in unbalanced calls to the irq_enter()
866 * and irq_exit() functions), RCU will give you what you deserve, good
867 * and hard. But very infrequently and irreproducibly.
869 * Use things like work queues to work around this limitation.
871 * You have been warned.
873 void rcu_irq_enter(void)
876 struct rcu_dynticks *rdtp;
879 local_irq_save(flags);
880 rdtp = this_cpu_ptr(&rcu_dynticks);
881 oldval = rdtp->dynticks_nesting;
882 rdtp->dynticks_nesting++;
883 WARN_ON_ONCE(IS_ENABLED(CONFIG_RCU_EQS_DEBUG) &&
884 rdtp->dynticks_nesting == 0);
886 trace_rcu_dyntick(TPS("++="), oldval, rdtp->dynticks_nesting);
888 rcu_eqs_exit_common(oldval, true);
890 local_irq_restore(flags);
894 * rcu_nmi_enter - inform RCU of entry to NMI context
896 * If the CPU was idle from RCU's viewpoint, update rdtp->dynticks and
897 * rdtp->dynticks_nmi_nesting to let the RCU grace-period handling know
898 * that the CPU is active. This implementation permits nested NMIs, as
899 * long as the nesting level does not overflow an int. (You will probably
900 * run out of stack space first.)
902 void rcu_nmi_enter(void)
904 struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
907 /* Complain about underflow. */
908 WARN_ON_ONCE(rdtp->dynticks_nmi_nesting < 0);
911 * If idle from RCU viewpoint, atomically increment ->dynticks
912 * to mark non-idle and increment ->dynticks_nmi_nesting by one.
913 * Otherwise, increment ->dynticks_nmi_nesting by two. This means
914 * if ->dynticks_nmi_nesting is equal to one, we are guaranteed
915 * to be in the outermost NMI handler that interrupted an RCU-idle
916 * period (observation due to Andy Lutomirski).
918 if (!(atomic_read(&rdtp->dynticks) & 0x1)) {
919 smp_mb__before_atomic(); /* Force delay from prior write. */
920 atomic_inc(&rdtp->dynticks);
921 /* atomic_inc() before later RCU read-side crit sects */
922 smp_mb__after_atomic(); /* See above. */
923 WARN_ON_ONCE(!(atomic_read(&rdtp->dynticks) & 0x1));
926 rdtp->dynticks_nmi_nesting += incby;
931 * rcu_nmi_exit - inform RCU of exit from NMI context
933 * If we are returning from the outermost NMI handler that interrupted an
934 * RCU-idle period, update rdtp->dynticks and rdtp->dynticks_nmi_nesting
935 * to let the RCU grace-period handling know that the CPU is back to
938 void rcu_nmi_exit(void)
940 struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
943 * Check for ->dynticks_nmi_nesting underflow and bad ->dynticks.
944 * (We are exiting an NMI handler, so RCU better be paying attention
947 WARN_ON_ONCE(rdtp->dynticks_nmi_nesting <= 0);
948 WARN_ON_ONCE(!(atomic_read(&rdtp->dynticks) & 0x1));
951 * If the nesting level is not 1, the CPU wasn't RCU-idle, so
952 * leave it in non-RCU-idle state.
954 if (rdtp->dynticks_nmi_nesting != 1) {
955 rdtp->dynticks_nmi_nesting -= 2;
959 /* This NMI interrupted an RCU-idle CPU, restore RCU-idleness. */
960 rdtp->dynticks_nmi_nesting = 0;
961 /* CPUs seeing atomic_inc() must see prior RCU read-side crit sects */
962 smp_mb__before_atomic(); /* See above. */
963 atomic_inc(&rdtp->dynticks);
964 smp_mb__after_atomic(); /* Force delay to next write. */
965 WARN_ON_ONCE(atomic_read(&rdtp->dynticks) & 0x1);
969 * __rcu_is_watching - are RCU read-side critical sections safe?
971 * Return true if RCU is watching the running CPU, which means that
972 * this CPU can safely enter RCU read-side critical sections. Unlike
973 * rcu_is_watching(), the caller of __rcu_is_watching() must have at
974 * least disabled preemption.
976 bool notrace __rcu_is_watching(void)
978 return atomic_read(this_cpu_ptr(&rcu_dynticks.dynticks)) & 0x1;
982 * rcu_is_watching - see if RCU thinks that the current CPU is idle
984 * If the current CPU is in its idle loop and is neither in an interrupt
985 * or NMI handler, return true.
987 bool notrace rcu_is_watching(void)
991 preempt_disable_notrace();
992 ret = __rcu_is_watching();
993 preempt_enable_notrace();
996 EXPORT_SYMBOL_GPL(rcu_is_watching);
998 #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU)
1001 * Is the current CPU online? Disable preemption to avoid false positives
1002 * that could otherwise happen due to the current CPU number being sampled,
1003 * this task being preempted, its old CPU being taken offline, resuming
1004 * on some other CPU, then determining that its old CPU is now offline.
1005 * It is OK to use RCU on an offline processor during initial boot, hence
1006 * the check for rcu_scheduler_fully_active. Note also that it is OK
1007 * for a CPU coming online to use RCU for one jiffy prior to marking itself
1008 * online in the cpu_online_mask. Similarly, it is OK for a CPU going
1009 * offline to continue to use RCU for one jiffy after marking itself
1010 * offline in the cpu_online_mask. This leniency is necessary given the
1011 * non-atomic nature of the online and offline processing, for example,
1012 * the fact that a CPU enters the scheduler after completing the CPU_DYING
1015 * This is also why RCU internally marks CPUs online during the
1016 * CPU_UP_PREPARE phase and offline during the CPU_DEAD phase.
1018 * Disable checking if in an NMI handler because we cannot safely report
1019 * errors from NMI handlers anyway.
1021 bool rcu_lockdep_current_cpu_online(void)
1023 struct rcu_data *rdp;
1024 struct rcu_node *rnp;
1030 rdp = this_cpu_ptr(&rcu_sched_data);
1032 ret = (rdp->grpmask & rcu_rnp_online_cpus(rnp)) ||
1033 !rcu_scheduler_fully_active;
1037 EXPORT_SYMBOL_GPL(rcu_lockdep_current_cpu_online);
1039 #endif /* #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU) */
1042 * rcu_is_cpu_rrupt_from_idle - see if idle or immediately interrupted from idle
1044 * If the current CPU is idle or running at a first-level (not nested)
1045 * interrupt from idle, return true. The caller must have at least
1046 * disabled preemption.
1048 static int rcu_is_cpu_rrupt_from_idle(void)
1050 return __this_cpu_read(rcu_dynticks.dynticks_nesting) <= 1;
1054 * Snapshot the specified CPU's dynticks counter so that we can later
1055 * credit them with an implicit quiescent state. Return 1 if this CPU
1056 * is in dynticks idle mode, which is an extended quiescent state.
1058 static int dyntick_save_progress_counter(struct rcu_data *rdp,
1059 bool *isidle, unsigned long *maxj)
1061 rdp->dynticks_snap = atomic_add_return(0, &rdp->dynticks->dynticks);
1062 rcu_sysidle_check_cpu(rdp, isidle, maxj);
1063 if ((rdp->dynticks_snap & 0x1) == 0) {
1064 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, TPS("dti"));
1067 if (ULONG_CMP_LT(READ_ONCE(rdp->gpnum) + ULONG_MAX / 4,
1068 rdp->mynode->gpnum))
1069 WRITE_ONCE(rdp->gpwrap, true);
1075 * Return true if the specified CPU has passed through a quiescent
1076 * state by virtue of being in or having passed through an dynticks
1077 * idle state since the last call to dyntick_save_progress_counter()
1078 * for this same CPU, or by virtue of having been offline.
1080 static int rcu_implicit_dynticks_qs(struct rcu_data *rdp,
1081 bool *isidle, unsigned long *maxj)
1087 curr = (unsigned int)atomic_add_return(0, &rdp->dynticks->dynticks);
1088 snap = (unsigned int)rdp->dynticks_snap;
1091 * If the CPU passed through or entered a dynticks idle phase with
1092 * no active irq/NMI handlers, then we can safely pretend that the CPU
1093 * already acknowledged the request to pass through a quiescent
1094 * state. Either way, that CPU cannot possibly be in an RCU
1095 * read-side critical section that started before the beginning
1096 * of the current RCU grace period.
1098 if ((curr & 0x1) == 0 || UINT_CMP_GE(curr, snap + 2)) {
1099 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, TPS("dti"));
1100 rdp->dynticks_fqs++;
1105 * Check for the CPU being offline, but only if the grace period
1106 * is old enough. We don't need to worry about the CPU changing
1107 * state: If we see it offline even once, it has been through a
1110 * The reason for insisting that the grace period be at least
1111 * one jiffy old is that CPUs that are not quite online and that
1112 * have just gone offline can still execute RCU read-side critical
1115 if (ULONG_CMP_GE(rdp->rsp->gp_start + 2, jiffies))
1116 return 0; /* Grace period is not old enough. */
1118 if (cpu_is_offline(rdp->cpu)) {
1119 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, TPS("ofl"));
1125 * A CPU running for an extended time within the kernel can
1126 * delay RCU grace periods. When the CPU is in NO_HZ_FULL mode,
1127 * even context-switching back and forth between a pair of
1128 * in-kernel CPU-bound tasks cannot advance grace periods.
1129 * So if the grace period is old enough, make the CPU pay attention.
1130 * Note that the unsynchronized assignments to the per-CPU
1131 * rcu_sched_qs_mask variable are safe. Yes, setting of
1132 * bits can be lost, but they will be set again on the next
1133 * force-quiescent-state pass. So lost bit sets do not result
1134 * in incorrect behavior, merely in a grace period lasting
1135 * a few jiffies longer than it might otherwise. Because
1136 * there are at most four threads involved, and because the
1137 * updates are only once every few jiffies, the probability of
1138 * lossage (and thus of slight grace-period extension) is
1141 * Note that if the jiffies_till_sched_qs boot/sysfs parameter
1142 * is set too high, we override with half of the RCU CPU stall
1145 rcrmp = &per_cpu(rcu_sched_qs_mask, rdp->cpu);
1146 if (ULONG_CMP_GE(jiffies,
1147 rdp->rsp->gp_start + jiffies_till_sched_qs) ||
1148 ULONG_CMP_GE(jiffies, rdp->rsp->jiffies_resched)) {
1149 if (!(READ_ONCE(*rcrmp) & rdp->rsp->flavor_mask)) {
1150 WRITE_ONCE(rdp->cond_resched_completed,
1151 READ_ONCE(rdp->mynode->completed));
1152 smp_mb(); /* ->cond_resched_completed before *rcrmp. */
1154 READ_ONCE(*rcrmp) + rdp->rsp->flavor_mask);
1155 resched_cpu(rdp->cpu); /* Force CPU into scheduler. */
1156 rdp->rsp->jiffies_resched += 5; /* Enable beating. */
1157 } else if (ULONG_CMP_GE(jiffies, rdp->rsp->jiffies_resched)) {
1158 /* Time to beat on that CPU again! */
1159 resched_cpu(rdp->cpu); /* Force CPU into scheduler. */
1160 rdp->rsp->jiffies_resched += 5; /* Re-enable beating. */
1167 static void record_gp_stall_check_time(struct rcu_state *rsp)
1169 unsigned long j = jiffies;
1173 smp_wmb(); /* Record start time before stall time. */
1174 j1 = rcu_jiffies_till_stall_check();
1175 WRITE_ONCE(rsp->jiffies_stall, j + j1);
1176 rsp->jiffies_resched = j + j1 / 2;
1177 rsp->n_force_qs_gpstart = READ_ONCE(rsp->n_force_qs);
1181 * Complain about starvation of grace-period kthread.
1183 static void rcu_check_gp_kthread_starvation(struct rcu_state *rsp)
1189 gpa = READ_ONCE(rsp->gp_activity);
1190 if (j - gpa > 2 * HZ)
1191 pr_err("%s kthread starved for %ld jiffies! g%lu c%lu f%#x s%d ->state=%#lx\n",
1193 rsp->gpnum, rsp->completed,
1194 rsp->gp_flags, rsp->gp_state,
1195 rsp->gp_kthread ? rsp->gp_kthread->state : 0);
1199 * Dump stacks of all tasks running on stalled CPUs.
1201 static void rcu_dump_cpu_stacks(struct rcu_state *rsp)
1204 unsigned long flags;
1205 struct rcu_node *rnp;
1207 rcu_for_each_leaf_node(rsp, rnp) {
1208 raw_spin_lock_irqsave(&rnp->lock, flags);
1209 if (rnp->qsmask != 0) {
1210 for (cpu = 0; cpu <= rnp->grphi - rnp->grplo; cpu++)
1211 if (rnp->qsmask & (1UL << cpu))
1212 dump_cpu_task(rnp->grplo + cpu);
1214 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1218 static void print_other_cpu_stall(struct rcu_state *rsp, unsigned long gpnum)
1222 unsigned long flags;
1226 struct rcu_node *rnp = rcu_get_root(rsp);
1229 /* Only let one CPU complain about others per time interval. */
1231 raw_spin_lock_irqsave(&rnp->lock, flags);
1232 delta = jiffies - READ_ONCE(rsp->jiffies_stall);
1233 if (delta < RCU_STALL_RAT_DELAY || !rcu_gp_in_progress(rsp)) {
1234 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1237 WRITE_ONCE(rsp->jiffies_stall,
1238 jiffies + 3 * rcu_jiffies_till_stall_check() + 3);
1239 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1242 * OK, time to rat on our buddy...
1243 * See Documentation/RCU/stallwarn.txt for info on how to debug
1244 * RCU CPU stall warnings.
1246 pr_err("INFO: %s detected stalls on CPUs/tasks:",
1248 print_cpu_stall_info_begin();
1249 rcu_for_each_leaf_node(rsp, rnp) {
1250 raw_spin_lock_irqsave(&rnp->lock, flags);
1251 ndetected += rcu_print_task_stall(rnp);
1252 if (rnp->qsmask != 0) {
1253 for (cpu = 0; cpu <= rnp->grphi - rnp->grplo; cpu++)
1254 if (rnp->qsmask & (1UL << cpu)) {
1255 print_cpu_stall_info(rsp,
1260 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1263 print_cpu_stall_info_end();
1264 for_each_possible_cpu(cpu)
1265 totqlen += per_cpu_ptr(rsp->rda, cpu)->qlen;
1266 pr_cont("(detected by %d, t=%ld jiffies, g=%ld, c=%ld, q=%lu)\n",
1267 smp_processor_id(), (long)(jiffies - rsp->gp_start),
1268 (long)rsp->gpnum, (long)rsp->completed, totqlen);
1270 rcu_dump_cpu_stacks(rsp);
1272 if (READ_ONCE(rsp->gpnum) != gpnum ||
1273 READ_ONCE(rsp->completed) == gpnum) {
1274 pr_err("INFO: Stall ended before state dump start\n");
1277 gpa = READ_ONCE(rsp->gp_activity);
1278 pr_err("All QSes seen, last %s kthread activity %ld (%ld-%ld), jiffies_till_next_fqs=%ld, root ->qsmask %#lx\n",
1279 rsp->name, j - gpa, j, gpa,
1280 jiffies_till_next_fqs,
1281 rcu_get_root(rsp)->qsmask);
1282 /* In this case, the current CPU might be at fault. */
1283 sched_show_task(current);
1287 /* Complain about tasks blocking the grace period. */
1288 rcu_print_detail_task_stall(rsp);
1290 rcu_check_gp_kthread_starvation(rsp);
1292 force_quiescent_state(rsp); /* Kick them all. */
1295 static void print_cpu_stall(struct rcu_state *rsp)
1298 unsigned long flags;
1299 struct rcu_node *rnp = rcu_get_root(rsp);
1303 * OK, time to rat on ourselves...
1304 * See Documentation/RCU/stallwarn.txt for info on how to debug
1305 * RCU CPU stall warnings.
1307 pr_err("INFO: %s self-detected stall on CPU", rsp->name);
1308 print_cpu_stall_info_begin();
1309 print_cpu_stall_info(rsp, smp_processor_id());
1310 print_cpu_stall_info_end();
1311 for_each_possible_cpu(cpu)
1312 totqlen += per_cpu_ptr(rsp->rda, cpu)->qlen;
1313 pr_cont(" (t=%lu jiffies g=%ld c=%ld q=%lu)\n",
1314 jiffies - rsp->gp_start,
1315 (long)rsp->gpnum, (long)rsp->completed, totqlen);
1317 rcu_check_gp_kthread_starvation(rsp);
1319 rcu_dump_cpu_stacks(rsp);
1321 raw_spin_lock_irqsave(&rnp->lock, flags);
1322 if (ULONG_CMP_GE(jiffies, READ_ONCE(rsp->jiffies_stall)))
1323 WRITE_ONCE(rsp->jiffies_stall,
1324 jiffies + 3 * rcu_jiffies_till_stall_check() + 3);
1325 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1328 * Attempt to revive the RCU machinery by forcing a context switch.
1330 * A context switch would normally allow the RCU state machine to make
1331 * progress and it could be we're stuck in kernel space without context
1332 * switches for an entirely unreasonable amount of time.
1334 resched_cpu(smp_processor_id());
1337 static void check_cpu_stall(struct rcu_state *rsp, struct rcu_data *rdp)
1339 unsigned long completed;
1340 unsigned long gpnum;
1344 struct rcu_node *rnp;
1346 if (rcu_cpu_stall_suppress || !rcu_gp_in_progress(rsp))
1351 * Lots of memory barriers to reject false positives.
1353 * The idea is to pick up rsp->gpnum, then rsp->jiffies_stall,
1354 * then rsp->gp_start, and finally rsp->completed. These values
1355 * are updated in the opposite order with memory barriers (or
1356 * equivalent) during grace-period initialization and cleanup.
1357 * Now, a false positive can occur if we get an new value of
1358 * rsp->gp_start and a old value of rsp->jiffies_stall. But given
1359 * the memory barriers, the only way that this can happen is if one
1360 * grace period ends and another starts between these two fetches.
1361 * Detect this by comparing rsp->completed with the previous fetch
1364 * Given this check, comparisons of jiffies, rsp->jiffies_stall,
1365 * and rsp->gp_start suffice to forestall false positives.
1367 gpnum = READ_ONCE(rsp->gpnum);
1368 smp_rmb(); /* Pick up ->gpnum first... */
1369 js = READ_ONCE(rsp->jiffies_stall);
1370 smp_rmb(); /* ...then ->jiffies_stall before the rest... */
1371 gps = READ_ONCE(rsp->gp_start);
1372 smp_rmb(); /* ...and finally ->gp_start before ->completed. */
1373 completed = READ_ONCE(rsp->completed);
1374 if (ULONG_CMP_GE(completed, gpnum) ||
1375 ULONG_CMP_LT(j, js) ||
1376 ULONG_CMP_GE(gps, js))
1377 return; /* No stall or GP completed since entering function. */
1379 if (rcu_gp_in_progress(rsp) &&
1380 (READ_ONCE(rnp->qsmask) & rdp->grpmask)) {
1382 /* We haven't checked in, so go dump stack. */
1383 print_cpu_stall(rsp);
1385 } else if (rcu_gp_in_progress(rsp) &&
1386 ULONG_CMP_GE(j, js + RCU_STALL_RAT_DELAY)) {
1388 /* They had a few time units to dump stack, so complain. */
1389 print_other_cpu_stall(rsp, gpnum);
1394 * rcu_cpu_stall_reset - prevent further stall warnings in current grace period
1396 * Set the stall-warning timeout way off into the future, thus preventing
1397 * any RCU CPU stall-warning messages from appearing in the current set of
1398 * RCU grace periods.
1400 * The caller must disable hard irqs.
1402 void rcu_cpu_stall_reset(void)
1404 struct rcu_state *rsp;
1406 for_each_rcu_flavor(rsp)
1407 WRITE_ONCE(rsp->jiffies_stall, jiffies + ULONG_MAX / 2);
1411 * Initialize the specified rcu_data structure's default callback list
1412 * to empty. The default callback list is the one that is not used by
1413 * no-callbacks CPUs.
1415 static void init_default_callback_list(struct rcu_data *rdp)
1419 rdp->nxtlist = NULL;
1420 for (i = 0; i < RCU_NEXT_SIZE; i++)
1421 rdp->nxttail[i] = &rdp->nxtlist;
1425 * Initialize the specified rcu_data structure's callback list to empty.
1427 static void init_callback_list(struct rcu_data *rdp)
1429 if (init_nocb_callback_list(rdp))
1431 init_default_callback_list(rdp);
1435 * Determine the value that ->completed will have at the end of the
1436 * next subsequent grace period. This is used to tag callbacks so that
1437 * a CPU can invoke callbacks in a timely fashion even if that CPU has
1438 * been dyntick-idle for an extended period with callbacks under the
1439 * influence of RCU_FAST_NO_HZ.
1441 * The caller must hold rnp->lock with interrupts disabled.
1443 static unsigned long rcu_cbs_completed(struct rcu_state *rsp,
1444 struct rcu_node *rnp)
1447 * If RCU is idle, we just wait for the next grace period.
1448 * But we can only be sure that RCU is idle if we are looking
1449 * at the root rcu_node structure -- otherwise, a new grace
1450 * period might have started, but just not yet gotten around
1451 * to initializing the current non-root rcu_node structure.
1453 if (rcu_get_root(rsp) == rnp && rnp->gpnum == rnp->completed)
1454 return rnp->completed + 1;
1457 * Otherwise, wait for a possible partial grace period and
1458 * then the subsequent full grace period.
1460 return rnp->completed + 2;
1464 * Trace-event helper function for rcu_start_future_gp() and
1465 * rcu_nocb_wait_gp().
1467 static void trace_rcu_future_gp(struct rcu_node *rnp, struct rcu_data *rdp,
1468 unsigned long c, const char *s)
1470 trace_rcu_future_grace_period(rdp->rsp->name, rnp->gpnum,
1471 rnp->completed, c, rnp->level,
1472 rnp->grplo, rnp->grphi, s);
1476 * Start some future grace period, as needed to handle newly arrived
1477 * callbacks. The required future grace periods are recorded in each
1478 * rcu_node structure's ->need_future_gp field. Returns true if there
1479 * is reason to awaken the grace-period kthread.
1481 * The caller must hold the specified rcu_node structure's ->lock.
1483 static bool __maybe_unused
1484 rcu_start_future_gp(struct rcu_node *rnp, struct rcu_data *rdp,
1485 unsigned long *c_out)
1490 struct rcu_node *rnp_root = rcu_get_root(rdp->rsp);
1493 * Pick up grace-period number for new callbacks. If this
1494 * grace period is already marked as needed, return to the caller.
1496 c = rcu_cbs_completed(rdp->rsp, rnp);
1497 trace_rcu_future_gp(rnp, rdp, c, TPS("Startleaf"));
1498 if (rnp->need_future_gp[c & 0x1]) {
1499 trace_rcu_future_gp(rnp, rdp, c, TPS("Prestartleaf"));
1504 * If either this rcu_node structure or the root rcu_node structure
1505 * believe that a grace period is in progress, then we must wait
1506 * for the one following, which is in "c". Because our request
1507 * will be noticed at the end of the current grace period, we don't
1508 * need to explicitly start one. We only do the lockless check
1509 * of rnp_root's fields if the current rcu_node structure thinks
1510 * there is no grace period in flight, and because we hold rnp->lock,
1511 * the only possible change is when rnp_root's two fields are
1512 * equal, in which case rnp_root->gpnum might be concurrently
1513 * incremented. But that is OK, as it will just result in our
1514 * doing some extra useless work.
1516 if (rnp->gpnum != rnp->completed ||
1517 READ_ONCE(rnp_root->gpnum) != READ_ONCE(rnp_root->completed)) {
1518 rnp->need_future_gp[c & 0x1]++;
1519 trace_rcu_future_gp(rnp, rdp, c, TPS("Startedleaf"));
1524 * There might be no grace period in progress. If we don't already
1525 * hold it, acquire the root rcu_node structure's lock in order to
1526 * start one (if needed).
1528 if (rnp != rnp_root) {
1529 raw_spin_lock(&rnp_root->lock);
1530 smp_mb__after_unlock_lock();
1534 * Get a new grace-period number. If there really is no grace
1535 * period in progress, it will be smaller than the one we obtained
1536 * earlier. Adjust callbacks as needed. Note that even no-CBs
1537 * CPUs have a ->nxtcompleted[] array, so no no-CBs checks needed.
1539 c = rcu_cbs_completed(rdp->rsp, rnp_root);
1540 for (i = RCU_DONE_TAIL; i < RCU_NEXT_TAIL; i++)
1541 if (ULONG_CMP_LT(c, rdp->nxtcompleted[i]))
1542 rdp->nxtcompleted[i] = c;
1545 * If the needed for the required grace period is already
1546 * recorded, trace and leave.
1548 if (rnp_root->need_future_gp[c & 0x1]) {
1549 trace_rcu_future_gp(rnp, rdp, c, TPS("Prestartedroot"));
1553 /* Record the need for the future grace period. */
1554 rnp_root->need_future_gp[c & 0x1]++;
1556 /* If a grace period is not already in progress, start one. */
1557 if (rnp_root->gpnum != rnp_root->completed) {
1558 trace_rcu_future_gp(rnp, rdp, c, TPS("Startedleafroot"));
1560 trace_rcu_future_gp(rnp, rdp, c, TPS("Startedroot"));
1561 ret = rcu_start_gp_advanced(rdp->rsp, rnp_root, rdp);
1564 if (rnp != rnp_root)
1565 raw_spin_unlock(&rnp_root->lock);
1573 * Clean up any old requests for the just-ended grace period. Also return
1574 * whether any additional grace periods have been requested. Also invoke
1575 * rcu_nocb_gp_cleanup() in order to wake up any no-callbacks kthreads
1576 * waiting for this grace period to complete.
1578 static int rcu_future_gp_cleanup(struct rcu_state *rsp, struct rcu_node *rnp)
1580 int c = rnp->completed;
1582 struct rcu_data *rdp = this_cpu_ptr(rsp->rda);
1584 rcu_nocb_gp_cleanup(rsp, rnp);
1585 rnp->need_future_gp[c & 0x1] = 0;
1586 needmore = rnp->need_future_gp[(c + 1) & 0x1];
1587 trace_rcu_future_gp(rnp, rdp, c,
1588 needmore ? TPS("CleanupMore") : TPS("Cleanup"));
1593 * Awaken the grace-period kthread for the specified flavor of RCU.
1594 * Don't do a self-awaken, and don't bother awakening when there is
1595 * nothing for the grace-period kthread to do (as in several CPUs
1596 * raced to awaken, and we lost), and finally don't try to awaken
1597 * a kthread that has not yet been created.
1599 static void rcu_gp_kthread_wake(struct rcu_state *rsp)
1601 if (current == rsp->gp_kthread ||
1602 !READ_ONCE(rsp->gp_flags) ||
1605 wake_up(&rsp->gp_wq);
1609 * If there is room, assign a ->completed number to any callbacks on
1610 * this CPU that have not already been assigned. Also accelerate any
1611 * callbacks that were previously assigned a ->completed number that has
1612 * since proven to be too conservative, which can happen if callbacks get
1613 * assigned a ->completed number while RCU is idle, but with reference to
1614 * a non-root rcu_node structure. This function is idempotent, so it does
1615 * not hurt to call it repeatedly. Returns an flag saying that we should
1616 * awaken the RCU grace-period kthread.
1618 * The caller must hold rnp->lock with interrupts disabled.
1620 static bool rcu_accelerate_cbs(struct rcu_state *rsp, struct rcu_node *rnp,
1621 struct rcu_data *rdp)
1627 /* If the CPU has no callbacks, nothing to do. */
1628 if (!rdp->nxttail[RCU_NEXT_TAIL] || !*rdp->nxttail[RCU_DONE_TAIL])
1632 * Starting from the sublist containing the callbacks most
1633 * recently assigned a ->completed number and working down, find the
1634 * first sublist that is not assignable to an upcoming grace period.
1635 * Such a sublist has something in it (first two tests) and has
1636 * a ->completed number assigned that will complete sooner than
1637 * the ->completed number for newly arrived callbacks (last test).
1639 * The key point is that any later sublist can be assigned the
1640 * same ->completed number as the newly arrived callbacks, which
1641 * means that the callbacks in any of these later sublist can be
1642 * grouped into a single sublist, whether or not they have already
1643 * been assigned a ->completed number.
1645 c = rcu_cbs_completed(rsp, rnp);
1646 for (i = RCU_NEXT_TAIL - 1; i > RCU_DONE_TAIL; i--)
1647 if (rdp->nxttail[i] != rdp->nxttail[i - 1] &&
1648 !ULONG_CMP_GE(rdp->nxtcompleted[i], c))
1652 * If there are no sublist for unassigned callbacks, leave.
1653 * At the same time, advance "i" one sublist, so that "i" will
1654 * index into the sublist where all the remaining callbacks should
1657 if (++i >= RCU_NEXT_TAIL)
1661 * Assign all subsequent callbacks' ->completed number to the next
1662 * full grace period and group them all in the sublist initially
1665 for (; i <= RCU_NEXT_TAIL; i++) {
1666 rdp->nxttail[i] = rdp->nxttail[RCU_NEXT_TAIL];
1667 rdp->nxtcompleted[i] = c;
1669 /* Record any needed additional grace periods. */
1670 ret = rcu_start_future_gp(rnp, rdp, NULL);
1672 /* Trace depending on how much we were able to accelerate. */
1673 if (!*rdp->nxttail[RCU_WAIT_TAIL])
1674 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("AccWaitCB"));
1676 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("AccReadyCB"));
1681 * Move any callbacks whose grace period has completed to the
1682 * RCU_DONE_TAIL sublist, then compact the remaining sublists and
1683 * assign ->completed numbers to any callbacks in the RCU_NEXT_TAIL
1684 * sublist. This function is idempotent, so it does not hurt to
1685 * invoke it repeatedly. As long as it is not invoked -too- often...
1686 * Returns true if the RCU grace-period kthread needs to be awakened.
1688 * The caller must hold rnp->lock with interrupts disabled.
1690 static bool rcu_advance_cbs(struct rcu_state *rsp, struct rcu_node *rnp,
1691 struct rcu_data *rdp)
1695 /* If the CPU has no callbacks, nothing to do. */
1696 if (!rdp->nxttail[RCU_NEXT_TAIL] || !*rdp->nxttail[RCU_DONE_TAIL])
1700 * Find all callbacks whose ->completed numbers indicate that they
1701 * are ready to invoke, and put them into the RCU_DONE_TAIL sublist.
1703 for (i = RCU_WAIT_TAIL; i < RCU_NEXT_TAIL; i++) {
1704 if (ULONG_CMP_LT(rnp->completed, rdp->nxtcompleted[i]))
1706 rdp->nxttail[RCU_DONE_TAIL] = rdp->nxttail[i];
1708 /* Clean up any sublist tail pointers that were misordered above. */
1709 for (j = RCU_WAIT_TAIL; j < i; j++)
1710 rdp->nxttail[j] = rdp->nxttail[RCU_DONE_TAIL];
1712 /* Copy down callbacks to fill in empty sublists. */
1713 for (j = RCU_WAIT_TAIL; i < RCU_NEXT_TAIL; i++, j++) {
1714 if (rdp->nxttail[j] == rdp->nxttail[RCU_NEXT_TAIL])
1716 rdp->nxttail[j] = rdp->nxttail[i];
1717 rdp->nxtcompleted[j] = rdp->nxtcompleted[i];
1720 /* Classify any remaining callbacks. */
1721 return rcu_accelerate_cbs(rsp, rnp, rdp);
1725 * Update CPU-local rcu_data state to record the beginnings and ends of
1726 * grace periods. The caller must hold the ->lock of the leaf rcu_node
1727 * structure corresponding to the current CPU, and must have irqs disabled.
1728 * Returns true if the grace-period kthread needs to be awakened.
1730 static bool __note_gp_changes(struct rcu_state *rsp, struct rcu_node *rnp,
1731 struct rcu_data *rdp)
1735 /* Handle the ends of any preceding grace periods first. */
1736 if (rdp->completed == rnp->completed &&
1737 !unlikely(READ_ONCE(rdp->gpwrap))) {
1739 /* No grace period end, so just accelerate recent callbacks. */
1740 ret = rcu_accelerate_cbs(rsp, rnp, rdp);
1744 /* Advance callbacks. */
1745 ret = rcu_advance_cbs(rsp, rnp, rdp);
1747 /* Remember that we saw this grace-period completion. */
1748 rdp->completed = rnp->completed;
1749 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("cpuend"));
1752 if (rdp->gpnum != rnp->gpnum || unlikely(READ_ONCE(rdp->gpwrap))) {
1754 * If the current grace period is waiting for this CPU,
1755 * set up to detect a quiescent state, otherwise don't
1756 * go looking for one.
1758 rdp->gpnum = rnp->gpnum;
1759 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("cpustart"));
1760 rdp->cpu_no_qs.b.norm = true;
1761 rdp->rcu_qs_ctr_snap = __this_cpu_read(rcu_qs_ctr);
1762 rdp->core_needs_qs = !!(rnp->qsmask & rdp->grpmask);
1763 zero_cpu_stall_ticks(rdp);
1764 WRITE_ONCE(rdp->gpwrap, false);
1769 static void note_gp_changes(struct rcu_state *rsp, struct rcu_data *rdp)
1771 unsigned long flags;
1773 struct rcu_node *rnp;
1775 local_irq_save(flags);
1777 if ((rdp->gpnum == READ_ONCE(rnp->gpnum) &&
1778 rdp->completed == READ_ONCE(rnp->completed) &&
1779 !unlikely(READ_ONCE(rdp->gpwrap))) || /* w/out lock. */
1780 !raw_spin_trylock(&rnp->lock)) { /* irqs already off, so later. */
1781 local_irq_restore(flags);
1784 smp_mb__after_unlock_lock();
1785 needwake = __note_gp_changes(rsp, rnp, rdp);
1786 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1788 rcu_gp_kthread_wake(rsp);
1791 static void rcu_gp_slow(struct rcu_state *rsp, int delay)
1794 !(rsp->gpnum % (rcu_num_nodes * PER_RCU_NODE_PERIOD * delay)))
1795 schedule_timeout_uninterruptible(delay);
1799 * Initialize a new grace period. Return 0 if no grace period required.
1801 static int rcu_gp_init(struct rcu_state *rsp)
1803 unsigned long oldmask;
1804 struct rcu_data *rdp;
1805 struct rcu_node *rnp = rcu_get_root(rsp);
1807 WRITE_ONCE(rsp->gp_activity, jiffies);
1808 raw_spin_lock_irq(&rnp->lock);
1809 smp_mb__after_unlock_lock();
1810 if (!READ_ONCE(rsp->gp_flags)) {
1811 /* Spurious wakeup, tell caller to go back to sleep. */
1812 raw_spin_unlock_irq(&rnp->lock);
1815 WRITE_ONCE(rsp->gp_flags, 0); /* Clear all flags: New grace period. */
1817 if (WARN_ON_ONCE(rcu_gp_in_progress(rsp))) {
1819 * Grace period already in progress, don't start another.
1820 * Not supposed to be able to happen.
1822 raw_spin_unlock_irq(&rnp->lock);
1826 /* Advance to a new grace period and initialize state. */
1827 record_gp_stall_check_time(rsp);
1828 /* Record GP times before starting GP, hence smp_store_release(). */
1829 smp_store_release(&rsp->gpnum, rsp->gpnum + 1);
1830 trace_rcu_grace_period(rsp->name, rsp->gpnum, TPS("start"));
1831 raw_spin_unlock_irq(&rnp->lock);
1834 * Apply per-leaf buffered online and offline operations to the
1835 * rcu_node tree. Note that this new grace period need not wait
1836 * for subsequent online CPUs, and that quiescent-state forcing
1837 * will handle subsequent offline CPUs.
1839 rcu_for_each_leaf_node(rsp, rnp) {
1840 rcu_gp_slow(rsp, gp_preinit_delay);
1841 raw_spin_lock_irq(&rnp->lock);
1842 smp_mb__after_unlock_lock();
1843 if (rnp->qsmaskinit == rnp->qsmaskinitnext &&
1844 !rnp->wait_blkd_tasks) {
1845 /* Nothing to do on this leaf rcu_node structure. */
1846 raw_spin_unlock_irq(&rnp->lock);
1850 /* Record old state, apply changes to ->qsmaskinit field. */
1851 oldmask = rnp->qsmaskinit;
1852 rnp->qsmaskinit = rnp->qsmaskinitnext;
1854 /* If zero-ness of ->qsmaskinit changed, propagate up tree. */
1855 if (!oldmask != !rnp->qsmaskinit) {
1856 if (!oldmask) /* First online CPU for this rcu_node. */
1857 rcu_init_new_rnp(rnp);
1858 else if (rcu_preempt_has_tasks(rnp)) /* blocked tasks */
1859 rnp->wait_blkd_tasks = true;
1860 else /* Last offline CPU and can propagate. */
1861 rcu_cleanup_dead_rnp(rnp);
1865 * If all waited-on tasks from prior grace period are
1866 * done, and if all this rcu_node structure's CPUs are
1867 * still offline, propagate up the rcu_node tree and
1868 * clear ->wait_blkd_tasks. Otherwise, if one of this
1869 * rcu_node structure's CPUs has since come back online,
1870 * simply clear ->wait_blkd_tasks (but rcu_cleanup_dead_rnp()
1871 * checks for this, so just call it unconditionally).
1873 if (rnp->wait_blkd_tasks &&
1874 (!rcu_preempt_has_tasks(rnp) ||
1876 rnp->wait_blkd_tasks = false;
1877 rcu_cleanup_dead_rnp(rnp);
1880 raw_spin_unlock_irq(&rnp->lock);
1884 * Set the quiescent-state-needed bits in all the rcu_node
1885 * structures for all currently online CPUs in breadth-first order,
1886 * starting from the root rcu_node structure, relying on the layout
1887 * of the tree within the rsp->node[] array. Note that other CPUs
1888 * will access only the leaves of the hierarchy, thus seeing that no
1889 * grace period is in progress, at least until the corresponding
1890 * leaf node has been initialized. In addition, we have excluded
1891 * CPU-hotplug operations.
1893 * The grace period cannot complete until the initialization
1894 * process finishes, because this kthread handles both.
1896 rcu_for_each_node_breadth_first(rsp, rnp) {
1897 rcu_gp_slow(rsp, gp_init_delay);
1898 raw_spin_lock_irq(&rnp->lock);
1899 smp_mb__after_unlock_lock();
1900 rdp = this_cpu_ptr(rsp->rda);
1901 rcu_preempt_check_blocked_tasks(rnp);
1902 rnp->qsmask = rnp->qsmaskinit;
1903 WRITE_ONCE(rnp->gpnum, rsp->gpnum);
1904 if (WARN_ON_ONCE(rnp->completed != rsp->completed))
1905 WRITE_ONCE(rnp->completed, rsp->completed);
1906 if (rnp == rdp->mynode)
1907 (void)__note_gp_changes(rsp, rnp, rdp);
1908 rcu_preempt_boost_start_gp(rnp);
1909 trace_rcu_grace_period_init(rsp->name, rnp->gpnum,
1910 rnp->level, rnp->grplo,
1911 rnp->grphi, rnp->qsmask);
1912 raw_spin_unlock_irq(&rnp->lock);
1913 cond_resched_rcu_qs();
1914 WRITE_ONCE(rsp->gp_activity, jiffies);
1921 * Helper function for wait_event_interruptible_timeout() wakeup
1922 * at force-quiescent-state time.
1924 static bool rcu_gp_fqs_check_wake(struct rcu_state *rsp, int *gfp)
1926 struct rcu_node *rnp = rcu_get_root(rsp);
1928 /* Someone like call_rcu() requested a force-quiescent-state scan. */
1929 *gfp = READ_ONCE(rsp->gp_flags);
1930 if (*gfp & RCU_GP_FLAG_FQS)
1933 /* The current grace period has completed. */
1934 if (!READ_ONCE(rnp->qsmask) && !rcu_preempt_blocked_readers_cgp(rnp))
1941 * Do one round of quiescent-state forcing.
1943 static int rcu_gp_fqs(struct rcu_state *rsp, int fqs_state_in)
1945 int fqs_state = fqs_state_in;
1946 bool isidle = false;
1948 struct rcu_node *rnp = rcu_get_root(rsp);
1950 WRITE_ONCE(rsp->gp_activity, jiffies);
1952 if (fqs_state == RCU_SAVE_DYNTICK) {
1953 /* Collect dyntick-idle snapshots. */
1954 if (is_sysidle_rcu_state(rsp)) {
1956 maxj = jiffies - ULONG_MAX / 4;
1958 force_qs_rnp(rsp, dyntick_save_progress_counter,
1960 rcu_sysidle_report_gp(rsp, isidle, maxj);
1961 fqs_state = RCU_FORCE_QS;
1963 /* Handle dyntick-idle and offline CPUs. */
1965 force_qs_rnp(rsp, rcu_implicit_dynticks_qs, &isidle, &maxj);
1967 /* Clear flag to prevent immediate re-entry. */
1968 if (READ_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) {
1969 raw_spin_lock_irq(&rnp->lock);
1970 smp_mb__after_unlock_lock();
1971 WRITE_ONCE(rsp->gp_flags,
1972 READ_ONCE(rsp->gp_flags) & ~RCU_GP_FLAG_FQS);
1973 raw_spin_unlock_irq(&rnp->lock);
1979 * Clean up after the old grace period.
1981 static void rcu_gp_cleanup(struct rcu_state *rsp)
1983 unsigned long gp_duration;
1984 bool needgp = false;
1986 struct rcu_data *rdp;
1987 struct rcu_node *rnp = rcu_get_root(rsp);
1989 WRITE_ONCE(rsp->gp_activity, jiffies);
1990 raw_spin_lock_irq(&rnp->lock);
1991 smp_mb__after_unlock_lock();
1992 gp_duration = jiffies - rsp->gp_start;
1993 if (gp_duration > rsp->gp_max)
1994 rsp->gp_max = gp_duration;
1997 * We know the grace period is complete, but to everyone else
1998 * it appears to still be ongoing. But it is also the case
1999 * that to everyone else it looks like there is nothing that
2000 * they can do to advance the grace period. It is therefore
2001 * safe for us to drop the lock in order to mark the grace
2002 * period as completed in all of the rcu_node structures.
2004 raw_spin_unlock_irq(&rnp->lock);
2007 * Propagate new ->completed value to rcu_node structures so
2008 * that other CPUs don't have to wait until the start of the next
2009 * grace period to process their callbacks. This also avoids
2010 * some nasty RCU grace-period initialization races by forcing
2011 * the end of the current grace period to be completely recorded in
2012 * all of the rcu_node structures before the beginning of the next
2013 * grace period is recorded in any of the rcu_node structures.
2015 rcu_for_each_node_breadth_first(rsp, rnp) {
2016 raw_spin_lock_irq(&rnp->lock);
2017 smp_mb__after_unlock_lock();
2018 WARN_ON_ONCE(rcu_preempt_blocked_readers_cgp(rnp));
2019 WARN_ON_ONCE(rnp->qsmask);
2020 WRITE_ONCE(rnp->completed, rsp->gpnum);
2021 rdp = this_cpu_ptr(rsp->rda);
2022 if (rnp == rdp->mynode)
2023 needgp = __note_gp_changes(rsp, rnp, rdp) || needgp;
2024 /* smp_mb() provided by prior unlock-lock pair. */
2025 nocb += rcu_future_gp_cleanup(rsp, rnp);
2026 raw_spin_unlock_irq(&rnp->lock);
2027 cond_resched_rcu_qs();
2028 WRITE_ONCE(rsp->gp_activity, jiffies);
2029 rcu_gp_slow(rsp, gp_cleanup_delay);
2031 rnp = rcu_get_root(rsp);
2032 raw_spin_lock_irq(&rnp->lock);
2033 smp_mb__after_unlock_lock(); /* Order GP before ->completed update. */
2034 rcu_nocb_gp_set(rnp, nocb);
2036 /* Declare grace period done. */
2037 WRITE_ONCE(rsp->completed, rsp->gpnum);
2038 trace_rcu_grace_period(rsp->name, rsp->completed, TPS("end"));
2039 rsp->fqs_state = RCU_GP_IDLE;
2040 rdp = this_cpu_ptr(rsp->rda);
2041 /* Advance CBs to reduce false positives below. */
2042 needgp = rcu_advance_cbs(rsp, rnp, rdp) || needgp;
2043 if (needgp || cpu_needs_another_gp(rsp, rdp)) {
2044 WRITE_ONCE(rsp->gp_flags, RCU_GP_FLAG_INIT);
2045 trace_rcu_grace_period(rsp->name,
2046 READ_ONCE(rsp->gpnum),
2049 raw_spin_unlock_irq(&rnp->lock);
2053 * Body of kthread that handles grace periods.
2055 static int __noreturn rcu_gp_kthread(void *arg)
2061 struct rcu_state *rsp = arg;
2062 struct rcu_node *rnp = rcu_get_root(rsp);
2064 rcu_bind_gp_kthread();
2067 /* Handle grace-period start. */
2069 trace_rcu_grace_period(rsp->name,
2070 READ_ONCE(rsp->gpnum),
2072 rsp->gp_state = RCU_GP_WAIT_GPS;
2073 wait_event_interruptible(rsp->gp_wq,
2074 READ_ONCE(rsp->gp_flags) &
2076 rsp->gp_state = RCU_GP_DONE_GPS;
2077 /* Locking provides needed memory barrier. */
2078 if (rcu_gp_init(rsp))
2080 cond_resched_rcu_qs();
2081 WRITE_ONCE(rsp->gp_activity, jiffies);
2082 WARN_ON(signal_pending(current));
2083 trace_rcu_grace_period(rsp->name,
2084 READ_ONCE(rsp->gpnum),
2088 /* Handle quiescent-state forcing. */
2089 fqs_state = RCU_SAVE_DYNTICK;
2090 j = jiffies_till_first_fqs;
2093 jiffies_till_first_fqs = HZ;
2098 rsp->jiffies_force_qs = jiffies + j;
2099 trace_rcu_grace_period(rsp->name,
2100 READ_ONCE(rsp->gpnum),
2102 rsp->gp_state = RCU_GP_WAIT_FQS;
2103 ret = wait_event_interruptible_timeout(rsp->gp_wq,
2104 rcu_gp_fqs_check_wake(rsp, &gf), j);
2105 rsp->gp_state = RCU_GP_DOING_FQS;
2106 /* Locking provides needed memory barriers. */
2107 /* If grace period done, leave loop. */
2108 if (!READ_ONCE(rnp->qsmask) &&
2109 !rcu_preempt_blocked_readers_cgp(rnp))
2111 /* If time for quiescent-state forcing, do it. */
2112 if (ULONG_CMP_GE(jiffies, rsp->jiffies_force_qs) ||
2113 (gf & RCU_GP_FLAG_FQS)) {
2114 trace_rcu_grace_period(rsp->name,
2115 READ_ONCE(rsp->gpnum),
2117 fqs_state = rcu_gp_fqs(rsp, fqs_state);
2118 trace_rcu_grace_period(rsp->name,
2119 READ_ONCE(rsp->gpnum),
2121 cond_resched_rcu_qs();
2122 WRITE_ONCE(rsp->gp_activity, jiffies);
2124 /* Deal with stray signal. */
2125 cond_resched_rcu_qs();
2126 WRITE_ONCE(rsp->gp_activity, jiffies);
2127 WARN_ON(signal_pending(current));
2128 trace_rcu_grace_period(rsp->name,
2129 READ_ONCE(rsp->gpnum),
2132 j = jiffies_till_next_fqs;
2135 jiffies_till_next_fqs = HZ;
2138 jiffies_till_next_fqs = 1;
2142 /* Handle grace-period end. */
2143 rsp->gp_state = RCU_GP_CLEANUP;
2144 rcu_gp_cleanup(rsp);
2145 rsp->gp_state = RCU_GP_CLEANED;
2150 * Start a new RCU grace period if warranted, re-initializing the hierarchy
2151 * in preparation for detecting the next grace period. The caller must hold
2152 * the root node's ->lock and hard irqs must be disabled.
2154 * Note that it is legal for a dying CPU (which is marked as offline) to
2155 * invoke this function. This can happen when the dying CPU reports its
2158 * Returns true if the grace-period kthread must be awakened.
2161 rcu_start_gp_advanced(struct rcu_state *rsp, struct rcu_node *rnp,
2162 struct rcu_data *rdp)
2164 if (!rsp->gp_kthread || !cpu_needs_another_gp(rsp, rdp)) {
2166 * Either we have not yet spawned the grace-period
2167 * task, this CPU does not need another grace period,
2168 * or a grace period is already in progress.
2169 * Either way, don't start a new grace period.
2173 WRITE_ONCE(rsp->gp_flags, RCU_GP_FLAG_INIT);
2174 trace_rcu_grace_period(rsp->name, READ_ONCE(rsp->gpnum),
2178 * We can't do wakeups while holding the rnp->lock, as that
2179 * could cause possible deadlocks with the rq->lock. Defer
2180 * the wakeup to our caller.
2186 * Similar to rcu_start_gp_advanced(), but also advance the calling CPU's
2187 * callbacks. Note that rcu_start_gp_advanced() cannot do this because it
2188 * is invoked indirectly from rcu_advance_cbs(), which would result in
2189 * endless recursion -- or would do so if it wasn't for the self-deadlock
2190 * that is encountered beforehand.
2192 * Returns true if the grace-period kthread needs to be awakened.
2194 static bool rcu_start_gp(struct rcu_state *rsp)
2196 struct rcu_data *rdp = this_cpu_ptr(rsp->rda);
2197 struct rcu_node *rnp = rcu_get_root(rsp);
2201 * If there is no grace period in progress right now, any
2202 * callbacks we have up to this point will be satisfied by the
2203 * next grace period. Also, advancing the callbacks reduces the
2204 * probability of false positives from cpu_needs_another_gp()
2205 * resulting in pointless grace periods. So, advance callbacks
2206 * then start the grace period!
2208 ret = rcu_advance_cbs(rsp, rnp, rdp) || ret;
2209 ret = rcu_start_gp_advanced(rsp, rnp, rdp) || ret;
2214 * Report a full set of quiescent states to the specified rcu_state
2215 * data structure. This involves cleaning up after the prior grace
2216 * period and letting rcu_start_gp() start up the next grace period
2217 * if one is needed. Note that the caller must hold rnp->lock, which
2218 * is released before return.
2220 static void rcu_report_qs_rsp(struct rcu_state *rsp, unsigned long flags)
2221 __releases(rcu_get_root(rsp)->lock)
2223 WARN_ON_ONCE(!rcu_gp_in_progress(rsp));
2224 WRITE_ONCE(rsp->gp_flags, READ_ONCE(rsp->gp_flags) | RCU_GP_FLAG_FQS);
2225 raw_spin_unlock_irqrestore(&rcu_get_root(rsp)->lock, flags);
2226 rcu_gp_kthread_wake(rsp);
2230 * Similar to rcu_report_qs_rdp(), for which it is a helper function.
2231 * Allows quiescent states for a group of CPUs to be reported at one go
2232 * to the specified rcu_node structure, though all the CPUs in the group
2233 * must be represented by the same rcu_node structure (which need not be a
2234 * leaf rcu_node structure, though it often will be). The gps parameter
2235 * is the grace-period snapshot, which means that the quiescent states
2236 * are valid only if rnp->gpnum is equal to gps. That structure's lock
2237 * must be held upon entry, and it is released before return.
2240 rcu_report_qs_rnp(unsigned long mask, struct rcu_state *rsp,
2241 struct rcu_node *rnp, unsigned long gps, unsigned long flags)
2242 __releases(rnp->lock)
2244 unsigned long oldmask = 0;
2245 struct rcu_node *rnp_c;
2247 /* Walk up the rcu_node hierarchy. */
2249 if (!(rnp->qsmask & mask) || rnp->gpnum != gps) {
2252 * Our bit has already been cleared, or the
2253 * relevant grace period is already over, so done.
2255 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2258 WARN_ON_ONCE(oldmask); /* Any child must be all zeroed! */
2259 rnp->qsmask &= ~mask;
2260 trace_rcu_quiescent_state_report(rsp->name, rnp->gpnum,
2261 mask, rnp->qsmask, rnp->level,
2262 rnp->grplo, rnp->grphi,
2264 if (rnp->qsmask != 0 || rcu_preempt_blocked_readers_cgp(rnp)) {
2266 /* Other bits still set at this level, so done. */
2267 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2270 mask = rnp->grpmask;
2271 if (rnp->parent == NULL) {
2273 /* No more levels. Exit loop holding root lock. */
2277 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2280 raw_spin_lock_irqsave(&rnp->lock, flags);
2281 smp_mb__after_unlock_lock();
2282 oldmask = rnp_c->qsmask;
2286 * Get here if we are the last CPU to pass through a quiescent
2287 * state for this grace period. Invoke rcu_report_qs_rsp()
2288 * to clean up and start the next grace period if one is needed.
2290 rcu_report_qs_rsp(rsp, flags); /* releases rnp->lock. */
2294 * Record a quiescent state for all tasks that were previously queued
2295 * on the specified rcu_node structure and that were blocking the current
2296 * RCU grace period. The caller must hold the specified rnp->lock with
2297 * irqs disabled, and this lock is released upon return, but irqs remain
2300 static void rcu_report_unblock_qs_rnp(struct rcu_state *rsp,
2301 struct rcu_node *rnp, unsigned long flags)
2302 __releases(rnp->lock)
2306 struct rcu_node *rnp_p;
2308 if (rcu_state_p == &rcu_sched_state || rsp != rcu_state_p ||
2309 rnp->qsmask != 0 || rcu_preempt_blocked_readers_cgp(rnp)) {
2310 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2311 return; /* Still need more quiescent states! */
2314 rnp_p = rnp->parent;
2315 if (rnp_p == NULL) {
2317 * Only one rcu_node structure in the tree, so don't
2318 * try to report up to its nonexistent parent!
2320 rcu_report_qs_rsp(rsp, flags);
2324 /* Report up the rest of the hierarchy, tracking current ->gpnum. */
2326 mask = rnp->grpmask;
2327 raw_spin_unlock(&rnp->lock); /* irqs remain disabled. */
2328 raw_spin_lock(&rnp_p->lock); /* irqs already disabled. */
2329 smp_mb__after_unlock_lock();
2330 rcu_report_qs_rnp(mask, rsp, rnp_p, gps, flags);
2334 * Record a quiescent state for the specified CPU to that CPU's rcu_data
2335 * structure. This must be either called from the specified CPU, or
2336 * called when the specified CPU is known to be offline (and when it is
2337 * also known that no other CPU is concurrently trying to help the offline
2338 * CPU). The lastcomp argument is used to make sure we are still in the
2339 * grace period of interest. We don't want to end the current grace period
2340 * based on quiescent states detected in an earlier grace period!
2343 rcu_report_qs_rdp(int cpu, struct rcu_state *rsp, struct rcu_data *rdp)
2345 unsigned long flags;
2348 struct rcu_node *rnp;
2351 raw_spin_lock_irqsave(&rnp->lock, flags);
2352 smp_mb__after_unlock_lock();
2353 if ((rdp->cpu_no_qs.b.norm &&
2354 rdp->rcu_qs_ctr_snap == __this_cpu_read(rcu_qs_ctr)) ||
2355 rdp->gpnum != rnp->gpnum || rnp->completed == rnp->gpnum ||
2359 * The grace period in which this quiescent state was
2360 * recorded has ended, so don't report it upwards.
2361 * We will instead need a new quiescent state that lies
2362 * within the current grace period.
2364 rdp->cpu_no_qs.b.norm = true; /* need qs for new gp. */
2365 rdp->rcu_qs_ctr_snap = __this_cpu_read(rcu_qs_ctr);
2366 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2369 mask = rdp->grpmask;
2370 if ((rnp->qsmask & mask) == 0) {
2371 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2373 rdp->core_needs_qs = 0;
2376 * This GP can't end until cpu checks in, so all of our
2377 * callbacks can be processed during the next GP.
2379 needwake = rcu_accelerate_cbs(rsp, rnp, rdp);
2381 rcu_report_qs_rnp(mask, rsp, rnp, rnp->gpnum, flags);
2382 /* ^^^ Released rnp->lock */
2384 rcu_gp_kthread_wake(rsp);
2389 * Check to see if there is a new grace period of which this CPU
2390 * is not yet aware, and if so, set up local rcu_data state for it.
2391 * Otherwise, see if this CPU has just passed through its first
2392 * quiescent state for this grace period, and record that fact if so.
2395 rcu_check_quiescent_state(struct rcu_state *rsp, struct rcu_data *rdp)
2397 /* Check for grace-period ends and beginnings. */
2398 note_gp_changes(rsp, rdp);
2401 * Does this CPU still need to do its part for current grace period?
2402 * If no, return and let the other CPUs do their part as well.
2404 if (!rdp->core_needs_qs)
2408 * Was there a quiescent state since the beginning of the grace
2409 * period? If no, then exit and wait for the next call.
2411 if (rdp->cpu_no_qs.b.norm &&
2412 rdp->rcu_qs_ctr_snap == __this_cpu_read(rcu_qs_ctr))
2416 * Tell RCU we are done (but rcu_report_qs_rdp() will be the
2419 rcu_report_qs_rdp(rdp->cpu, rsp, rdp);
2423 * Send the specified CPU's RCU callbacks to the orphanage. The
2424 * specified CPU must be offline, and the caller must hold the
2428 rcu_send_cbs_to_orphanage(int cpu, struct rcu_state *rsp,
2429 struct rcu_node *rnp, struct rcu_data *rdp)
2431 /* No-CBs CPUs do not have orphanable callbacks. */
2432 if (!IS_ENABLED(CONFIG_HOTPLUG_CPU) || rcu_is_nocb_cpu(rdp->cpu))
2436 * Orphan the callbacks. First adjust the counts. This is safe
2437 * because _rcu_barrier() excludes CPU-hotplug operations, so it
2438 * cannot be running now. Thus no memory barrier is required.
2440 if (rdp->nxtlist != NULL) {
2441 rsp->qlen_lazy += rdp->qlen_lazy;
2442 rsp->qlen += rdp->qlen;
2443 rdp->n_cbs_orphaned += rdp->qlen;
2445 WRITE_ONCE(rdp->qlen, 0);
2449 * Next, move those callbacks still needing a grace period to
2450 * the orphanage, where some other CPU will pick them up.
2451 * Some of the callbacks might have gone partway through a grace
2452 * period, but that is too bad. They get to start over because we
2453 * cannot assume that grace periods are synchronized across CPUs.
2454 * We don't bother updating the ->nxttail[] array yet, instead
2455 * we just reset the whole thing later on.
2457 if (*rdp->nxttail[RCU_DONE_TAIL] != NULL) {
2458 *rsp->orphan_nxttail = *rdp->nxttail[RCU_DONE_TAIL];
2459 rsp->orphan_nxttail = rdp->nxttail[RCU_NEXT_TAIL];
2460 *rdp->nxttail[RCU_DONE_TAIL] = NULL;
2464 * Then move the ready-to-invoke callbacks to the orphanage,
2465 * where some other CPU will pick them up. These will not be
2466 * required to pass though another grace period: They are done.
2468 if (rdp->nxtlist != NULL) {
2469 *rsp->orphan_donetail = rdp->nxtlist;
2470 rsp->orphan_donetail = rdp->nxttail[RCU_DONE_TAIL];
2474 * Finally, initialize the rcu_data structure's list to empty and
2475 * disallow further callbacks on this CPU.
2477 init_callback_list(rdp);
2478 rdp->nxttail[RCU_NEXT_TAIL] = NULL;
2482 * Adopt the RCU callbacks from the specified rcu_state structure's
2483 * orphanage. The caller must hold the ->orphan_lock.
2485 static void rcu_adopt_orphan_cbs(struct rcu_state *rsp, unsigned long flags)
2488 struct rcu_data *rdp = raw_cpu_ptr(rsp->rda);
2490 /* No-CBs CPUs are handled specially. */
2491 if (!IS_ENABLED(CONFIG_HOTPLUG_CPU) ||
2492 rcu_nocb_adopt_orphan_cbs(rsp, rdp, flags))
2495 /* Do the accounting first. */
2496 rdp->qlen_lazy += rsp->qlen_lazy;
2497 rdp->qlen += rsp->qlen;
2498 rdp->n_cbs_adopted += rsp->qlen;
2499 if (rsp->qlen_lazy != rsp->qlen)
2500 rcu_idle_count_callbacks_posted();
2505 * We do not need a memory barrier here because the only way we
2506 * can get here if there is an rcu_barrier() in flight is if
2507 * we are the task doing the rcu_barrier().
2510 /* First adopt the ready-to-invoke callbacks. */
2511 if (rsp->orphan_donelist != NULL) {
2512 *rsp->orphan_donetail = *rdp->nxttail[RCU_DONE_TAIL];
2513 *rdp->nxttail[RCU_DONE_TAIL] = rsp->orphan_donelist;
2514 for (i = RCU_NEXT_SIZE - 1; i >= RCU_DONE_TAIL; i--)
2515 if (rdp->nxttail[i] == rdp->nxttail[RCU_DONE_TAIL])
2516 rdp->nxttail[i] = rsp->orphan_donetail;
2517 rsp->orphan_donelist = NULL;
2518 rsp->orphan_donetail = &rsp->orphan_donelist;
2521 /* And then adopt the callbacks that still need a grace period. */
2522 if (rsp->orphan_nxtlist != NULL) {
2523 *rdp->nxttail[RCU_NEXT_TAIL] = rsp->orphan_nxtlist;
2524 rdp->nxttail[RCU_NEXT_TAIL] = rsp->orphan_nxttail;
2525 rsp->orphan_nxtlist = NULL;
2526 rsp->orphan_nxttail = &rsp->orphan_nxtlist;
2531 * Trace the fact that this CPU is going offline.
2533 static void rcu_cleanup_dying_cpu(struct rcu_state *rsp)
2535 RCU_TRACE(unsigned long mask);
2536 RCU_TRACE(struct rcu_data *rdp = this_cpu_ptr(rsp->rda));
2537 RCU_TRACE(struct rcu_node *rnp = rdp->mynode);
2539 if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))
2542 RCU_TRACE(mask = rdp->grpmask);
2543 trace_rcu_grace_period(rsp->name,
2544 rnp->gpnum + 1 - !!(rnp->qsmask & mask),
2549 * All CPUs for the specified rcu_node structure have gone offline,
2550 * and all tasks that were preempted within an RCU read-side critical
2551 * section while running on one of those CPUs have since exited their RCU
2552 * read-side critical section. Some other CPU is reporting this fact with
2553 * the specified rcu_node structure's ->lock held and interrupts disabled.
2554 * This function therefore goes up the tree of rcu_node structures,
2555 * clearing the corresponding bits in the ->qsmaskinit fields. Note that
2556 * the leaf rcu_node structure's ->qsmaskinit field has already been
2559 * This function does check that the specified rcu_node structure has
2560 * all CPUs offline and no blocked tasks, so it is OK to invoke it
2561 * prematurely. That said, invoking it after the fact will cost you
2562 * a needless lock acquisition. So once it has done its work, don't
2565 static void rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf)
2568 struct rcu_node *rnp = rnp_leaf;
2570 if (!IS_ENABLED(CONFIG_HOTPLUG_CPU) ||
2571 rnp->qsmaskinit || rcu_preempt_has_tasks(rnp))
2574 mask = rnp->grpmask;
2578 raw_spin_lock(&rnp->lock); /* irqs already disabled. */
2579 smp_mb__after_unlock_lock(); /* GP memory ordering. */
2580 rnp->qsmaskinit &= ~mask;
2581 rnp->qsmask &= ~mask;
2582 if (rnp->qsmaskinit) {
2583 raw_spin_unlock(&rnp->lock); /* irqs remain disabled. */
2586 raw_spin_unlock(&rnp->lock); /* irqs remain disabled. */
2591 * The CPU is exiting the idle loop into the arch_cpu_idle_dead()
2592 * function. We now remove it from the rcu_node tree's ->qsmaskinit
2595 static void rcu_cleanup_dying_idle_cpu(int cpu, struct rcu_state *rsp)
2597 unsigned long flags;
2599 struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
2600 struct rcu_node *rnp = rdp->mynode; /* Outgoing CPU's rdp & rnp. */
2602 if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))
2605 /* Remove outgoing CPU from mask in the leaf rcu_node structure. */
2606 mask = rdp->grpmask;
2607 raw_spin_lock_irqsave(&rnp->lock, flags);
2608 smp_mb__after_unlock_lock(); /* Enforce GP memory-order guarantee. */
2609 rnp->qsmaskinitnext &= ~mask;
2610 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2614 * The CPU has been completely removed, and some other CPU is reporting
2615 * this fact from process context. Do the remainder of the cleanup,
2616 * including orphaning the outgoing CPU's RCU callbacks, and also
2617 * adopting them. There can only be one CPU hotplug operation at a time,
2618 * so no other CPU can be attempting to update rcu_cpu_kthread_task.
2620 static void rcu_cleanup_dead_cpu(int cpu, struct rcu_state *rsp)
2622 unsigned long flags;
2623 struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
2624 struct rcu_node *rnp = rdp->mynode; /* Outgoing CPU's rdp & rnp. */
2626 if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))
2629 /* Adjust any no-longer-needed kthreads. */
2630 rcu_boost_kthread_setaffinity(rnp, -1);
2632 /* Orphan the dead CPU's callbacks, and adopt them if appropriate. */
2633 raw_spin_lock_irqsave(&rsp->orphan_lock, flags);
2634 rcu_send_cbs_to_orphanage(cpu, rsp, rnp, rdp);
2635 rcu_adopt_orphan_cbs(rsp, flags);
2636 raw_spin_unlock_irqrestore(&rsp->orphan_lock, flags);
2638 WARN_ONCE(rdp->qlen != 0 || rdp->nxtlist != NULL,
2639 "rcu_cleanup_dead_cpu: Callbacks on offline CPU %d: qlen=%lu, nxtlist=%p\n",
2640 cpu, rdp->qlen, rdp->nxtlist);
2644 * Invoke any RCU callbacks that have made it to the end of their grace
2645 * period. Thottle as specified by rdp->blimit.
2647 static void rcu_do_batch(struct rcu_state *rsp, struct rcu_data *rdp)
2649 unsigned long flags;
2650 struct rcu_head *next, *list, **tail;
2651 long bl, count, count_lazy;
2654 /* If no callbacks are ready, just return. */
2655 if (!cpu_has_callbacks_ready_to_invoke(rdp)) {
2656 trace_rcu_batch_start(rsp->name, rdp->qlen_lazy, rdp->qlen, 0);
2657 trace_rcu_batch_end(rsp->name, 0, !!READ_ONCE(rdp->nxtlist),
2658 need_resched(), is_idle_task(current),
2659 rcu_is_callbacks_kthread());
2664 * Extract the list of ready callbacks, disabling to prevent
2665 * races with call_rcu() from interrupt handlers.
2667 local_irq_save(flags);
2668 WARN_ON_ONCE(cpu_is_offline(smp_processor_id()));
2670 trace_rcu_batch_start(rsp->name, rdp->qlen_lazy, rdp->qlen, bl);
2671 list = rdp->nxtlist;
2672 rdp->nxtlist = *rdp->nxttail[RCU_DONE_TAIL];
2673 *rdp->nxttail[RCU_DONE_TAIL] = NULL;
2674 tail = rdp->nxttail[RCU_DONE_TAIL];
2675 for (i = RCU_NEXT_SIZE - 1; i >= 0; i--)
2676 if (rdp->nxttail[i] == rdp->nxttail[RCU_DONE_TAIL])
2677 rdp->nxttail[i] = &rdp->nxtlist;
2678 local_irq_restore(flags);
2680 /* Invoke callbacks. */
2681 count = count_lazy = 0;
2685 debug_rcu_head_unqueue(list);
2686 if (__rcu_reclaim(rsp->name, list))
2689 /* Stop only if limit reached and CPU has something to do. */
2690 if (++count >= bl &&
2692 (!is_idle_task(current) && !rcu_is_callbacks_kthread())))
2696 local_irq_save(flags);
2697 trace_rcu_batch_end(rsp->name, count, !!list, need_resched(),
2698 is_idle_task(current),
2699 rcu_is_callbacks_kthread());
2701 /* Update count, and requeue any remaining callbacks. */
2703 *tail = rdp->nxtlist;
2704 rdp->nxtlist = list;
2705 for (i = 0; i < RCU_NEXT_SIZE; i++)
2706 if (&rdp->nxtlist == rdp->nxttail[i])
2707 rdp->nxttail[i] = tail;
2711 smp_mb(); /* List handling before counting for rcu_barrier(). */
2712 rdp->qlen_lazy -= count_lazy;
2713 WRITE_ONCE(rdp->qlen, rdp->qlen - count);
2714 rdp->n_cbs_invoked += count;
2716 /* Reinstate batch limit if we have worked down the excess. */
2717 if (rdp->blimit == LONG_MAX && rdp->qlen <= qlowmark)
2718 rdp->blimit = blimit;
2720 /* Reset ->qlen_last_fqs_check trigger if enough CBs have drained. */
2721 if (rdp->qlen == 0 && rdp->qlen_last_fqs_check != 0) {
2722 rdp->qlen_last_fqs_check = 0;
2723 rdp->n_force_qs_snap = rsp->n_force_qs;
2724 } else if (rdp->qlen < rdp->qlen_last_fqs_check - qhimark)
2725 rdp->qlen_last_fqs_check = rdp->qlen;
2726 WARN_ON_ONCE((rdp->nxtlist == NULL) != (rdp->qlen == 0));
2728 local_irq_restore(flags);
2730 /* Re-invoke RCU core processing if there are callbacks remaining. */
2731 if (cpu_has_callbacks_ready_to_invoke(rdp))
2736 * Check to see if this CPU is in a non-context-switch quiescent state
2737 * (user mode or idle loop for rcu, non-softirq execution for rcu_bh).
2738 * Also schedule RCU core processing.
2740 * This function must be called from hardirq context. It is normally
2741 * invoked from the scheduling-clock interrupt. If rcu_pending returns
2742 * false, there is no point in invoking rcu_check_callbacks().
2744 void rcu_check_callbacks(int user)
2746 trace_rcu_utilization(TPS("Start scheduler-tick"));
2747 increment_cpu_stall_ticks();
2748 if (user || rcu_is_cpu_rrupt_from_idle()) {
2751 * Get here if this CPU took its interrupt from user
2752 * mode or from the idle loop, and if this is not a
2753 * nested interrupt. In this case, the CPU is in
2754 * a quiescent state, so note it.
2756 * No memory barrier is required here because both
2757 * rcu_sched_qs() and rcu_bh_qs() reference only CPU-local
2758 * variables that other CPUs neither access nor modify,
2759 * at least not while the corresponding CPU is online.
2765 } else if (!in_softirq()) {
2768 * Get here if this CPU did not take its interrupt from
2769 * softirq, in other words, if it is not interrupting
2770 * a rcu_bh read-side critical section. This is an _bh
2771 * critical section, so note it.
2776 rcu_preempt_check_callbacks();
2780 rcu_note_voluntary_context_switch(current);
2781 trace_rcu_utilization(TPS("End scheduler-tick"));
2785 * Scan the leaf rcu_node structures, processing dyntick state for any that
2786 * have not yet encountered a quiescent state, using the function specified.
2787 * Also initiate boosting for any threads blocked on the root rcu_node.
2789 * The caller must have suppressed start of new grace periods.
2791 static void force_qs_rnp(struct rcu_state *rsp,
2792 int (*f)(struct rcu_data *rsp, bool *isidle,
2793 unsigned long *maxj),
2794 bool *isidle, unsigned long *maxj)
2798 unsigned long flags;
2800 struct rcu_node *rnp;
2802 rcu_for_each_leaf_node(rsp, rnp) {
2803 cond_resched_rcu_qs();
2805 raw_spin_lock_irqsave(&rnp->lock, flags);
2806 smp_mb__after_unlock_lock();
2807 if (rnp->qsmask == 0) {
2808 if (rcu_state_p == &rcu_sched_state ||
2809 rsp != rcu_state_p ||
2810 rcu_preempt_blocked_readers_cgp(rnp)) {
2812 * No point in scanning bits because they
2813 * are all zero. But we might need to
2814 * priority-boost blocked readers.
2816 rcu_initiate_boost(rnp, flags);
2817 /* rcu_initiate_boost() releases rnp->lock */
2821 (rnp->parent->qsmask & rnp->grpmask)) {
2823 * Race between grace-period
2824 * initialization and task exiting RCU
2825 * read-side critical section: Report.
2827 rcu_report_unblock_qs_rnp(rsp, rnp, flags);
2828 /* rcu_report_unblock_qs_rnp() rlses ->lock */
2834 for (; cpu <= rnp->grphi; cpu++, bit <<= 1) {
2835 if ((rnp->qsmask & bit) != 0) {
2836 if (f(per_cpu_ptr(rsp->rda, cpu), isidle, maxj))
2841 /* Idle/offline CPUs, report (releases rnp->lock. */
2842 rcu_report_qs_rnp(mask, rsp, rnp, rnp->gpnum, flags);
2844 /* Nothing to do here, so just drop the lock. */
2845 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2851 * Force quiescent states on reluctant CPUs, and also detect which
2852 * CPUs are in dyntick-idle mode.
2854 static void force_quiescent_state(struct rcu_state *rsp)
2856 unsigned long flags;
2858 struct rcu_node *rnp;
2859 struct rcu_node *rnp_old = NULL;
2861 /* Funnel through hierarchy to reduce memory contention. */
2862 rnp = __this_cpu_read(rsp->rda->mynode);
2863 for (; rnp != NULL; rnp = rnp->parent) {
2864 ret = (READ_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) ||
2865 !raw_spin_trylock(&rnp->fqslock);
2866 if (rnp_old != NULL)
2867 raw_spin_unlock(&rnp_old->fqslock);
2869 rsp->n_force_qs_lh++;
2874 /* rnp_old == rcu_get_root(rsp), rnp == NULL. */
2876 /* Reached the root of the rcu_node tree, acquire lock. */
2877 raw_spin_lock_irqsave(&rnp_old->lock, flags);
2878 smp_mb__after_unlock_lock();
2879 raw_spin_unlock(&rnp_old->fqslock);
2880 if (READ_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) {
2881 rsp->n_force_qs_lh++;
2882 raw_spin_unlock_irqrestore(&rnp_old->lock, flags);
2883 return; /* Someone beat us to it. */
2885 WRITE_ONCE(rsp->gp_flags, READ_ONCE(rsp->gp_flags) | RCU_GP_FLAG_FQS);
2886 raw_spin_unlock_irqrestore(&rnp_old->lock, flags);
2887 rcu_gp_kthread_wake(rsp);
2891 * This does the RCU core processing work for the specified rcu_state
2892 * and rcu_data structures. This may be called only from the CPU to
2893 * whom the rdp belongs.
2896 __rcu_process_callbacks(struct rcu_state *rsp)
2898 unsigned long flags;
2900 struct rcu_data *rdp = raw_cpu_ptr(rsp->rda);
2902 WARN_ON_ONCE(rdp->beenonline == 0);
2904 /* Update RCU state based on any recent quiescent states. */
2905 rcu_check_quiescent_state(rsp, rdp);
2907 /* Does this CPU require a not-yet-started grace period? */
2908 local_irq_save(flags);
2909 if (cpu_needs_another_gp(rsp, rdp)) {
2910 raw_spin_lock(&rcu_get_root(rsp)->lock); /* irqs disabled. */
2911 needwake = rcu_start_gp(rsp);
2912 raw_spin_unlock_irqrestore(&rcu_get_root(rsp)->lock, flags);
2914 rcu_gp_kthread_wake(rsp);
2916 local_irq_restore(flags);
2919 /* If there are callbacks ready, invoke them. */
2920 if (cpu_has_callbacks_ready_to_invoke(rdp))
2921 invoke_rcu_callbacks(rsp, rdp);
2923 /* Do any needed deferred wakeups of rcuo kthreads. */
2924 do_nocb_deferred_wakeup(rdp);
2928 * Do RCU core processing for the current CPU.
2930 static void rcu_process_callbacks(struct softirq_action *unused)
2932 struct rcu_state *rsp;
2934 if (cpu_is_offline(smp_processor_id()))
2936 trace_rcu_utilization(TPS("Start RCU core"));
2937 for_each_rcu_flavor(rsp)
2938 __rcu_process_callbacks(rsp);
2939 trace_rcu_utilization(TPS("End RCU core"));
2943 * Schedule RCU callback invocation. If the specified type of RCU
2944 * does not support RCU priority boosting, just do a direct call,
2945 * otherwise wake up the per-CPU kernel kthread. Note that because we
2946 * are running on the current CPU with softirqs disabled, the
2947 * rcu_cpu_kthread_task cannot disappear out from under us.
2949 static void invoke_rcu_callbacks(struct rcu_state *rsp, struct rcu_data *rdp)
2951 if (unlikely(!READ_ONCE(rcu_scheduler_fully_active)))
2953 if (likely(!rsp->boost)) {
2954 rcu_do_batch(rsp, rdp);
2957 invoke_rcu_callbacks_kthread();
2960 static void invoke_rcu_core(void)
2962 if (cpu_online(smp_processor_id()))
2963 raise_softirq(RCU_SOFTIRQ);
2967 * Handle any core-RCU processing required by a call_rcu() invocation.
2969 static void __call_rcu_core(struct rcu_state *rsp, struct rcu_data *rdp,
2970 struct rcu_head *head, unsigned long flags)
2975 * If called from an extended quiescent state, invoke the RCU
2976 * core in order to force a re-evaluation of RCU's idleness.
2978 if (!rcu_is_watching())
2981 /* If interrupts were disabled or CPU offline, don't invoke RCU core. */
2982 if (irqs_disabled_flags(flags) || cpu_is_offline(smp_processor_id()))
2986 * Force the grace period if too many callbacks or too long waiting.
2987 * Enforce hysteresis, and don't invoke force_quiescent_state()
2988 * if some other CPU has recently done so. Also, don't bother
2989 * invoking force_quiescent_state() if the newly enqueued callback
2990 * is the only one waiting for a grace period to complete.
2992 if (unlikely(rdp->qlen > rdp->qlen_last_fqs_check + qhimark)) {
2994 /* Are we ignoring a completed grace period? */
2995 note_gp_changes(rsp, rdp);
2997 /* Start a new grace period if one not already started. */
2998 if (!rcu_gp_in_progress(rsp)) {
2999 struct rcu_node *rnp_root = rcu_get_root(rsp);
3001 raw_spin_lock(&rnp_root->lock);
3002 smp_mb__after_unlock_lock();
3003 needwake = rcu_start_gp(rsp);
3004 raw_spin_unlock(&rnp_root->lock);
3006 rcu_gp_kthread_wake(rsp);
3008 /* Give the grace period a kick. */
3009 rdp->blimit = LONG_MAX;
3010 if (rsp->n_force_qs == rdp->n_force_qs_snap &&
3011 *rdp->nxttail[RCU_DONE_TAIL] != head)
3012 force_quiescent_state(rsp);
3013 rdp->n_force_qs_snap = rsp->n_force_qs;
3014 rdp->qlen_last_fqs_check = rdp->qlen;
3020 * RCU callback function to leak a callback.
3022 static void rcu_leak_callback(struct rcu_head *rhp)
3027 * Helper function for call_rcu() and friends. The cpu argument will
3028 * normally be -1, indicating "currently running CPU". It may specify
3029 * a CPU only if that CPU is a no-CBs CPU. Currently, only _rcu_barrier()
3030 * is expected to specify a CPU.
3033 __call_rcu(struct rcu_head *head, void (*func)(struct rcu_head *rcu),
3034 struct rcu_state *rsp, int cpu, bool lazy)
3036 unsigned long flags;
3037 struct rcu_data *rdp;
3039 WARN_ON_ONCE((unsigned long)head & 0x1); /* Misaligned rcu_head! */
3040 if (debug_rcu_head_queue(head)) {
3041 /* Probable double call_rcu(), so leak the callback. */
3042 WRITE_ONCE(head->func, rcu_leak_callback);
3043 WARN_ONCE(1, "__call_rcu(): Leaked duplicate callback\n");
3050 * Opportunistically note grace-period endings and beginnings.
3051 * Note that we might see a beginning right after we see an
3052 * end, but never vice versa, since this CPU has to pass through
3053 * a quiescent state betweentimes.
3055 local_irq_save(flags);
3056 rdp = this_cpu_ptr(rsp->rda);
3058 /* Add the callback to our list. */
3059 if (unlikely(rdp->nxttail[RCU_NEXT_TAIL] == NULL) || cpu != -1) {
3063 rdp = per_cpu_ptr(rsp->rda, cpu);
3064 if (likely(rdp->mynode)) {
3065 /* Post-boot, so this should be for a no-CBs CPU. */
3066 offline = !__call_rcu_nocb(rdp, head, lazy, flags);
3067 WARN_ON_ONCE(offline);
3068 /* Offline CPU, _call_rcu() illegal, leak callback. */
3069 local_irq_restore(flags);
3073 * Very early boot, before rcu_init(). Initialize if needed
3074 * and then drop through to queue the callback.
3077 WARN_ON_ONCE(!rcu_is_watching());
3078 if (!likely(rdp->nxtlist))
3079 init_default_callback_list(rdp);
3081 WRITE_ONCE(rdp->qlen, rdp->qlen + 1);
3085 rcu_idle_count_callbacks_posted();
3086 smp_mb(); /* Count before adding callback for rcu_barrier(). */
3087 *rdp->nxttail[RCU_NEXT_TAIL] = head;
3088 rdp->nxttail[RCU_NEXT_TAIL] = &head->next;
3090 if (__is_kfree_rcu_offset((unsigned long)func))
3091 trace_rcu_kfree_callback(rsp->name, head, (unsigned long)func,
3092 rdp->qlen_lazy, rdp->qlen);
3094 trace_rcu_callback(rsp->name, head, rdp->qlen_lazy, rdp->qlen);
3096 /* Go handle any RCU core processing required. */
3097 __call_rcu_core(rsp, rdp, head, flags);
3098 local_irq_restore(flags);
3102 * Queue an RCU-sched callback for invocation after a grace period.
3104 void call_rcu_sched(struct rcu_head *head, void (*func)(struct rcu_head *rcu))
3106 __call_rcu(head, func, &rcu_sched_state, -1, 0);
3108 EXPORT_SYMBOL_GPL(call_rcu_sched);
3111 * Queue an RCU callback for invocation after a quicker grace period.
3113 void call_rcu_bh(struct rcu_head *head, void (*func)(struct rcu_head *rcu))
3115 __call_rcu(head, func, &rcu_bh_state, -1, 0);
3117 EXPORT_SYMBOL_GPL(call_rcu_bh);
3120 * Queue an RCU callback for lazy invocation after a grace period.
3121 * This will likely be later named something like "call_rcu_lazy()",
3122 * but this change will require some way of tagging the lazy RCU
3123 * callbacks in the list of pending callbacks. Until then, this
3124 * function may only be called from __kfree_rcu().
3126 void kfree_call_rcu(struct rcu_head *head,
3127 void (*func)(struct rcu_head *rcu))
3129 __call_rcu(head, func, rcu_state_p, -1, 1);
3131 EXPORT_SYMBOL_GPL(kfree_call_rcu);
3134 * Because a context switch is a grace period for RCU-sched and RCU-bh,
3135 * any blocking grace-period wait automatically implies a grace period
3136 * if there is only one CPU online at any point time during execution
3137 * of either synchronize_sched() or synchronize_rcu_bh(). It is OK to
3138 * occasionally incorrectly indicate that there are multiple CPUs online
3139 * when there was in fact only one the whole time, as this just adds
3140 * some overhead: RCU still operates correctly.
3142 static inline int rcu_blocking_is_gp(void)
3146 might_sleep(); /* Check for RCU read-side critical section. */
3148 ret = num_online_cpus() <= 1;
3154 * synchronize_sched - wait until an rcu-sched grace period has elapsed.
3156 * Control will return to the caller some time after a full rcu-sched
3157 * grace period has elapsed, in other words after all currently executing
3158 * rcu-sched read-side critical sections have completed. These read-side
3159 * critical sections are delimited by rcu_read_lock_sched() and
3160 * rcu_read_unlock_sched(), and may be nested. Note that preempt_disable(),
3161 * local_irq_disable(), and so on may be used in place of
3162 * rcu_read_lock_sched().
3164 * This means that all preempt_disable code sequences, including NMI and
3165 * non-threaded hardware-interrupt handlers, in progress on entry will
3166 * have completed before this primitive returns. However, this does not
3167 * guarantee that softirq handlers will have completed, since in some
3168 * kernels, these handlers can run in process context, and can block.
3170 * Note that this guarantee implies further memory-ordering guarantees.
3171 * On systems with more than one CPU, when synchronize_sched() returns,
3172 * each CPU is guaranteed to have executed a full memory barrier since the
3173 * end of its last RCU-sched read-side critical section whose beginning
3174 * preceded the call to synchronize_sched(). In addition, each CPU having
3175 * an RCU read-side critical section that extends beyond the return from
3176 * synchronize_sched() is guaranteed to have executed a full memory barrier
3177 * after the beginning of synchronize_sched() and before the beginning of
3178 * that RCU read-side critical section. Note that these guarantees include
3179 * CPUs that are offline, idle, or executing in user mode, as well as CPUs
3180 * that are executing in the kernel.
3182 * Furthermore, if CPU A invoked synchronize_sched(), which returned
3183 * to its caller on CPU B, then both CPU A and CPU B are guaranteed
3184 * to have executed a full memory barrier during the execution of
3185 * synchronize_sched() -- even if CPU A and CPU B are the same CPU (but
3186 * again only if the system has more than one CPU).
3188 * This primitive provides the guarantees made by the (now removed)
3189 * synchronize_kernel() API. In contrast, synchronize_rcu() only
3190 * guarantees that rcu_read_lock() sections will have completed.
3191 * In "classic RCU", these two guarantees happen to be one and
3192 * the same, but can differ in realtime RCU implementations.
3194 void synchronize_sched(void)
3196 RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map) ||
3197 lock_is_held(&rcu_lock_map) ||
3198 lock_is_held(&rcu_sched_lock_map),
3199 "Illegal synchronize_sched() in RCU-sched read-side critical section");
3200 if (rcu_blocking_is_gp())
3202 if (rcu_gp_is_expedited())
3203 synchronize_sched_expedited();
3205 wait_rcu_gp(call_rcu_sched);
3207 EXPORT_SYMBOL_GPL(synchronize_sched);
3210 * synchronize_rcu_bh - wait until an rcu_bh grace period has elapsed.
3212 * Control will return to the caller some time after a full rcu_bh grace
3213 * period has elapsed, in other words after all currently executing rcu_bh
3214 * read-side critical sections have completed. RCU read-side critical
3215 * sections are delimited by rcu_read_lock_bh() and rcu_read_unlock_bh(),
3216 * and may be nested.
3218 * See the description of synchronize_sched() for more detailed information
3219 * on memory ordering guarantees.
3221 void synchronize_rcu_bh(void)
3223 RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map) ||
3224 lock_is_held(&rcu_lock_map) ||
3225 lock_is_held(&rcu_sched_lock_map),
3226 "Illegal synchronize_rcu_bh() in RCU-bh read-side critical section");
3227 if (rcu_blocking_is_gp())
3229 if (rcu_gp_is_expedited())
3230 synchronize_rcu_bh_expedited();
3232 wait_rcu_gp(call_rcu_bh);
3234 EXPORT_SYMBOL_GPL(synchronize_rcu_bh);
3237 * get_state_synchronize_rcu - Snapshot current RCU state
3239 * Returns a cookie that is used by a later call to cond_synchronize_rcu()
3240 * to determine whether or not a full grace period has elapsed in the
3243 unsigned long get_state_synchronize_rcu(void)
3246 * Any prior manipulation of RCU-protected data must happen
3247 * before the load from ->gpnum.
3252 * Make sure this load happens before the purportedly
3253 * time-consuming work between get_state_synchronize_rcu()
3254 * and cond_synchronize_rcu().
3256 return smp_load_acquire(&rcu_state_p->gpnum);
3258 EXPORT_SYMBOL_GPL(get_state_synchronize_rcu);
3261 * cond_synchronize_rcu - Conditionally wait for an RCU grace period
3263 * @oldstate: return value from earlier call to get_state_synchronize_rcu()
3265 * If a full RCU grace period has elapsed since the earlier call to
3266 * get_state_synchronize_rcu(), just return. Otherwise, invoke
3267 * synchronize_rcu() to wait for a full grace period.
3269 * Yes, this function does not take counter wrap into account. But
3270 * counter wrap is harmless. If the counter wraps, we have waited for
3271 * more than 2 billion grace periods (and way more on a 64-bit system!),
3272 * so waiting for one additional grace period should be just fine.
3274 void cond_synchronize_rcu(unsigned long oldstate)
3276 unsigned long newstate;
3279 * Ensure that this load happens before any RCU-destructive
3280 * actions the caller might carry out after we return.
3282 newstate = smp_load_acquire(&rcu_state_p->completed);
3283 if (ULONG_CMP_GE(oldstate, newstate))
3286 EXPORT_SYMBOL_GPL(cond_synchronize_rcu);
3289 * get_state_synchronize_sched - Snapshot current RCU-sched state
3291 * Returns a cookie that is used by a later call to cond_synchronize_sched()
3292 * to determine whether or not a full grace period has elapsed in the
3295 unsigned long get_state_synchronize_sched(void)
3298 * Any prior manipulation of RCU-protected data must happen
3299 * before the load from ->gpnum.
3304 * Make sure this load happens before the purportedly
3305 * time-consuming work between get_state_synchronize_sched()
3306 * and cond_synchronize_sched().
3308 return smp_load_acquire(&rcu_sched_state.gpnum);
3310 EXPORT_SYMBOL_GPL(get_state_synchronize_sched);
3313 * cond_synchronize_sched - Conditionally wait for an RCU-sched grace period
3315 * @oldstate: return value from earlier call to get_state_synchronize_sched()
3317 * If a full RCU-sched grace period has elapsed since the earlier call to
3318 * get_state_synchronize_sched(), just return. Otherwise, invoke
3319 * synchronize_sched() to wait for a full grace period.
3321 * Yes, this function does not take counter wrap into account. But
3322 * counter wrap is harmless. If the counter wraps, we have waited for
3323 * more than 2 billion grace periods (and way more on a 64-bit system!),
3324 * so waiting for one additional grace period should be just fine.
3326 void cond_synchronize_sched(unsigned long oldstate)
3328 unsigned long newstate;
3331 * Ensure that this load happens before any RCU-destructive
3332 * actions the caller might carry out after we return.
3334 newstate = smp_load_acquire(&rcu_sched_state.completed);
3335 if (ULONG_CMP_GE(oldstate, newstate))
3336 synchronize_sched();
3338 EXPORT_SYMBOL_GPL(cond_synchronize_sched);
3340 /* Adjust sequence number for start of update-side operation. */
3341 static void rcu_seq_start(unsigned long *sp)
3343 WRITE_ONCE(*sp, *sp + 1);
3344 smp_mb(); /* Ensure update-side operation after counter increment. */
3345 WARN_ON_ONCE(!(*sp & 0x1));
3348 /* Adjust sequence number for end of update-side operation. */
3349 static void rcu_seq_end(unsigned long *sp)
3351 smp_mb(); /* Ensure update-side operation before counter increment. */
3352 WRITE_ONCE(*sp, *sp + 1);
3353 WARN_ON_ONCE(*sp & 0x1);
3356 /* Take a snapshot of the update side's sequence number. */
3357 static unsigned long rcu_seq_snap(unsigned long *sp)
3361 smp_mb(); /* Caller's modifications seen first by other CPUs. */
3362 s = (READ_ONCE(*sp) + 3) & ~0x1;
3363 smp_mb(); /* Above access must not bleed into critical section. */
3368 * Given a snapshot from rcu_seq_snap(), determine whether or not a
3369 * full update-side operation has occurred.
3371 static bool rcu_seq_done(unsigned long *sp, unsigned long s)
3373 return ULONG_CMP_GE(READ_ONCE(*sp), s);
3376 /* Wrapper functions for expedited grace periods. */
3377 static void rcu_exp_gp_seq_start(struct rcu_state *rsp)
3379 rcu_seq_start(&rsp->expedited_sequence);
3381 static void rcu_exp_gp_seq_end(struct rcu_state *rsp)
3383 rcu_seq_end(&rsp->expedited_sequence);
3384 smp_mb(); /* Ensure that consecutive grace periods serialize. */
3386 static unsigned long rcu_exp_gp_seq_snap(struct rcu_state *rsp)
3388 return rcu_seq_snap(&rsp->expedited_sequence);
3390 static bool rcu_exp_gp_seq_done(struct rcu_state *rsp, unsigned long s)
3392 return rcu_seq_done(&rsp->expedited_sequence, s);
3396 * Reset the ->expmaskinit values in the rcu_node tree to reflect any
3397 * recent CPU-online activity. Note that these masks are not cleared
3398 * when CPUs go offline, so they reflect the union of all CPUs that have
3399 * ever been online. This means that this function normally takes its
3400 * no-work-to-do fastpath.
3402 static void sync_exp_reset_tree_hotplug(struct rcu_state *rsp)
3405 unsigned long flags;
3407 unsigned long oldmask;
3408 int ncpus = READ_ONCE(rsp->ncpus);
3409 struct rcu_node *rnp;
3410 struct rcu_node *rnp_up;
3412 /* If no new CPUs onlined since last time, nothing to do. */
3413 if (likely(ncpus == rsp->ncpus_snap))
3415 rsp->ncpus_snap = ncpus;
3418 * Each pass through the following loop propagates newly onlined
3419 * CPUs for the current rcu_node structure up the rcu_node tree.
3421 rcu_for_each_leaf_node(rsp, rnp) {
3422 raw_spin_lock_irqsave(&rnp->lock, flags);
3423 smp_mb__after_unlock_lock();
3424 if (rnp->expmaskinit == rnp->expmaskinitnext) {
3425 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3426 continue; /* No new CPUs, nothing to do. */
3429 /* Update this node's mask, track old value for propagation. */
3430 oldmask = rnp->expmaskinit;
3431 rnp->expmaskinit = rnp->expmaskinitnext;
3432 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3434 /* If was already nonzero, nothing to propagate. */
3438 /* Propagate the new CPU up the tree. */
3439 mask = rnp->grpmask;
3440 rnp_up = rnp->parent;
3443 raw_spin_lock_irqsave(&rnp_up->lock, flags);
3444 smp_mb__after_unlock_lock();
3445 if (rnp_up->expmaskinit)
3447 rnp_up->expmaskinit |= mask;
3448 raw_spin_unlock_irqrestore(&rnp_up->lock, flags);
3451 mask = rnp_up->grpmask;
3452 rnp_up = rnp_up->parent;
3458 * Reset the ->expmask values in the rcu_node tree in preparation for
3459 * a new expedited grace period.
3461 static void __maybe_unused sync_exp_reset_tree(struct rcu_state *rsp)
3463 unsigned long flags;
3464 struct rcu_node *rnp;
3466 sync_exp_reset_tree_hotplug(rsp);
3467 rcu_for_each_node_breadth_first(rsp, rnp) {
3468 raw_spin_lock_irqsave(&rnp->lock, flags);
3469 smp_mb__after_unlock_lock();
3470 WARN_ON_ONCE(rnp->expmask);
3471 rnp->expmask = rnp->expmaskinit;
3472 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3477 * Return non-zero if there is no RCU expedited grace period in progress
3478 * for the specified rcu_node structure, in other words, if all CPUs and
3479 * tasks covered by the specified rcu_node structure have done their bit
3480 * for the current expedited grace period. Works only for preemptible
3481 * RCU -- other RCU implementation use other means.
3483 * Caller must hold the root rcu_node's exp_funnel_mutex.
3485 static int sync_rcu_preempt_exp_done(struct rcu_node *rnp)
3487 return rnp->exp_tasks == NULL &&
3488 READ_ONCE(rnp->expmask) == 0;
3492 * Report the exit from RCU read-side critical section for the last task
3493 * that queued itself during or before the current expedited preemptible-RCU
3494 * grace period. This event is reported either to the rcu_node structure on
3495 * which the task was queued or to one of that rcu_node structure's ancestors,
3496 * recursively up the tree. (Calm down, calm down, we do the recursion
3499 * Caller must hold the root rcu_node's exp_funnel_mutex and the
3500 * specified rcu_node structure's ->lock.
3502 static void __rcu_report_exp_rnp(struct rcu_state *rsp, struct rcu_node *rnp,
3503 bool wake, unsigned long flags)
3504 __releases(rnp->lock)
3509 if (!sync_rcu_preempt_exp_done(rnp)) {
3511 rcu_initiate_boost(rnp, flags);
3513 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3516 if (rnp->parent == NULL) {
3517 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3519 smp_mb(); /* EGP done before wake_up(). */
3520 wake_up(&rsp->expedited_wq);
3524 mask = rnp->grpmask;
3525 raw_spin_unlock(&rnp->lock); /* irqs remain disabled */
3527 raw_spin_lock(&rnp->lock); /* irqs already disabled */
3528 smp_mb__after_unlock_lock();
3529 WARN_ON_ONCE(!(rnp->expmask & mask));
3530 rnp->expmask &= ~mask;
3535 * Report expedited quiescent state for specified node. This is a
3536 * lock-acquisition wrapper function for __rcu_report_exp_rnp().
3538 * Caller must hold the root rcu_node's exp_funnel_mutex.
3540 static void __maybe_unused rcu_report_exp_rnp(struct rcu_state *rsp,
3541 struct rcu_node *rnp, bool wake)
3543 unsigned long flags;
3545 raw_spin_lock_irqsave(&rnp->lock, flags);
3546 smp_mb__after_unlock_lock();
3547 __rcu_report_exp_rnp(rsp, rnp, wake, flags);
3551 * Report expedited quiescent state for multiple CPUs, all covered by the
3552 * specified leaf rcu_node structure. Caller must hold the root
3553 * rcu_node's exp_funnel_mutex.
3555 static void rcu_report_exp_cpu_mult(struct rcu_state *rsp, struct rcu_node *rnp,
3556 unsigned long mask, bool wake)
3558 unsigned long flags;
3560 raw_spin_lock_irqsave(&rnp->lock, flags);
3561 smp_mb__after_unlock_lock();
3562 if (!(rnp->expmask & mask)) {
3563 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3566 rnp->expmask &= ~mask;
3567 __rcu_report_exp_rnp(rsp, rnp, wake, flags); /* Releases rnp->lock. */
3571 * Report expedited quiescent state for specified rcu_data (CPU).
3572 * Caller must hold the root rcu_node's exp_funnel_mutex.
3574 static void rcu_report_exp_rdp(struct rcu_state *rsp, struct rcu_data *rdp,
3577 rcu_report_exp_cpu_mult(rsp, rdp->mynode, rdp->grpmask, wake);
3580 /* Common code for synchronize_{rcu,sched}_expedited() work-done checking. */
3581 static bool sync_exp_work_done(struct rcu_state *rsp, struct rcu_node *rnp,
3582 struct rcu_data *rdp,
3583 atomic_long_t *stat, unsigned long s)
3585 if (rcu_exp_gp_seq_done(rsp, s)) {
3587 mutex_unlock(&rnp->exp_funnel_mutex);
3589 mutex_unlock(&rdp->exp_funnel_mutex);
3590 /* Ensure test happens before caller kfree(). */
3591 smp_mb__before_atomic(); /* ^^^ */
3592 atomic_long_inc(stat);
3599 * Funnel-lock acquisition for expedited grace periods. Returns a
3600 * pointer to the root rcu_node structure, or NULL if some other
3601 * task did the expedited grace period for us.
3603 static struct rcu_node *exp_funnel_lock(struct rcu_state *rsp, unsigned long s)
3605 struct rcu_data *rdp;
3606 struct rcu_node *rnp0;
3607 struct rcu_node *rnp1 = NULL;
3610 * First try directly acquiring the root lock in order to reduce
3611 * latency in the common case where expedited grace periods are
3612 * rare. We check mutex_is_locked() to avoid pathological levels of
3613 * memory contention on ->exp_funnel_mutex in the heavy-load case.
3615 rnp0 = rcu_get_root(rsp);
3616 if (!mutex_is_locked(&rnp0->exp_funnel_mutex)) {
3617 if (mutex_trylock(&rnp0->exp_funnel_mutex)) {
3618 if (sync_exp_work_done(rsp, rnp0, NULL,
3619 &rsp->expedited_workdone0, s))
3626 * Each pass through the following loop works its way
3627 * up the rcu_node tree, returning if others have done the
3628 * work or otherwise falls through holding the root rnp's
3629 * ->exp_funnel_mutex. The mapping from CPU to rcu_node structure
3630 * can be inexact, as it is just promoting locality and is not
3631 * strictly needed for correctness.
3633 rdp = per_cpu_ptr(rsp->rda, raw_smp_processor_id());
3634 if (sync_exp_work_done(rsp, NULL, NULL, &rsp->expedited_workdone1, s))
3636 mutex_lock(&rdp->exp_funnel_mutex);
3638 for (; rnp0 != NULL; rnp0 = rnp0->parent) {
3639 if (sync_exp_work_done(rsp, rnp1, rdp,
3640 &rsp->expedited_workdone2, s))
3642 mutex_lock(&rnp0->exp_funnel_mutex);
3644 mutex_unlock(&rnp1->exp_funnel_mutex);
3646 mutex_unlock(&rdp->exp_funnel_mutex);
3649 if (sync_exp_work_done(rsp, rnp1, rdp,
3650 &rsp->expedited_workdone3, s))
3655 /* Invoked on each online non-idle CPU for expedited quiescent state. */
3656 static void sync_sched_exp_handler(void *data)
3658 struct rcu_data *rdp;
3659 struct rcu_node *rnp;
3660 struct rcu_state *rsp = data;
3662 rdp = this_cpu_ptr(rsp->rda);
3664 if (!(READ_ONCE(rnp->expmask) & rdp->grpmask) ||
3665 __this_cpu_read(rcu_sched_data.cpu_no_qs.b.exp))
3667 __this_cpu_write(rcu_sched_data.cpu_no_qs.b.exp, true);
3668 resched_cpu(smp_processor_id());
3671 /* Send IPI for expedited cleanup if needed at end of CPU-hotplug operation. */
3672 static void sync_sched_exp_online_cleanup(int cpu)
3674 struct rcu_data *rdp;
3676 struct rcu_node *rnp;
3677 struct rcu_state *rsp = &rcu_sched_state;
3679 rdp = per_cpu_ptr(rsp->rda, cpu);
3681 if (!(READ_ONCE(rnp->expmask) & rdp->grpmask))
3683 ret = smp_call_function_single(cpu, sync_sched_exp_handler, rsp, 0);
3688 * Select the nodes that the upcoming expedited grace period needs
3691 static void sync_rcu_exp_select_cpus(struct rcu_state *rsp,
3692 smp_call_func_t func)
3695 unsigned long flags;
3697 unsigned long mask_ofl_test;
3698 unsigned long mask_ofl_ipi;
3700 struct rcu_node *rnp;
3702 sync_exp_reset_tree(rsp);
3703 rcu_for_each_leaf_node(rsp, rnp) {
3704 raw_spin_lock_irqsave(&rnp->lock, flags);
3705 smp_mb__after_unlock_lock();
3707 /* Each pass checks a CPU for identity, offline, and idle. */
3709 for (cpu = rnp->grplo; cpu <= rnp->grphi; cpu++) {
3710 struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
3711 struct rcu_dynticks *rdtp = &per_cpu(rcu_dynticks, cpu);
3713 if (raw_smp_processor_id() == cpu ||
3714 !(atomic_add_return(0, &rdtp->dynticks) & 0x1))
3715 mask_ofl_test |= rdp->grpmask;
3717 mask_ofl_ipi = rnp->expmask & ~mask_ofl_test;
3720 * Need to wait for any blocked tasks as well. Note that
3721 * additional blocking tasks will also block the expedited
3722 * GP until such time as the ->expmask bits are cleared.
3724 if (rcu_preempt_has_tasks(rnp))
3725 rnp->exp_tasks = rnp->blkd_tasks.next;
3726 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3728 /* IPI the remaining CPUs for expedited quiescent state. */
3730 for (cpu = rnp->grplo; cpu <= rnp->grphi; cpu++, mask <<= 1) {
3731 if (!(mask_ofl_ipi & mask))
3734 ret = smp_call_function_single(cpu, func, rsp, 0);
3736 mask_ofl_ipi &= ~mask;
3738 /* Failed, raced with offline. */
3739 raw_spin_lock_irqsave(&rnp->lock, flags);
3740 if (cpu_online(cpu) &&
3741 (rnp->expmask & mask)) {
3742 raw_spin_unlock_irqrestore(&rnp->lock,
3744 schedule_timeout_uninterruptible(1);
3745 if (cpu_online(cpu) &&
3746 (rnp->expmask & mask))
3748 raw_spin_lock_irqsave(&rnp->lock,
3751 if (!(rnp->expmask & mask))
3752 mask_ofl_ipi &= ~mask;
3753 raw_spin_unlock_irqrestore(&rnp->lock, flags);
3756 /* Report quiescent states for those that went offline. */
3757 mask_ofl_test |= mask_ofl_ipi;
3759 rcu_report_exp_cpu_mult(rsp, rnp, mask_ofl_test, false);
3763 static void synchronize_sched_expedited_wait(struct rcu_state *rsp)
3766 unsigned long jiffies_stall;
3767 unsigned long jiffies_start;
3769 struct rcu_node *rnp;
3770 struct rcu_node *rnp_root = rcu_get_root(rsp);
3773 jiffies_stall = rcu_jiffies_till_stall_check();
3774 jiffies_start = jiffies;
3777 ret = wait_event_interruptible_timeout(
3779 sync_rcu_preempt_exp_done(rnp_root),
3784 /* Hit a signal, disable CPU stall warnings. */
3785 wait_event(rsp->expedited_wq,
3786 sync_rcu_preempt_exp_done(rnp_root));
3789 pr_err("INFO: %s detected expedited stalls on CPUs/tasks: {",
3791 rcu_for_each_leaf_node(rsp, rnp) {
3792 (void)rcu_print_task_exp_stall(rnp);
3794 for (cpu = rnp->grplo; cpu <= rnp->grphi; cpu++, mask <<= 1) {
3795 struct rcu_data *rdp;
3797 if (!(rnp->expmask & mask))
3799 rdp = per_cpu_ptr(rsp->rda, cpu);
3800 pr_cont(" %d-%c%c%c", cpu,
3801 "O."[cpu_online(cpu)],
3802 "o."[!!(rdp->grpmask & rnp->expmaskinit)],
3803 "N."[!!(rdp->grpmask & rnp->expmaskinitnext)]);
3807 pr_cont(" } %lu jiffies s: %lu\n",
3808 jiffies - jiffies_start, rsp->expedited_sequence);
3809 rcu_for_each_leaf_node(rsp, rnp) {
3811 for (cpu = rnp->grplo; cpu <= rnp->grphi; cpu++, mask <<= 1) {
3812 if (!(rnp->expmask & mask))
3817 jiffies_stall = 3 * rcu_jiffies_till_stall_check() + 3;
3822 * synchronize_sched_expedited - Brute-force RCU-sched grace period
3824 * Wait for an RCU-sched grace period to elapse, but use a "big hammer"
3825 * approach to force the grace period to end quickly. This consumes
3826 * significant time on all CPUs and is unfriendly to real-time workloads,
3827 * so is thus not recommended for any sort of common-case code. In fact,
3828 * if you are using synchronize_sched_expedited() in a loop, please
3829 * restructure your code to batch your updates, and then use a single
3830 * synchronize_sched() instead.
3832 * This implementation can be thought of as an application of sequence
3833 * locking to expedited grace periods, but using the sequence counter to
3834 * determine when someone else has already done the work instead of for
3837 void synchronize_sched_expedited(void)
3840 struct rcu_node *rnp;
3841 struct rcu_state *rsp = &rcu_sched_state;
3843 /* Take a snapshot of the sequence number. */
3844 s = rcu_exp_gp_seq_snap(rsp);
3846 rnp = exp_funnel_lock(rsp, s);
3848 return; /* Someone else did our work for us. */
3850 rcu_exp_gp_seq_start(rsp);
3851 sync_rcu_exp_select_cpus(rsp, sync_sched_exp_handler);
3852 synchronize_sched_expedited_wait(rsp);
3854 rcu_exp_gp_seq_end(rsp);
3855 mutex_unlock(&rnp->exp_funnel_mutex);
3857 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
3860 * Check to see if there is any immediate RCU-related work to be done
3861 * by the current CPU, for the specified type of RCU, returning 1 if so.
3862 * The checks are in order of increasing expense: checks that can be
3863 * carried out against CPU-local state are performed first. However,
3864 * we must check for CPU stalls first, else we might not get a chance.
3866 static int __rcu_pending(struct rcu_state *rsp, struct rcu_data *rdp)
3868 struct rcu_node *rnp = rdp->mynode;
3870 rdp->n_rcu_pending++;
3872 /* Check for CPU stalls, if enabled. */
3873 check_cpu_stall(rsp, rdp);
3875 /* Is this CPU a NO_HZ_FULL CPU that should ignore RCU? */
3876 if (rcu_nohz_full_cpu(rsp))
3879 /* Is the RCU core waiting for a quiescent state from this CPU? */
3880 if (rcu_scheduler_fully_active &&
3881 rdp->core_needs_qs && rdp->cpu_no_qs.b.norm &&
3882 rdp->rcu_qs_ctr_snap == __this_cpu_read(rcu_qs_ctr)) {
3883 rdp->n_rp_core_needs_qs++;
3884 } else if (rdp->core_needs_qs &&
3885 (!rdp->cpu_no_qs.b.norm ||
3886 rdp->rcu_qs_ctr_snap != __this_cpu_read(rcu_qs_ctr))) {
3887 rdp->n_rp_report_qs++;
3891 /* Does this CPU have callbacks ready to invoke? */
3892 if (cpu_has_callbacks_ready_to_invoke(rdp)) {
3893 rdp->n_rp_cb_ready++;
3897 /* Has RCU gone idle with this CPU needing another grace period? */
3898 if (cpu_needs_another_gp(rsp, rdp)) {
3899 rdp->n_rp_cpu_needs_gp++;
3903 /* Has another RCU grace period completed? */
3904 if (READ_ONCE(rnp->completed) != rdp->completed) { /* outside lock */
3905 rdp->n_rp_gp_completed++;
3909 /* Has a new RCU grace period started? */
3910 if (READ_ONCE(rnp->gpnum) != rdp->gpnum ||
3911 unlikely(READ_ONCE(rdp->gpwrap))) { /* outside lock */
3912 rdp->n_rp_gp_started++;
3916 /* Does this CPU need a deferred NOCB wakeup? */
3917 if (rcu_nocb_need_deferred_wakeup(rdp)) {
3918 rdp->n_rp_nocb_defer_wakeup++;
3923 rdp->n_rp_need_nothing++;
3928 * Check to see if there is any immediate RCU-related work to be done
3929 * by the current CPU, returning 1 if so. This function is part of the
3930 * RCU implementation; it is -not- an exported member of the RCU API.
3932 static int rcu_pending(void)
3934 struct rcu_state *rsp;
3936 for_each_rcu_flavor(rsp)
3937 if (__rcu_pending(rsp, this_cpu_ptr(rsp->rda)))
3943 * Return true if the specified CPU has any callback. If all_lazy is
3944 * non-NULL, store an indication of whether all callbacks are lazy.
3945 * (If there are no callbacks, all of them are deemed to be lazy.)
3947 static bool __maybe_unused rcu_cpu_has_callbacks(bool *all_lazy)
3951 struct rcu_data *rdp;
3952 struct rcu_state *rsp;
3954 for_each_rcu_flavor(rsp) {
3955 rdp = this_cpu_ptr(rsp->rda);
3959 if (rdp->qlen != rdp->qlen_lazy || !all_lazy) {
3970 * Helper function for _rcu_barrier() tracing. If tracing is disabled,
3971 * the compiler is expected to optimize this away.
3973 static void _rcu_barrier_trace(struct rcu_state *rsp, const char *s,
3974 int cpu, unsigned long done)
3976 trace_rcu_barrier(rsp->name, s, cpu,
3977 atomic_read(&rsp->barrier_cpu_count), done);
3981 * RCU callback function for _rcu_barrier(). If we are last, wake
3982 * up the task executing _rcu_barrier().
3984 static void rcu_barrier_callback(struct rcu_head *rhp)
3986 struct rcu_data *rdp = container_of(rhp, struct rcu_data, barrier_head);
3987 struct rcu_state *rsp = rdp->rsp;
3989 if (atomic_dec_and_test(&rsp->barrier_cpu_count)) {
3990 _rcu_barrier_trace(rsp, "LastCB", -1, rsp->barrier_sequence);
3991 complete(&rsp->barrier_completion);
3993 _rcu_barrier_trace(rsp, "CB", -1, rsp->barrier_sequence);
3998 * Called with preemption disabled, and from cross-cpu IRQ context.
4000 static void rcu_barrier_func(void *type)
4002 struct rcu_state *rsp = type;
4003 struct rcu_data *rdp = raw_cpu_ptr(rsp->rda);
4005 _rcu_barrier_trace(rsp, "IRQ", -1, rsp->barrier_sequence);
4006 atomic_inc(&rsp->barrier_cpu_count);
4007 rsp->call(&rdp->barrier_head, rcu_barrier_callback);
4011 * Orchestrate the specified type of RCU barrier, waiting for all
4012 * RCU callbacks of the specified type to complete.
4014 static void _rcu_barrier(struct rcu_state *rsp)
4017 struct rcu_data *rdp;
4018 unsigned long s = rcu_seq_snap(&rsp->barrier_sequence);
4020 _rcu_barrier_trace(rsp, "Begin", -1, s);
4022 /* Take mutex to serialize concurrent rcu_barrier() requests. */
4023 mutex_lock(&rsp->barrier_mutex);
4025 /* Did someone else do our work for us? */
4026 if (rcu_seq_done(&rsp->barrier_sequence, s)) {
4027 _rcu_barrier_trace(rsp, "EarlyExit", -1, rsp->barrier_sequence);
4028 smp_mb(); /* caller's subsequent code after above check. */
4029 mutex_unlock(&rsp->barrier_mutex);
4033 /* Mark the start of the barrier operation. */
4034 rcu_seq_start(&rsp->barrier_sequence);
4035 _rcu_barrier_trace(rsp, "Inc1", -1, rsp->barrier_sequence);
4038 * Initialize the count to one rather than to zero in order to
4039 * avoid a too-soon return to zero in case of a short grace period
4040 * (or preemption of this task). Exclude CPU-hotplug operations
4041 * to ensure that no offline CPU has callbacks queued.
4043 init_completion(&rsp->barrier_completion);
4044 atomic_set(&rsp->barrier_cpu_count, 1);
4048 * Force each CPU with callbacks to register a new callback.
4049 * When that callback is invoked, we will know that all of the
4050 * corresponding CPU's preceding callbacks have been invoked.
4052 for_each_possible_cpu(cpu) {
4053 if (!cpu_online(cpu) && !rcu_is_nocb_cpu(cpu))
4055 rdp = per_cpu_ptr(rsp->rda, cpu);
4056 if (rcu_is_nocb_cpu(cpu)) {
4057 if (!rcu_nocb_cpu_needs_barrier(rsp, cpu)) {
4058 _rcu_barrier_trace(rsp, "OfflineNoCB", cpu,
4059 rsp->barrier_sequence);
4061 _rcu_barrier_trace(rsp, "OnlineNoCB", cpu,
4062 rsp->barrier_sequence);
4063 smp_mb__before_atomic();
4064 atomic_inc(&rsp->barrier_cpu_count);
4065 __call_rcu(&rdp->barrier_head,
4066 rcu_barrier_callback, rsp, cpu, 0);
4068 } else if (READ_ONCE(rdp->qlen)) {
4069 _rcu_barrier_trace(rsp, "OnlineQ", cpu,
4070 rsp->barrier_sequence);
4071 smp_call_function_single(cpu, rcu_barrier_func, rsp, 1);
4073 _rcu_barrier_trace(rsp, "OnlineNQ", cpu,
4074 rsp->barrier_sequence);
4080 * Now that we have an rcu_barrier_callback() callback on each
4081 * CPU, and thus each counted, remove the initial count.
4083 if (atomic_dec_and_test(&rsp->barrier_cpu_count))
4084 complete(&rsp->barrier_completion);
4086 /* Wait for all rcu_barrier_callback() callbacks to be invoked. */
4087 wait_for_completion(&rsp->barrier_completion);
4089 /* Mark the end of the barrier operation. */
4090 _rcu_barrier_trace(rsp, "Inc2", -1, rsp->barrier_sequence);
4091 rcu_seq_end(&rsp->barrier_sequence);
4093 /* Other rcu_barrier() invocations can now safely proceed. */
4094 mutex_unlock(&rsp->barrier_mutex);
4098 * rcu_barrier_bh - Wait until all in-flight call_rcu_bh() callbacks complete.
4100 void rcu_barrier_bh(void)
4102 _rcu_barrier(&rcu_bh_state);
4104 EXPORT_SYMBOL_GPL(rcu_barrier_bh);
4107 * rcu_barrier_sched - Wait for in-flight call_rcu_sched() callbacks.
4109 void rcu_barrier_sched(void)
4111 _rcu_barrier(&rcu_sched_state);
4113 EXPORT_SYMBOL_GPL(rcu_barrier_sched);
4116 * Propagate ->qsinitmask bits up the rcu_node tree to account for the
4117 * first CPU in a given leaf rcu_node structure coming online. The caller
4118 * must hold the corresponding leaf rcu_node ->lock with interrrupts
4121 static void rcu_init_new_rnp(struct rcu_node *rnp_leaf)
4124 struct rcu_node *rnp = rnp_leaf;
4127 mask = rnp->grpmask;
4131 raw_spin_lock(&rnp->lock); /* Interrupts already disabled. */
4132 rnp->qsmaskinit |= mask;
4133 raw_spin_unlock(&rnp->lock); /* Interrupts remain disabled. */
4138 * Do boot-time initialization of a CPU's per-CPU RCU data.
4141 rcu_boot_init_percpu_data(int cpu, struct rcu_state *rsp)
4143 unsigned long flags;
4144 struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
4145 struct rcu_node *rnp = rcu_get_root(rsp);
4147 /* Set up local state, ensuring consistent view of global state. */
4148 raw_spin_lock_irqsave(&rnp->lock, flags);
4149 rdp->grpmask = 1UL << (cpu - rdp->mynode->grplo);
4150 rdp->dynticks = &per_cpu(rcu_dynticks, cpu);
4151 WARN_ON_ONCE(rdp->dynticks->dynticks_nesting != DYNTICK_TASK_EXIT_IDLE);
4152 WARN_ON_ONCE(atomic_read(&rdp->dynticks->dynticks) != 1);
4155 mutex_init(&rdp->exp_funnel_mutex);
4156 rcu_boot_init_nocb_percpu_data(rdp);
4157 raw_spin_unlock_irqrestore(&rnp->lock, flags);
4161 * Initialize a CPU's per-CPU RCU data. Note that only one online or
4162 * offline event can be happening at a given time. Note also that we
4163 * can accept some slop in the rsp->completed access due to the fact
4164 * that this CPU cannot possibly have any RCU callbacks in flight yet.
4167 rcu_init_percpu_data(int cpu, struct rcu_state *rsp)
4169 unsigned long flags;
4171 struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
4172 struct rcu_node *rnp = rcu_get_root(rsp);
4174 /* Set up local state, ensuring consistent view of global state. */
4175 raw_spin_lock_irqsave(&rnp->lock, flags);
4176 rdp->qlen_last_fqs_check = 0;
4177 rdp->n_force_qs_snap = rsp->n_force_qs;
4178 rdp->blimit = blimit;
4180 init_callback_list(rdp); /* Re-enable callbacks on this CPU. */
4181 rdp->dynticks->dynticks_nesting = DYNTICK_TASK_EXIT_IDLE;
4182 rcu_sysidle_init_percpu_data(rdp->dynticks);
4183 atomic_set(&rdp->dynticks->dynticks,
4184 (atomic_read(&rdp->dynticks->dynticks) & ~0x1) + 1);
4185 raw_spin_unlock(&rnp->lock); /* irqs remain disabled. */
4188 * Add CPU to leaf rcu_node pending-online bitmask. Any needed
4189 * propagation up the rcu_node tree will happen at the beginning
4190 * of the next grace period.
4193 mask = rdp->grpmask;
4194 raw_spin_lock(&rnp->lock); /* irqs already disabled. */
4195 smp_mb__after_unlock_lock();
4196 rnp->qsmaskinitnext |= mask;
4197 rnp->expmaskinitnext |= mask;
4198 if (!rdp->beenonline)
4199 WRITE_ONCE(rsp->ncpus, READ_ONCE(rsp->ncpus) + 1);
4200 rdp->beenonline = true; /* We have now been online. */
4201 rdp->gpnum = rnp->completed; /* Make CPU later note any new GP. */
4202 rdp->completed = rnp->completed;
4203 rdp->cpu_no_qs.b.norm = true;
4204 rdp->rcu_qs_ctr_snap = per_cpu(rcu_qs_ctr, cpu);
4205 rdp->core_needs_qs = false;
4206 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("cpuonl"));
4207 raw_spin_unlock_irqrestore(&rnp->lock, flags);
4210 static void rcu_prepare_cpu(int cpu)
4212 struct rcu_state *rsp;
4214 for_each_rcu_flavor(rsp)
4215 rcu_init_percpu_data(cpu, rsp);
4219 * Handle CPU online/offline notification events.
4221 int rcu_cpu_notify(struct notifier_block *self,
4222 unsigned long action, void *hcpu)
4224 long cpu = (long)hcpu;
4225 struct rcu_data *rdp = per_cpu_ptr(rcu_state_p->rda, cpu);
4226 struct rcu_node *rnp = rdp->mynode;
4227 struct rcu_state *rsp;
4230 case CPU_UP_PREPARE:
4231 case CPU_UP_PREPARE_FROZEN:
4232 rcu_prepare_cpu(cpu);
4233 rcu_prepare_kthreads(cpu);
4234 rcu_spawn_all_nocb_kthreads(cpu);
4237 case CPU_DOWN_FAILED:
4238 sync_sched_exp_online_cleanup(cpu);
4239 rcu_boost_kthread_setaffinity(rnp, -1);
4241 case CPU_DOWN_PREPARE:
4242 rcu_boost_kthread_setaffinity(rnp, cpu);
4245 case CPU_DYING_FROZEN:
4246 for_each_rcu_flavor(rsp)
4247 rcu_cleanup_dying_cpu(rsp);
4249 case CPU_DYING_IDLE:
4250 /* QS for any half-done expedited RCU-sched GP. */
4252 rcu_report_exp_rdp(&rcu_sched_state,
4253 this_cpu_ptr(rcu_sched_state.rda), true);
4256 for_each_rcu_flavor(rsp) {
4257 rcu_cleanup_dying_idle_cpu(cpu, rsp);
4261 case CPU_DEAD_FROZEN:
4262 case CPU_UP_CANCELED:
4263 case CPU_UP_CANCELED_FROZEN:
4264 for_each_rcu_flavor(rsp) {
4265 rcu_cleanup_dead_cpu(cpu, rsp);
4266 do_nocb_deferred_wakeup(per_cpu_ptr(rsp->rda, cpu));
4275 static int rcu_pm_notify(struct notifier_block *self,
4276 unsigned long action, void *hcpu)
4279 case PM_HIBERNATION_PREPARE:
4280 case PM_SUSPEND_PREPARE:
4281 if (nr_cpu_ids <= 256) /* Expediting bad for large systems. */
4284 case PM_POST_HIBERNATION:
4285 case PM_POST_SUSPEND:
4286 if (nr_cpu_ids <= 256) /* Expediting bad for large systems. */
4287 rcu_unexpedite_gp();
4296 * Spawn the kthreads that handle each RCU flavor's grace periods.
4298 static int __init rcu_spawn_gp_kthread(void)
4300 unsigned long flags;
4301 int kthread_prio_in = kthread_prio;
4302 struct rcu_node *rnp;
4303 struct rcu_state *rsp;
4304 struct sched_param sp;
4305 struct task_struct *t;
4307 /* Force priority into range. */
4308 if (IS_ENABLED(CONFIG_RCU_BOOST) && kthread_prio < 1)
4310 else if (kthread_prio < 0)
4312 else if (kthread_prio > 99)
4314 if (kthread_prio != kthread_prio_in)
4315 pr_alert("rcu_spawn_gp_kthread(): Limited prio to %d from %d\n",
4316 kthread_prio, kthread_prio_in);
4318 rcu_scheduler_fully_active = 1;
4319 for_each_rcu_flavor(rsp) {
4320 t = kthread_create(rcu_gp_kthread, rsp, "%s", rsp->name);
4322 rnp = rcu_get_root(rsp);
4323 raw_spin_lock_irqsave(&rnp->lock, flags);
4324 rsp->gp_kthread = t;
4326 sp.sched_priority = kthread_prio;
4327 sched_setscheduler_nocheck(t, SCHED_FIFO, &sp);
4330 raw_spin_unlock_irqrestore(&rnp->lock, flags);
4332 rcu_spawn_nocb_kthreads();
4333 rcu_spawn_boost_kthreads();
4336 early_initcall(rcu_spawn_gp_kthread);
4339 * This function is invoked towards the end of the scheduler's initialization
4340 * process. Before this is called, the idle task might contain
4341 * RCU read-side critical sections (during which time, this idle
4342 * task is booting the system). After this function is called, the
4343 * idle tasks are prohibited from containing RCU read-side critical
4344 * sections. This function also enables RCU lockdep checking.
4346 void rcu_scheduler_starting(void)
4348 WARN_ON(num_online_cpus() != 1);
4349 WARN_ON(nr_context_switches() > 0);
4350 rcu_scheduler_active = 1;
4354 * Compute the per-level fanout, either using the exact fanout specified
4355 * or balancing the tree, depending on the rcu_fanout_exact boot parameter.
4357 static void __init rcu_init_levelspread(int *levelspread, const int *levelcnt)
4361 if (rcu_fanout_exact) {
4362 levelspread[rcu_num_lvls - 1] = rcu_fanout_leaf;
4363 for (i = rcu_num_lvls - 2; i >= 0; i--)
4364 levelspread[i] = RCU_FANOUT;
4370 for (i = rcu_num_lvls - 1; i >= 0; i--) {
4372 levelspread[i] = (cprv + ccur - 1) / ccur;
4379 * Helper function for rcu_init() that initializes one rcu_state structure.
4381 static void __init rcu_init_one(struct rcu_state *rsp,
4382 struct rcu_data __percpu *rda)
4384 static const char * const buf[] = RCU_NODE_NAME_INIT;
4385 static const char * const fqs[] = RCU_FQS_NAME_INIT;
4386 static const char * const exp[] = RCU_EXP_NAME_INIT;
4387 static u8 fl_mask = 0x1;
4389 int levelcnt[RCU_NUM_LVLS]; /* # nodes in each level. */
4390 int levelspread[RCU_NUM_LVLS]; /* kids/node in each level. */
4394 struct rcu_node *rnp;
4396 BUILD_BUG_ON(RCU_NUM_LVLS > ARRAY_SIZE(buf)); /* Fix buf[] init! */
4398 /* Silence gcc 4.8 false positive about array index out of range. */
4399 if (rcu_num_lvls <= 0 || rcu_num_lvls > RCU_NUM_LVLS)
4400 panic("rcu_init_one: rcu_num_lvls out of range");
4402 /* Initialize the level-tracking arrays. */
4404 for (i = 0; i < rcu_num_lvls; i++)
4405 levelcnt[i] = num_rcu_lvl[i];
4406 for (i = 1; i < rcu_num_lvls; i++)
4407 rsp->level[i] = rsp->level[i - 1] + levelcnt[i - 1];
4408 rcu_init_levelspread(levelspread, levelcnt);
4409 rsp->flavor_mask = fl_mask;
4412 /* Initialize the elements themselves, starting from the leaves. */
4414 for (i = rcu_num_lvls - 1; i >= 0; i--) {
4415 cpustride *= levelspread[i];
4416 rnp = rsp->level[i];
4417 for (j = 0; j < levelcnt[i]; j++, rnp++) {
4418 raw_spin_lock_init(&rnp->lock);
4419 lockdep_set_class_and_name(&rnp->lock,
4420 &rcu_node_class[i], buf[i]);
4421 raw_spin_lock_init(&rnp->fqslock);
4422 lockdep_set_class_and_name(&rnp->fqslock,
4423 &rcu_fqs_class[i], fqs[i]);
4424 rnp->gpnum = rsp->gpnum;
4425 rnp->completed = rsp->completed;
4427 rnp->qsmaskinit = 0;
4428 rnp->grplo = j * cpustride;
4429 rnp->grphi = (j + 1) * cpustride - 1;
4430 if (rnp->grphi >= nr_cpu_ids)
4431 rnp->grphi = nr_cpu_ids - 1;
4437 rnp->grpnum = j % levelspread[i - 1];
4438 rnp->grpmask = 1UL << rnp->grpnum;
4439 rnp->parent = rsp->level[i - 1] +
4440 j / levelspread[i - 1];
4443 INIT_LIST_HEAD(&rnp->blkd_tasks);
4444 rcu_init_one_nocb(rnp);
4445 mutex_init(&rnp->exp_funnel_mutex);
4446 lockdep_set_class_and_name(&rnp->exp_funnel_mutex,
4447 &rcu_exp_class[i], exp[i]);
4451 init_waitqueue_head(&rsp->gp_wq);
4452 init_waitqueue_head(&rsp->expedited_wq);
4453 rnp = rsp->level[rcu_num_lvls - 1];
4454 for_each_possible_cpu(i) {
4455 while (i > rnp->grphi)
4457 per_cpu_ptr(rsp->rda, i)->mynode = rnp;
4458 rcu_boot_init_percpu_data(i, rsp);
4460 list_add(&rsp->flavors, &rcu_struct_flavors);
4464 * Compute the rcu_node tree geometry from kernel parameters. This cannot
4465 * replace the definitions in tree.h because those are needed to size
4466 * the ->node array in the rcu_state structure.
4468 static void __init rcu_init_geometry(void)
4472 int rcu_capacity[RCU_NUM_LVLS];
4475 * Initialize any unspecified boot parameters.
4476 * The default values of jiffies_till_first_fqs and
4477 * jiffies_till_next_fqs are set to the RCU_JIFFIES_TILL_FORCE_QS
4478 * value, which is a function of HZ, then adding one for each
4479 * RCU_JIFFIES_FQS_DIV CPUs that might be on the system.
4481 d = RCU_JIFFIES_TILL_FORCE_QS + nr_cpu_ids / RCU_JIFFIES_FQS_DIV;
4482 if (jiffies_till_first_fqs == ULONG_MAX)
4483 jiffies_till_first_fqs = d;
4484 if (jiffies_till_next_fqs == ULONG_MAX)
4485 jiffies_till_next_fqs = d;
4487 /* If the compile-time values are accurate, just leave. */
4488 if (rcu_fanout_leaf == RCU_FANOUT_LEAF &&
4489 nr_cpu_ids == NR_CPUS)
4491 pr_info("RCU: Adjusting geometry for rcu_fanout_leaf=%d, nr_cpu_ids=%d\n",
4492 rcu_fanout_leaf, nr_cpu_ids);
4495 * The boot-time rcu_fanout_leaf parameter is only permitted
4496 * to increase the leaf-level fanout, not decrease it. Of course,
4497 * the leaf-level fanout cannot exceed the number of bits in
4498 * the rcu_node masks. Complain and fall back to the compile-
4499 * time values if these limits are exceeded.
4501 if (rcu_fanout_leaf < RCU_FANOUT_LEAF ||
4502 rcu_fanout_leaf > sizeof(unsigned long) * 8) {
4503 rcu_fanout_leaf = RCU_FANOUT_LEAF;
4509 * Compute number of nodes that can be handled an rcu_node tree
4510 * with the given number of levels.
4512 rcu_capacity[0] = rcu_fanout_leaf;
4513 for (i = 1; i < RCU_NUM_LVLS; i++)
4514 rcu_capacity[i] = rcu_capacity[i - 1] * RCU_FANOUT;
4517 * The tree must be able to accommodate the configured number of CPUs.
4518 * If this limit is exceeded than we have a serious problem elsewhere.
4520 if (nr_cpu_ids > rcu_capacity[RCU_NUM_LVLS - 1])
4521 panic("rcu_init_geometry: rcu_capacity[] is too small");
4523 /* Calculate the number of levels in the tree. */
4524 for (i = 0; nr_cpu_ids > rcu_capacity[i]; i++) {
4526 rcu_num_lvls = i + 1;
4528 /* Calculate the number of rcu_nodes at each level of the tree. */
4529 for (i = 0; i < rcu_num_lvls; i++) {
4530 int cap = rcu_capacity[(rcu_num_lvls - 1) - i];
4531 num_rcu_lvl[i] = DIV_ROUND_UP(nr_cpu_ids, cap);
4534 /* Calculate the total number of rcu_node structures. */
4536 for (i = 0; i < rcu_num_lvls; i++)
4537 rcu_num_nodes += num_rcu_lvl[i];
4541 * Dump out the structure of the rcu_node combining tree associated
4542 * with the rcu_state structure referenced by rsp.
4544 static void __init rcu_dump_rcu_node_tree(struct rcu_state *rsp)
4547 struct rcu_node *rnp;
4549 pr_info("rcu_node tree layout dump\n");
4551 rcu_for_each_node_breadth_first(rsp, rnp) {
4552 if (rnp->level != level) {
4557 pr_cont("%d:%d ^%d ", rnp->grplo, rnp->grphi, rnp->grpnum);
4562 void __init rcu_init(void)
4566 rcu_early_boot_tests();
4568 rcu_bootup_announce();
4569 rcu_init_geometry();
4570 rcu_init_one(&rcu_bh_state, &rcu_bh_data);
4571 rcu_init_one(&rcu_sched_state, &rcu_sched_data);
4573 rcu_dump_rcu_node_tree(&rcu_sched_state);
4574 __rcu_init_preempt();
4575 open_softirq(RCU_SOFTIRQ, rcu_process_callbacks);
4578 * We don't need protection against CPU-hotplug here because
4579 * this is called early in boot, before either interrupts
4580 * or the scheduler are operational.
4582 cpu_notifier(rcu_cpu_notify, 0);
4583 pm_notifier(rcu_pm_notify, 0);
4584 for_each_online_cpu(cpu)
4585 rcu_cpu_notify(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
4588 #include "tree_plugin.h"