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