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