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