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