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