Add the rt linux 4.1.3-rt3 as base
[kvmfornfv.git] / kernel / kernel / rcu / tree.c
1 /*
2  * Read-Copy Update mechanism for mutual exclusion
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, you can access it online at
16  * http://www.gnu.org/licenses/gpl-2.0.html.
17  *
18  * Copyright IBM Corporation, 2008
19  *
20  * Authors: Dipankar Sarma <dipankar@in.ibm.com>
21  *          Manfred Spraul <manfred@colorfullife.com>
22  *          Paul E. McKenney <paulmck@linux.vnet.ibm.com> Hierarchical version
23  *
24  * Based on the original work by Paul McKenney <paulmck@us.ibm.com>
25  * and inputs from Rusty Russell, Andrea Arcangeli and Andi Kleen.
26  *
27  * For detailed explanation of Read-Copy Update mechanism see -
28  *      Documentation/RCU
29  */
30 #include <linux/types.h>
31 #include <linux/kernel.h>
32 #include <linux/init.h>
33 #include <linux/spinlock.h>
34 #include <linux/smp.h>
35 #include <linux/rcupdate.h>
36 #include <linux/interrupt.h>
37 #include <linux/sched.h>
38 #include <linux/nmi.h>
39 #include <linux/atomic.h>
40 #include <linux/bitops.h>
41 #include <linux/export.h>
42 #include <linux/completion.h>
43 #include <linux/moduleparam.h>
44 #include <linux/module.h>
45 #include <linux/percpu.h>
46 #include <linux/notifier.h>
47 #include <linux/cpu.h>
48 #include <linux/mutex.h>
49 #include <linux/time.h>
50 #include <linux/kernel_stat.h>
51 #include <linux/wait.h>
52 #include <linux/kthread.h>
53 #include <linux/prefetch.h>
54 #include <linux/delay.h>
55 #include <linux/stop_machine.h>
56 #include <linux/random.h>
57 #include <linux/ftrace_event.h>
58 #include <linux/suspend.h>
59 #include <linux/delay.h>
60 #include <linux/gfp.h>
61 #include <linux/oom.h>
62 #include <linux/smpboot.h>
63 #include "../time/tick-internal.h"
64
65 #include "tree.h"
66 #include "rcu.h"
67
68 MODULE_ALIAS("rcutree");
69 #ifdef MODULE_PARAM_PREFIX
70 #undef MODULE_PARAM_PREFIX
71 #endif
72 #define MODULE_PARAM_PREFIX "rcutree."
73
74 /* Data structures. */
75
76 static struct lock_class_key rcu_node_class[RCU_NUM_LVLS];
77 static struct lock_class_key rcu_fqs_class[RCU_NUM_LVLS];
78
79 /*
80  * In order to export the rcu_state name to the tracing tools, it
81  * needs to be added in the __tracepoint_string section.
82  * This requires defining a separate variable tp_<sname>_varname
83  * that points to the string being used, and this will allow
84  * the tracing userspace tools to be able to decipher the string
85  * address to the matching string.
86  */
87 #ifdef CONFIG_TRACING
88 # define DEFINE_RCU_TPS(sname) \
89 static char sname##_varname[] = #sname; \
90 static const char *tp_##sname##_varname __used __tracepoint_string = sname##_varname;
91 # define RCU_STATE_NAME(sname) sname##_varname
92 #else
93 # define DEFINE_RCU_TPS(sname)
94 # define RCU_STATE_NAME(sname) __stringify(sname)
95 #endif
96
97 #define RCU_STATE_INITIALIZER(sname, sabbr, cr) \
98 DEFINE_RCU_TPS(sname) \
99 DEFINE_PER_CPU_SHARED_ALIGNED(struct rcu_data, sname##_data); \
100 struct rcu_state sname##_state = { \
101         .level = { &sname##_state.node[0] }, \
102         .rda = &sname##_data, \
103         .call = cr, \
104         .fqs_state = RCU_GP_IDLE, \
105         .gpnum = 0UL - 300UL, \
106         .completed = 0UL - 300UL, \
107         .orphan_lock = __RAW_SPIN_LOCK_UNLOCKED(&sname##_state.orphan_lock), \
108         .orphan_nxttail = &sname##_state.orphan_nxtlist, \
109         .orphan_donetail = &sname##_state.orphan_donelist, \
110         .barrier_mutex = __MUTEX_INITIALIZER(sname##_state.barrier_mutex), \
111         .name = RCU_STATE_NAME(sname), \
112         .abbr = sabbr, \
113 }
114
115 RCU_STATE_INITIALIZER(rcu_sched, 's', call_rcu_sched);
116 RCU_STATE_INITIALIZER(rcu_bh, 'b', call_rcu_bh);
117
118 static struct rcu_state *rcu_state_p;
119 LIST_HEAD(rcu_struct_flavors);
120
121 /* Increase (but not decrease) the CONFIG_RCU_FANOUT_LEAF at boot time. */
122 static int rcu_fanout_leaf = CONFIG_RCU_FANOUT_LEAF;
123 module_param(rcu_fanout_leaf, int, 0444);
124 int rcu_num_lvls __read_mostly = RCU_NUM_LVLS;
125 static int num_rcu_lvl[] = {  /* Number of rcu_nodes at specified level. */
126         NUM_RCU_LVL_0,
127         NUM_RCU_LVL_1,
128         NUM_RCU_LVL_2,
129         NUM_RCU_LVL_3,
130         NUM_RCU_LVL_4,
131 };
132 int rcu_num_nodes __read_mostly = NUM_RCU_NODES; /* Total # rcu_nodes in use. */
133
134 /*
135  * The rcu_scheduler_active variable transitions from zero to one just
136  * before the first task is spawned.  So when this variable is zero, RCU
137  * can assume that there is but one task, allowing RCU to (for example)
138  * optimize synchronize_sched() to a simple barrier().  When this variable
139  * is one, RCU must actually do all the hard work required to detect real
140  * grace periods.  This variable is also used to suppress boot-time false
141  * positives from lockdep-RCU error checking.
142  */
143 int rcu_scheduler_active __read_mostly;
144 EXPORT_SYMBOL_GPL(rcu_scheduler_active);
145
146 /*
147  * The rcu_scheduler_fully_active variable transitions from zero to one
148  * during the early_initcall() processing, which is after the scheduler
149  * is capable of creating new tasks.  So RCU processing (for example,
150  * creating tasks for RCU priority boosting) must be delayed until after
151  * rcu_scheduler_fully_active transitions from zero to one.  We also
152  * currently delay invocation of any RCU callbacks until after this point.
153  *
154  * It might later prove better for people registering RCU callbacks during
155  * early boot to take responsibility for these callbacks, but one step at
156  * a time.
157  */
158 static int rcu_scheduler_fully_active __read_mostly;
159
160 static void rcu_init_new_rnp(struct rcu_node *rnp_leaf);
161 static void rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf);
162 static void rcu_boost_kthread_setaffinity(struct rcu_node *rnp, int outgoingcpu);
163 static void invoke_rcu_core(void);
164 static void invoke_rcu_callbacks(struct rcu_state *rsp, struct rcu_data *rdp);
165
166 /* rcuc/rcub kthread realtime priority */
167 static int kthread_prio = CONFIG_RCU_KTHREAD_PRIO;
168 module_param(kthread_prio, int, 0644);
169
170 /* Delay in jiffies for grace-period initialization delays, debug only. */
171 #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_INIT
172 static int gp_init_delay = CONFIG_RCU_TORTURE_TEST_SLOW_INIT_DELAY;
173 module_param(gp_init_delay, int, 0644);
174 #else /* #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_INIT */
175 static const int gp_init_delay;
176 #endif /* #else #ifdef CONFIG_RCU_TORTURE_TEST_SLOW_INIT */
177 #define PER_RCU_NODE_PERIOD 10  /* Number of grace periods between delays. */
178
179 /*
180  * Track the rcutorture test sequence number and the update version
181  * number within a given test.  The rcutorture_testseq is incremented
182  * on every rcutorture module load and unload, so has an odd value
183  * when a test is running.  The rcutorture_vernum is set to zero
184  * when rcutorture starts and is incremented on each rcutorture update.
185  * These variables enable correlating rcutorture output with the
186  * RCU tracing information.
187  */
188 unsigned long rcutorture_testseq;
189 unsigned long rcutorture_vernum;
190
191 /*
192  * Compute the mask of online CPUs for the specified rcu_node structure.
193  * This will not be stable unless the rcu_node structure's ->lock is
194  * held, but the bit corresponding to the current CPU will be stable
195  * in most contexts.
196  */
197 unsigned long rcu_rnp_online_cpus(struct rcu_node *rnp)
198 {
199         return ACCESS_ONCE(rnp->qsmaskinitnext);
200 }
201
202 /*
203  * Return true if an RCU grace period is in progress.  The ACCESS_ONCE()s
204  * permit this function to be invoked without holding the root rcu_node
205  * structure's ->lock, but of course results can be subject to change.
206  */
207 static int rcu_gp_in_progress(struct rcu_state *rsp)
208 {
209         return ACCESS_ONCE(rsp->completed) != ACCESS_ONCE(rsp->gpnum);
210 }
211
212 /*
213  * Note a quiescent state.  Because we do not need to know
214  * how many quiescent states passed, just if there was at least
215  * one since the start of the grace period, this just sets a flag.
216  * The caller must have disabled preemption.
217  */
218 void rcu_sched_qs(void)
219 {
220         if (!__this_cpu_read(rcu_sched_data.passed_quiesce)) {
221                 trace_rcu_grace_period(TPS("rcu_sched"),
222                                        __this_cpu_read(rcu_sched_data.gpnum),
223                                        TPS("cpuqs"));
224                 __this_cpu_write(rcu_sched_data.passed_quiesce, 1);
225         }
226 }
227
228 #ifdef CONFIG_PREEMPT_RT_FULL
229 static void rcu_preempt_qs(void);
230
231 void rcu_bh_qs(void)
232 {
233         unsigned long flags;
234
235         /* Callers to this function, rcu_preempt_qs(), must disable irqs. */
236         local_irq_save(flags);
237         rcu_preempt_qs();
238         local_irq_restore(flags);
239 }
240 #else
241 void rcu_bh_qs(void)
242 {
243         if (!__this_cpu_read(rcu_bh_data.passed_quiesce)) {
244                 trace_rcu_grace_period(TPS("rcu_bh"),
245                                        __this_cpu_read(rcu_bh_data.gpnum),
246                                        TPS("cpuqs"));
247                 __this_cpu_write(rcu_bh_data.passed_quiesce, 1);
248         }
249 }
250 #endif
251
252 static DEFINE_PER_CPU(int, rcu_sched_qs_mask);
253
254 static DEFINE_PER_CPU(struct rcu_dynticks, rcu_dynticks) = {
255         .dynticks_nesting = DYNTICK_TASK_EXIT_IDLE,
256         .dynticks = ATOMIC_INIT(1),
257 #ifdef CONFIG_NO_HZ_FULL_SYSIDLE
258         .dynticks_idle_nesting = DYNTICK_TASK_NEST_VALUE,
259         .dynticks_idle = ATOMIC_INIT(1),
260 #endif /* #ifdef CONFIG_NO_HZ_FULL_SYSIDLE */
261 };
262
263 DEFINE_PER_CPU_SHARED_ALIGNED(unsigned long, rcu_qs_ctr);
264 EXPORT_PER_CPU_SYMBOL_GPL(rcu_qs_ctr);
265
266 /*
267  * Let the RCU core know that this CPU has gone through the scheduler,
268  * which is a quiescent state.  This is called when the need for a
269  * quiescent state is urgent, so we burn an atomic operation and full
270  * memory barriers to let the RCU core know about it, regardless of what
271  * this CPU might (or might not) do in the near future.
272  *
273  * We inform the RCU core by emulating a zero-duration dyntick-idle
274  * period, which we in turn do by incrementing the ->dynticks counter
275  * by two.
276  */
277 static void rcu_momentary_dyntick_idle(void)
278 {
279         unsigned long flags;
280         struct rcu_data *rdp;
281         struct rcu_dynticks *rdtp;
282         int resched_mask;
283         struct rcu_state *rsp;
284
285         local_irq_save(flags);
286
287         /*
288          * Yes, we can lose flag-setting operations.  This is OK, because
289          * the flag will be set again after some delay.
290          */
291         resched_mask = raw_cpu_read(rcu_sched_qs_mask);
292         raw_cpu_write(rcu_sched_qs_mask, 0);
293
294         /* Find the flavor that needs a quiescent state. */
295         for_each_rcu_flavor(rsp) {
296                 rdp = raw_cpu_ptr(rsp->rda);
297                 if (!(resched_mask & rsp->flavor_mask))
298                         continue;
299                 smp_mb(); /* rcu_sched_qs_mask before cond_resched_completed. */
300                 if (ACCESS_ONCE(rdp->mynode->completed) !=
301                     ACCESS_ONCE(rdp->cond_resched_completed))
302                         continue;
303
304                 /*
305                  * Pretend to be momentarily idle for the quiescent state.
306                  * This allows the grace-period kthread to record the
307                  * quiescent state, with no need for this CPU to do anything
308                  * further.
309                  */
310                 rdtp = this_cpu_ptr(&rcu_dynticks);
311                 smp_mb__before_atomic(); /* Earlier stuff before QS. */
312                 atomic_add(2, &rdtp->dynticks);  /* QS. */
313                 smp_mb__after_atomic(); /* Later stuff after QS. */
314                 break;
315         }
316         local_irq_restore(flags);
317 }
318
319 /*
320  * Note a context switch.  This is a quiescent state for RCU-sched,
321  * and requires special handling for preemptible RCU.
322  * The caller must have disabled preemption.
323  */
324 void rcu_note_context_switch(void)
325 {
326         trace_rcu_utilization(TPS("Start context switch"));
327         rcu_sched_qs();
328         rcu_preempt_note_context_switch();
329         if (unlikely(raw_cpu_read(rcu_sched_qs_mask)))
330                 rcu_momentary_dyntick_idle();
331         trace_rcu_utilization(TPS("End context switch"));
332 }
333 EXPORT_SYMBOL_GPL(rcu_note_context_switch);
334
335 /*
336  * Register a quiescent state for all RCU flavors.  If there is an
337  * emergency, invoke rcu_momentary_dyntick_idle() to do a heavy-weight
338  * dyntick-idle quiescent state visible to other CPUs (but only for those
339  * RCU flavors in desperate need of a quiescent state, which will normally
340  * be none of them).  Either way, do a lightweight quiescent state for
341  * all RCU flavors.
342  */
343 void rcu_all_qs(void)
344 {
345         if (unlikely(raw_cpu_read(rcu_sched_qs_mask)))
346                 rcu_momentary_dyntick_idle();
347         this_cpu_inc(rcu_qs_ctr);
348 }
349 EXPORT_SYMBOL_GPL(rcu_all_qs);
350
351 static long blimit = 10;        /* Maximum callbacks per rcu_do_batch. */
352 static long qhimark = 10000;    /* If this many pending, ignore blimit. */
353 static long qlowmark = 100;     /* Once only this many pending, use blimit. */
354
355 module_param(blimit, long, 0444);
356 module_param(qhimark, long, 0444);
357 module_param(qlowmark, long, 0444);
358
359 static ulong jiffies_till_first_fqs = ULONG_MAX;
360 static ulong jiffies_till_next_fqs = ULONG_MAX;
361
362 module_param(jiffies_till_first_fqs, ulong, 0644);
363 module_param(jiffies_till_next_fqs, ulong, 0644);
364
365 /*
366  * How long the grace period must be before we start recruiting
367  * quiescent-state help from rcu_note_context_switch().
368  */
369 static ulong jiffies_till_sched_qs = HZ / 20;
370 module_param(jiffies_till_sched_qs, ulong, 0644);
371
372 static bool rcu_start_gp_advanced(struct rcu_state *rsp, struct rcu_node *rnp,
373                                   struct rcu_data *rdp);
374 static void force_qs_rnp(struct rcu_state *rsp,
375                          int (*f)(struct rcu_data *rsp, bool *isidle,
376                                   unsigned long *maxj),
377                          bool *isidle, unsigned long *maxj);
378 static void force_quiescent_state(struct rcu_state *rsp);
379 static int rcu_pending(void);
380
381 /*
382  * Return the number of RCU batches started thus far for debug & stats.
383  */
384 unsigned long rcu_batches_started(void)
385 {
386         return rcu_state_p->gpnum;
387 }
388 EXPORT_SYMBOL_GPL(rcu_batches_started);
389
390 /*
391  * Return the number of RCU-sched batches started thus far for debug & stats.
392  */
393 unsigned long rcu_batches_started_sched(void)
394 {
395         return rcu_sched_state.gpnum;
396 }
397 EXPORT_SYMBOL_GPL(rcu_batches_started_sched);
398
399 /*
400  * Return the number of RCU BH batches started thus far for debug & stats.
401  */
402 unsigned long rcu_batches_started_bh(void)
403 {
404         return rcu_bh_state.gpnum;
405 }
406 EXPORT_SYMBOL_GPL(rcu_batches_started_bh);
407
408 /*
409  * Return the number of RCU batches completed thus far for debug & stats.
410  */
411 unsigned long rcu_batches_completed(void)
412 {
413         return rcu_state_p->completed;
414 }
415 EXPORT_SYMBOL_GPL(rcu_batches_completed);
416
417 /*
418  * Return the number of RCU-sched batches completed thus far for debug & stats.
419  */
420 unsigned long rcu_batches_completed_sched(void)
421 {
422         return rcu_sched_state.completed;
423 }
424 EXPORT_SYMBOL_GPL(rcu_batches_completed_sched);
425
426 #ifndef CONFIG_PREEMPT_RT_FULL
427 /*
428  * Return the number of RCU BH batches completed thus far for debug & stats.
429  */
430 unsigned long rcu_batches_completed_bh(void)
431 {
432         return rcu_bh_state.completed;
433 }
434 EXPORT_SYMBOL_GPL(rcu_batches_completed_bh);
435
436 /*
437  * Force a quiescent state.
438  */
439 void rcu_force_quiescent_state(void)
440 {
441         force_quiescent_state(rcu_state_p);
442 }
443 EXPORT_SYMBOL_GPL(rcu_force_quiescent_state);
444
445 /*
446  * Force a quiescent state for RCU BH.
447  */
448 void rcu_bh_force_quiescent_state(void)
449 {
450         force_quiescent_state(&rcu_bh_state);
451 }
452 EXPORT_SYMBOL_GPL(rcu_bh_force_quiescent_state);
453
454 #else
455 void rcu_force_quiescent_state(void)
456 {
457 }
458 EXPORT_SYMBOL_GPL(rcu_force_quiescent_state);
459 #endif
460
461 /*
462  * Force a quiescent state for RCU-sched.
463  */
464 void rcu_sched_force_quiescent_state(void)
465 {
466         force_quiescent_state(&rcu_sched_state);
467 }
468 EXPORT_SYMBOL_GPL(rcu_sched_force_quiescent_state);
469
470 /*
471  * Show the state of the grace-period kthreads.
472  */
473 void show_rcu_gp_kthreads(void)
474 {
475         struct rcu_state *rsp;
476
477         for_each_rcu_flavor(rsp) {
478                 pr_info("%s: wait state: %d ->state: %#lx\n",
479                         rsp->name, rsp->gp_state, rsp->gp_kthread->state);
480                 /* sched_show_task(rsp->gp_kthread); */
481         }
482 }
483 EXPORT_SYMBOL_GPL(show_rcu_gp_kthreads);
484
485 /*
486  * Record the number of times rcutorture tests have been initiated and
487  * terminated.  This information allows the debugfs tracing stats to be
488  * correlated to the rcutorture messages, even when the rcutorture module
489  * is being repeatedly loaded and unloaded.  In other words, we cannot
490  * store this state in rcutorture itself.
491  */
492 void rcutorture_record_test_transition(void)
493 {
494         rcutorture_testseq++;
495         rcutorture_vernum = 0;
496 }
497 EXPORT_SYMBOL_GPL(rcutorture_record_test_transition);
498
499 /*
500  * Send along grace-period-related data for rcutorture diagnostics.
501  */
502 void rcutorture_get_gp_data(enum rcutorture_type test_type, int *flags,
503                             unsigned long *gpnum, unsigned long *completed)
504 {
505         struct rcu_state *rsp = NULL;
506
507         switch (test_type) {
508         case RCU_FLAVOR:
509                 rsp = rcu_state_p;
510                 break;
511         case RCU_BH_FLAVOR:
512                 rsp = &rcu_bh_state;
513                 break;
514         case RCU_SCHED_FLAVOR:
515                 rsp = &rcu_sched_state;
516                 break;
517         default:
518                 break;
519         }
520         if (rsp != NULL) {
521                 *flags = ACCESS_ONCE(rsp->gp_flags);
522                 *gpnum = ACCESS_ONCE(rsp->gpnum);
523                 *completed = ACCESS_ONCE(rsp->completed);
524                 return;
525         }
526         *flags = 0;
527         *gpnum = 0;
528         *completed = 0;
529 }
530 EXPORT_SYMBOL_GPL(rcutorture_get_gp_data);
531
532 /*
533  * Record the number of writer passes through the current rcutorture test.
534  * This is also used to correlate debugfs tracing stats with the rcutorture
535  * messages.
536  */
537 void rcutorture_record_progress(unsigned long vernum)
538 {
539         rcutorture_vernum++;
540 }
541 EXPORT_SYMBOL_GPL(rcutorture_record_progress);
542
543 /*
544  * Does the CPU have callbacks ready to be invoked?
545  */
546 static int
547 cpu_has_callbacks_ready_to_invoke(struct rcu_data *rdp)
548 {
549         return &rdp->nxtlist != rdp->nxttail[RCU_DONE_TAIL] &&
550                rdp->nxttail[RCU_DONE_TAIL] != NULL;
551 }
552
553 /*
554  * Return the root node of the specified rcu_state structure.
555  */
556 static struct rcu_node *rcu_get_root(struct rcu_state *rsp)
557 {
558         return &rsp->node[0];
559 }
560
561 /*
562  * Is there any need for future grace periods?
563  * Interrupts must be disabled.  If the caller does not hold the root
564  * rnp_node structure's ->lock, the results are advisory only.
565  */
566 static int rcu_future_needs_gp(struct rcu_state *rsp)
567 {
568         struct rcu_node *rnp = rcu_get_root(rsp);
569         int idx = (ACCESS_ONCE(rnp->completed) + 1) & 0x1;
570         int *fp = &rnp->need_future_gp[idx];
571
572         return ACCESS_ONCE(*fp);
573 }
574
575 /*
576  * Does the current CPU require a not-yet-started grace period?
577  * The caller must have disabled interrupts to prevent races with
578  * normal callback registry.
579  */
580 static int
581 cpu_needs_another_gp(struct rcu_state *rsp, struct rcu_data *rdp)
582 {
583         int i;
584
585         if (rcu_gp_in_progress(rsp))
586                 return 0;  /* No, a grace period is already in progress. */
587         if (rcu_future_needs_gp(rsp))
588                 return 1;  /* Yes, a no-CBs CPU needs one. */
589         if (!rdp->nxttail[RCU_NEXT_TAIL])
590                 return 0;  /* No, this is a no-CBs (or offline) CPU. */
591         if (*rdp->nxttail[RCU_NEXT_READY_TAIL])
592                 return 1;  /* Yes, this CPU has newly registered callbacks. */
593         for (i = RCU_WAIT_TAIL; i < RCU_NEXT_TAIL; i++)
594                 if (rdp->nxttail[i - 1] != rdp->nxttail[i] &&
595                     ULONG_CMP_LT(ACCESS_ONCE(rsp->completed),
596                                  rdp->nxtcompleted[i]))
597                         return 1;  /* Yes, CBs for future grace period. */
598         return 0; /* No grace period needed. */
599 }
600
601 /*
602  * rcu_eqs_enter_common - current CPU is moving towards extended quiescent state
603  *
604  * If the new value of the ->dynticks_nesting counter now is zero,
605  * we really have entered idle, and must do the appropriate accounting.
606  * The caller must have disabled interrupts.
607  */
608 static void rcu_eqs_enter_common(long long oldval, bool user)
609 {
610         struct rcu_state *rsp;
611         struct rcu_data *rdp;
612         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
613
614         trace_rcu_dyntick(TPS("Start"), oldval, rdtp->dynticks_nesting);
615         if (!user && !is_idle_task(current)) {
616                 struct task_struct *idle __maybe_unused =
617                         idle_task(smp_processor_id());
618
619                 trace_rcu_dyntick(TPS("Error on entry: not idle task"), oldval, 0);
620                 ftrace_dump(DUMP_ORIG);
621                 WARN_ONCE(1, "Current pid: %d comm: %s / Idle pid: %d comm: %s",
622                           current->pid, current->comm,
623                           idle->pid, idle->comm); /* must be idle task! */
624         }
625         for_each_rcu_flavor(rsp) {
626                 rdp = this_cpu_ptr(rsp->rda);
627                 do_nocb_deferred_wakeup(rdp);
628         }
629         rcu_prepare_for_idle();
630         /* CPUs seeing atomic_inc() must see prior RCU read-side crit sects */
631         smp_mb__before_atomic();  /* See above. */
632         atomic_inc(&rdtp->dynticks);
633         smp_mb__after_atomic();  /* Force ordering with next sojourn. */
634         WARN_ON_ONCE(atomic_read(&rdtp->dynticks) & 0x1);
635         rcu_dynticks_task_enter();
636
637         /*
638          * It is illegal to enter an extended quiescent state while
639          * in an RCU read-side critical section.
640          */
641         rcu_lockdep_assert(!lock_is_held(&rcu_lock_map),
642                            "Illegal idle entry in RCU read-side critical section.");
643         rcu_lockdep_assert(!lock_is_held(&rcu_bh_lock_map),
644                            "Illegal idle entry in RCU-bh read-side critical section.");
645         rcu_lockdep_assert(!lock_is_held(&rcu_sched_lock_map),
646                            "Illegal idle entry in RCU-sched read-side critical section.");
647 }
648
649 /*
650  * Enter an RCU extended quiescent state, which can be either the
651  * idle loop or adaptive-tickless usermode execution.
652  */
653 static void rcu_eqs_enter(bool user)
654 {
655         long long oldval;
656         struct rcu_dynticks *rdtp;
657
658         rdtp = this_cpu_ptr(&rcu_dynticks);
659         oldval = rdtp->dynticks_nesting;
660         WARN_ON_ONCE((oldval & DYNTICK_TASK_NEST_MASK) == 0);
661         if ((oldval & DYNTICK_TASK_NEST_MASK) == DYNTICK_TASK_NEST_VALUE) {
662                 rdtp->dynticks_nesting = 0;
663                 rcu_eqs_enter_common(oldval, user);
664         } else {
665                 rdtp->dynticks_nesting -= DYNTICK_TASK_NEST_VALUE;
666         }
667 }
668
669 /**
670  * rcu_idle_enter - inform RCU that current CPU is entering idle
671  *
672  * Enter idle mode, in other words, -leave- the mode in which RCU
673  * read-side critical sections can occur.  (Though RCU read-side
674  * critical sections can occur in irq handlers in idle, a possibility
675  * handled by irq_enter() and irq_exit().)
676  *
677  * We crowbar the ->dynticks_nesting field to zero to allow for
678  * the possibility of usermode upcalls having messed up our count
679  * of interrupt nesting level during the prior busy period.
680  */
681 void rcu_idle_enter(void)
682 {
683         unsigned long flags;
684
685         local_irq_save(flags);
686         rcu_eqs_enter(false);
687         rcu_sysidle_enter(0);
688         local_irq_restore(flags);
689 }
690 EXPORT_SYMBOL_GPL(rcu_idle_enter);
691
692 #ifdef CONFIG_RCU_USER_QS
693 /**
694  * rcu_user_enter - inform RCU that we are resuming userspace.
695  *
696  * Enter RCU idle mode right before resuming userspace.  No use of RCU
697  * is permitted between this call and rcu_user_exit(). This way the
698  * CPU doesn't need to maintain the tick for RCU maintenance purposes
699  * when the CPU runs in userspace.
700  */
701 void rcu_user_enter(void)
702 {
703         rcu_eqs_enter(1);
704 }
705 #endif /* CONFIG_RCU_USER_QS */
706
707 /**
708  * rcu_irq_exit - inform RCU that current CPU is exiting irq towards idle
709  *
710  * Exit from an interrupt handler, which might possibly result in entering
711  * idle mode, in other words, leaving the mode in which read-side critical
712  * sections can occur.
713  *
714  * This code assumes that the idle loop never does anything that might
715  * result in unbalanced calls to irq_enter() and irq_exit().  If your
716  * architecture violates this assumption, RCU will give you what you
717  * deserve, good and hard.  But very infrequently and irreproducibly.
718  *
719  * Use things like work queues to work around this limitation.
720  *
721  * You have been warned.
722  */
723 void rcu_irq_exit(void)
724 {
725         unsigned long flags;
726         long long oldval;
727         struct rcu_dynticks *rdtp;
728
729         local_irq_save(flags);
730         rdtp = this_cpu_ptr(&rcu_dynticks);
731         oldval = rdtp->dynticks_nesting;
732         rdtp->dynticks_nesting--;
733         WARN_ON_ONCE(rdtp->dynticks_nesting < 0);
734         if (rdtp->dynticks_nesting)
735                 trace_rcu_dyntick(TPS("--="), oldval, rdtp->dynticks_nesting);
736         else
737                 rcu_eqs_enter_common(oldval, true);
738         rcu_sysidle_enter(1);
739         local_irq_restore(flags);
740 }
741
742 /*
743  * rcu_eqs_exit_common - current CPU moving away from extended quiescent state
744  *
745  * If the new value of the ->dynticks_nesting counter was previously zero,
746  * we really have exited idle, and must do the appropriate accounting.
747  * The caller must have disabled interrupts.
748  */
749 static void rcu_eqs_exit_common(long long oldval, int user)
750 {
751         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
752
753         rcu_dynticks_task_exit();
754         smp_mb__before_atomic();  /* Force ordering w/previous sojourn. */
755         atomic_inc(&rdtp->dynticks);
756         /* CPUs seeing atomic_inc() must see later RCU read-side crit sects */
757         smp_mb__after_atomic();  /* See above. */
758         WARN_ON_ONCE(!(atomic_read(&rdtp->dynticks) & 0x1));
759         rcu_cleanup_after_idle();
760         trace_rcu_dyntick(TPS("End"), oldval, rdtp->dynticks_nesting);
761         if (!user && !is_idle_task(current)) {
762                 struct task_struct *idle __maybe_unused =
763                         idle_task(smp_processor_id());
764
765                 trace_rcu_dyntick(TPS("Error on exit: not idle task"),
766                                   oldval, rdtp->dynticks_nesting);
767                 ftrace_dump(DUMP_ORIG);
768                 WARN_ONCE(1, "Current pid: %d comm: %s / Idle pid: %d comm: %s",
769                           current->pid, current->comm,
770                           idle->pid, idle->comm); /* must be idle task! */
771         }
772 }
773
774 /*
775  * Exit an RCU extended quiescent state, which can be either the
776  * idle loop or adaptive-tickless usermode execution.
777  */
778 static void rcu_eqs_exit(bool user)
779 {
780         struct rcu_dynticks *rdtp;
781         long long oldval;
782
783         rdtp = this_cpu_ptr(&rcu_dynticks);
784         oldval = rdtp->dynticks_nesting;
785         WARN_ON_ONCE(oldval < 0);
786         if (oldval & DYNTICK_TASK_NEST_MASK) {
787                 rdtp->dynticks_nesting += DYNTICK_TASK_NEST_VALUE;
788         } else {
789                 rdtp->dynticks_nesting = DYNTICK_TASK_EXIT_IDLE;
790                 rcu_eqs_exit_common(oldval, user);
791         }
792 }
793
794 /**
795  * rcu_idle_exit - inform RCU that current CPU is leaving idle
796  *
797  * Exit idle mode, in other words, -enter- the mode in which RCU
798  * read-side critical sections can occur.
799  *
800  * We crowbar the ->dynticks_nesting field to DYNTICK_TASK_NEST to
801  * allow for the possibility of usermode upcalls messing up our count
802  * of interrupt nesting level during the busy period that is just
803  * now starting.
804  */
805 void rcu_idle_exit(void)
806 {
807         unsigned long flags;
808
809         local_irq_save(flags);
810         rcu_eqs_exit(false);
811         rcu_sysidle_exit(0);
812         local_irq_restore(flags);
813 }
814 EXPORT_SYMBOL_GPL(rcu_idle_exit);
815
816 #ifdef CONFIG_RCU_USER_QS
817 /**
818  * rcu_user_exit - inform RCU that we are exiting userspace.
819  *
820  * Exit RCU idle mode while entering the kernel because it can
821  * run a RCU read side critical section anytime.
822  */
823 void rcu_user_exit(void)
824 {
825         rcu_eqs_exit(1);
826 }
827 #endif /* CONFIG_RCU_USER_QS */
828
829 /**
830  * rcu_irq_enter - inform RCU that current CPU is entering irq away from idle
831  *
832  * Enter an interrupt handler, which might possibly result in exiting
833  * idle mode, in other words, entering the mode in which read-side critical
834  * sections can occur.
835  *
836  * Note that the Linux kernel is fully capable of entering an interrupt
837  * handler that it never exits, for example when doing upcalls to
838  * user mode!  This code assumes that the idle loop never does upcalls to
839  * user mode.  If your architecture does do upcalls from the idle loop (or
840  * does anything else that results in unbalanced calls to the irq_enter()
841  * and irq_exit() functions), RCU will give you what you deserve, good
842  * and hard.  But very infrequently and irreproducibly.
843  *
844  * Use things like work queues to work around this limitation.
845  *
846  * You have been warned.
847  */
848 void rcu_irq_enter(void)
849 {
850         unsigned long flags;
851         struct rcu_dynticks *rdtp;
852         long long oldval;
853
854         local_irq_save(flags);
855         rdtp = this_cpu_ptr(&rcu_dynticks);
856         oldval = rdtp->dynticks_nesting;
857         rdtp->dynticks_nesting++;
858         WARN_ON_ONCE(rdtp->dynticks_nesting == 0);
859         if (oldval)
860                 trace_rcu_dyntick(TPS("++="), oldval, rdtp->dynticks_nesting);
861         else
862                 rcu_eqs_exit_common(oldval, true);
863         rcu_sysidle_exit(1);
864         local_irq_restore(flags);
865 }
866
867 /**
868  * rcu_nmi_enter - inform RCU of entry to NMI context
869  *
870  * If the CPU was idle from RCU's viewpoint, update rdtp->dynticks and
871  * rdtp->dynticks_nmi_nesting to let the RCU grace-period handling know
872  * that the CPU is active.  This implementation permits nested NMIs, as
873  * long as the nesting level does not overflow an int.  (You will probably
874  * run out of stack space first.)
875  */
876 void rcu_nmi_enter(void)
877 {
878         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
879         int incby = 2;
880
881         /* Complain about underflow. */
882         WARN_ON_ONCE(rdtp->dynticks_nmi_nesting < 0);
883
884         /*
885          * If idle from RCU viewpoint, atomically increment ->dynticks
886          * to mark non-idle and increment ->dynticks_nmi_nesting by one.
887          * Otherwise, increment ->dynticks_nmi_nesting by two.  This means
888          * if ->dynticks_nmi_nesting is equal to one, we are guaranteed
889          * to be in the outermost NMI handler that interrupted an RCU-idle
890          * period (observation due to Andy Lutomirski).
891          */
892         if (!(atomic_read(&rdtp->dynticks) & 0x1)) {
893                 smp_mb__before_atomic();  /* Force delay from prior write. */
894                 atomic_inc(&rdtp->dynticks);
895                 /* atomic_inc() before later RCU read-side crit sects */
896                 smp_mb__after_atomic();  /* See above. */
897                 WARN_ON_ONCE(!(atomic_read(&rdtp->dynticks) & 0x1));
898                 incby = 1;
899         }
900         rdtp->dynticks_nmi_nesting += incby;
901         barrier();
902 }
903
904 /**
905  * rcu_nmi_exit - inform RCU of exit from NMI context
906  *
907  * If we are returning from the outermost NMI handler that interrupted an
908  * RCU-idle period, update rdtp->dynticks and rdtp->dynticks_nmi_nesting
909  * to let the RCU grace-period handling know that the CPU is back to
910  * being RCU-idle.
911  */
912 void rcu_nmi_exit(void)
913 {
914         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
915
916         /*
917          * Check for ->dynticks_nmi_nesting underflow and bad ->dynticks.
918          * (We are exiting an NMI handler, so RCU better be paying attention
919          * to us!)
920          */
921         WARN_ON_ONCE(rdtp->dynticks_nmi_nesting <= 0);
922         WARN_ON_ONCE(!(atomic_read(&rdtp->dynticks) & 0x1));
923
924         /*
925          * If the nesting level is not 1, the CPU wasn't RCU-idle, so
926          * leave it in non-RCU-idle state.
927          */
928         if (rdtp->dynticks_nmi_nesting != 1) {
929                 rdtp->dynticks_nmi_nesting -= 2;
930                 return;
931         }
932
933         /* This NMI interrupted an RCU-idle CPU, restore RCU-idleness. */
934         rdtp->dynticks_nmi_nesting = 0;
935         /* CPUs seeing atomic_inc() must see prior RCU read-side crit sects */
936         smp_mb__before_atomic();  /* See above. */
937         atomic_inc(&rdtp->dynticks);
938         smp_mb__after_atomic();  /* Force delay to next write. */
939         WARN_ON_ONCE(atomic_read(&rdtp->dynticks) & 0x1);
940 }
941
942 /**
943  * __rcu_is_watching - are RCU read-side critical sections safe?
944  *
945  * Return true if RCU is watching the running CPU, which means that
946  * this CPU can safely enter RCU read-side critical sections.  Unlike
947  * rcu_is_watching(), the caller of __rcu_is_watching() must have at
948  * least disabled preemption.
949  */
950 bool notrace __rcu_is_watching(void)
951 {
952         return atomic_read(this_cpu_ptr(&rcu_dynticks.dynticks)) & 0x1;
953 }
954
955 /**
956  * rcu_is_watching - see if RCU thinks that the current CPU is idle
957  *
958  * If the current CPU is in its idle loop and is neither in an interrupt
959  * or NMI handler, return true.
960  */
961 bool notrace rcu_is_watching(void)
962 {
963         bool ret;
964
965         preempt_disable();
966         ret = __rcu_is_watching();
967         preempt_enable();
968         return ret;
969 }
970 EXPORT_SYMBOL_GPL(rcu_is_watching);
971
972 #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU)
973
974 /*
975  * Is the current CPU online?  Disable preemption to avoid false positives
976  * that could otherwise happen due to the current CPU number being sampled,
977  * this task being preempted, its old CPU being taken offline, resuming
978  * on some other CPU, then determining that its old CPU is now offline.
979  * It is OK to use RCU on an offline processor during initial boot, hence
980  * the check for rcu_scheduler_fully_active.  Note also that it is OK
981  * for a CPU coming online to use RCU for one jiffy prior to marking itself
982  * online in the cpu_online_mask.  Similarly, it is OK for a CPU going
983  * offline to continue to use RCU for one jiffy after marking itself
984  * offline in the cpu_online_mask.  This leniency is necessary given the
985  * non-atomic nature of the online and offline processing, for example,
986  * the fact that a CPU enters the scheduler after completing the CPU_DYING
987  * notifiers.
988  *
989  * This is also why RCU internally marks CPUs online during the
990  * CPU_UP_PREPARE phase and offline during the CPU_DEAD phase.
991  *
992  * Disable checking if in an NMI handler because we cannot safely report
993  * errors from NMI handlers anyway.
994  */
995 bool rcu_lockdep_current_cpu_online(void)
996 {
997         struct rcu_data *rdp;
998         struct rcu_node *rnp;
999         bool ret;
1000
1001         if (in_nmi())
1002                 return true;
1003         preempt_disable();
1004         rdp = this_cpu_ptr(&rcu_sched_data);
1005         rnp = rdp->mynode;
1006         ret = (rdp->grpmask & rcu_rnp_online_cpus(rnp)) ||
1007               !rcu_scheduler_fully_active;
1008         preempt_enable();
1009         return ret;
1010 }
1011 EXPORT_SYMBOL_GPL(rcu_lockdep_current_cpu_online);
1012
1013 #endif /* #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU) */
1014
1015 /**
1016  * rcu_is_cpu_rrupt_from_idle - see if idle or immediately interrupted from idle
1017  *
1018  * If the current CPU is idle or running at a first-level (not nested)
1019  * interrupt from idle, return true.  The caller must have at least
1020  * disabled preemption.
1021  */
1022 static int rcu_is_cpu_rrupt_from_idle(void)
1023 {
1024         return __this_cpu_read(rcu_dynticks.dynticks_nesting) <= 1;
1025 }
1026
1027 /*
1028  * Snapshot the specified CPU's dynticks counter so that we can later
1029  * credit them with an implicit quiescent state.  Return 1 if this CPU
1030  * is in dynticks idle mode, which is an extended quiescent state.
1031  */
1032 static int dyntick_save_progress_counter(struct rcu_data *rdp,
1033                                          bool *isidle, unsigned long *maxj)
1034 {
1035         rdp->dynticks_snap = atomic_add_return(0, &rdp->dynticks->dynticks);
1036         rcu_sysidle_check_cpu(rdp, isidle, maxj);
1037         if ((rdp->dynticks_snap & 0x1) == 0) {
1038                 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, TPS("dti"));
1039                 return 1;
1040         } else {
1041                 if (ULONG_CMP_LT(ACCESS_ONCE(rdp->gpnum) + ULONG_MAX / 4,
1042                                  rdp->mynode->gpnum))
1043                         ACCESS_ONCE(rdp->gpwrap) = true;
1044                 return 0;
1045         }
1046 }
1047
1048 /*
1049  * Return true if the specified CPU has passed through a quiescent
1050  * state by virtue of being in or having passed through an dynticks
1051  * idle state since the last call to dyntick_save_progress_counter()
1052  * for this same CPU, or by virtue of having been offline.
1053  */
1054 static int rcu_implicit_dynticks_qs(struct rcu_data *rdp,
1055                                     bool *isidle, unsigned long *maxj)
1056 {
1057         unsigned int curr;
1058         int *rcrmp;
1059         unsigned int snap;
1060
1061         curr = (unsigned int)atomic_add_return(0, &rdp->dynticks->dynticks);
1062         snap = (unsigned int)rdp->dynticks_snap;
1063
1064         /*
1065          * If the CPU passed through or entered a dynticks idle phase with
1066          * no active irq/NMI handlers, then we can safely pretend that the CPU
1067          * already acknowledged the request to pass through a quiescent
1068          * state.  Either way, that CPU cannot possibly be in an RCU
1069          * read-side critical section that started before the beginning
1070          * of the current RCU grace period.
1071          */
1072         if ((curr & 0x1) == 0 || UINT_CMP_GE(curr, snap + 2)) {
1073                 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, TPS("dti"));
1074                 rdp->dynticks_fqs++;
1075                 return 1;
1076         }
1077
1078         /*
1079          * Check for the CPU being offline, but only if the grace period
1080          * is old enough.  We don't need to worry about the CPU changing
1081          * state: If we see it offline even once, it has been through a
1082          * quiescent state.
1083          *
1084          * The reason for insisting that the grace period be at least
1085          * one jiffy old is that CPUs that are not quite online and that
1086          * have just gone offline can still execute RCU read-side critical
1087          * sections.
1088          */
1089         if (ULONG_CMP_GE(rdp->rsp->gp_start + 2, jiffies))
1090                 return 0;  /* Grace period is not old enough. */
1091         barrier();
1092         if (cpu_is_offline(rdp->cpu)) {
1093                 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, TPS("ofl"));
1094                 rdp->offline_fqs++;
1095                 return 1;
1096         }
1097
1098         /*
1099          * A CPU running for an extended time within the kernel can
1100          * delay RCU grace periods.  When the CPU is in NO_HZ_FULL mode,
1101          * even context-switching back and forth between a pair of
1102          * in-kernel CPU-bound tasks cannot advance grace periods.
1103          * So if the grace period is old enough, make the CPU pay attention.
1104          * Note that the unsynchronized assignments to the per-CPU
1105          * rcu_sched_qs_mask variable are safe.  Yes, setting of
1106          * bits can be lost, but they will be set again on the next
1107          * force-quiescent-state pass.  So lost bit sets do not result
1108          * in incorrect behavior, merely in a grace period lasting
1109          * a few jiffies longer than it might otherwise.  Because
1110          * there are at most four threads involved, and because the
1111          * updates are only once every few jiffies, the probability of
1112          * lossage (and thus of slight grace-period extension) is
1113          * quite low.
1114          *
1115          * Note that if the jiffies_till_sched_qs boot/sysfs parameter
1116          * is set too high, we override with half of the RCU CPU stall
1117          * warning delay.
1118          */
1119         rcrmp = &per_cpu(rcu_sched_qs_mask, rdp->cpu);
1120         if (ULONG_CMP_GE(jiffies,
1121                          rdp->rsp->gp_start + jiffies_till_sched_qs) ||
1122             ULONG_CMP_GE(jiffies, rdp->rsp->jiffies_resched)) {
1123                 if (!(ACCESS_ONCE(*rcrmp) & rdp->rsp->flavor_mask)) {
1124                         ACCESS_ONCE(rdp->cond_resched_completed) =
1125                                 ACCESS_ONCE(rdp->mynode->completed);
1126                         smp_mb(); /* ->cond_resched_completed before *rcrmp. */
1127                         ACCESS_ONCE(*rcrmp) =
1128                                 ACCESS_ONCE(*rcrmp) + rdp->rsp->flavor_mask;
1129                         resched_cpu(rdp->cpu);  /* Force CPU into scheduler. */
1130                         rdp->rsp->jiffies_resched += 5; /* Enable beating. */
1131                 } else if (ULONG_CMP_GE(jiffies, rdp->rsp->jiffies_resched)) {
1132                         /* Time to beat on that CPU again! */
1133                         resched_cpu(rdp->cpu);  /* Force CPU into scheduler. */
1134                         rdp->rsp->jiffies_resched += 5; /* Re-enable beating. */
1135                 }
1136         }
1137
1138         return 0;
1139 }
1140
1141 static void record_gp_stall_check_time(struct rcu_state *rsp)
1142 {
1143         unsigned long j = jiffies;
1144         unsigned long j1;
1145
1146         rsp->gp_start = j;
1147         smp_wmb(); /* Record start time before stall time. */
1148         j1 = rcu_jiffies_till_stall_check();
1149         ACCESS_ONCE(rsp->jiffies_stall) = j + j1;
1150         rsp->jiffies_resched = j + j1 / 2;
1151         rsp->n_force_qs_gpstart = ACCESS_ONCE(rsp->n_force_qs);
1152 }
1153
1154 /*
1155  * Complain about starvation of grace-period kthread.
1156  */
1157 static void rcu_check_gp_kthread_starvation(struct rcu_state *rsp)
1158 {
1159         unsigned long gpa;
1160         unsigned long j;
1161
1162         j = jiffies;
1163         gpa = ACCESS_ONCE(rsp->gp_activity);
1164         if (j - gpa > 2 * HZ)
1165                 pr_err("%s kthread starved for %ld jiffies!\n",
1166                        rsp->name, j - gpa);
1167 }
1168
1169 /*
1170  * Dump stacks of all tasks running on stalled CPUs.
1171  */
1172 static void rcu_dump_cpu_stacks(struct rcu_state *rsp)
1173 {
1174         int cpu;
1175         unsigned long flags;
1176         struct rcu_node *rnp;
1177
1178         rcu_for_each_leaf_node(rsp, rnp) {
1179                 raw_spin_lock_irqsave(&rnp->lock, flags);
1180                 if (rnp->qsmask != 0) {
1181                         for (cpu = 0; cpu <= rnp->grphi - rnp->grplo; cpu++)
1182                                 if (rnp->qsmask & (1UL << cpu))
1183                                         dump_cpu_task(rnp->grplo + cpu);
1184                 }
1185                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1186         }
1187 }
1188
1189 static void print_other_cpu_stall(struct rcu_state *rsp, unsigned long gpnum)
1190 {
1191         int cpu;
1192         long delta;
1193         unsigned long flags;
1194         unsigned long gpa;
1195         unsigned long j;
1196         int ndetected = 0;
1197         struct rcu_node *rnp = rcu_get_root(rsp);
1198         long totqlen = 0;
1199
1200         /* Only let one CPU complain about others per time interval. */
1201
1202         raw_spin_lock_irqsave(&rnp->lock, flags);
1203         delta = jiffies - ACCESS_ONCE(rsp->jiffies_stall);
1204         if (delta < RCU_STALL_RAT_DELAY || !rcu_gp_in_progress(rsp)) {
1205                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1206                 return;
1207         }
1208         ACCESS_ONCE(rsp->jiffies_stall) = jiffies + 3 * rcu_jiffies_till_stall_check() + 3;
1209         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1210
1211         /*
1212          * OK, time to rat on our buddy...
1213          * See Documentation/RCU/stallwarn.txt for info on how to debug
1214          * RCU CPU stall warnings.
1215          */
1216         pr_err("INFO: %s detected stalls on CPUs/tasks:",
1217                rsp->name);
1218         print_cpu_stall_info_begin();
1219         rcu_for_each_leaf_node(rsp, rnp) {
1220                 raw_spin_lock_irqsave(&rnp->lock, flags);
1221                 ndetected += rcu_print_task_stall(rnp);
1222                 if (rnp->qsmask != 0) {
1223                         for (cpu = 0; cpu <= rnp->grphi - rnp->grplo; cpu++)
1224                                 if (rnp->qsmask & (1UL << cpu)) {
1225                                         print_cpu_stall_info(rsp,
1226                                                              rnp->grplo + cpu);
1227                                         ndetected++;
1228                                 }
1229                 }
1230                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1231         }
1232
1233         print_cpu_stall_info_end();
1234         for_each_possible_cpu(cpu)
1235                 totqlen += per_cpu_ptr(rsp->rda, cpu)->qlen;
1236         pr_cont("(detected by %d, t=%ld jiffies, g=%ld, c=%ld, q=%lu)\n",
1237                smp_processor_id(), (long)(jiffies - rsp->gp_start),
1238                (long)rsp->gpnum, (long)rsp->completed, totqlen);
1239         if (ndetected) {
1240                 rcu_dump_cpu_stacks(rsp);
1241         } else {
1242                 if (ACCESS_ONCE(rsp->gpnum) != gpnum ||
1243                     ACCESS_ONCE(rsp->completed) == gpnum) {
1244                         pr_err("INFO: Stall ended before state dump start\n");
1245                 } else {
1246                         j = jiffies;
1247                         gpa = ACCESS_ONCE(rsp->gp_activity);
1248                         pr_err("All QSes seen, last %s kthread activity %ld (%ld-%ld), jiffies_till_next_fqs=%ld, root ->qsmask %#lx\n",
1249                                rsp->name, j - gpa, j, gpa,
1250                                jiffies_till_next_fqs,
1251                                rcu_get_root(rsp)->qsmask);
1252                         /* In this case, the current CPU might be at fault. */
1253                         sched_show_task(current);
1254                 }
1255         }
1256
1257         /* Complain about tasks blocking the grace period. */
1258         rcu_print_detail_task_stall(rsp);
1259
1260         rcu_check_gp_kthread_starvation(rsp);
1261
1262         force_quiescent_state(rsp);  /* Kick them all. */
1263 }
1264
1265 static void print_cpu_stall(struct rcu_state *rsp)
1266 {
1267         int cpu;
1268         unsigned long flags;
1269         struct rcu_node *rnp = rcu_get_root(rsp);
1270         long totqlen = 0;
1271
1272         /*
1273          * OK, time to rat on ourselves...
1274          * See Documentation/RCU/stallwarn.txt for info on how to debug
1275          * RCU CPU stall warnings.
1276          */
1277         pr_err("INFO: %s self-detected stall on CPU", rsp->name);
1278         print_cpu_stall_info_begin();
1279         print_cpu_stall_info(rsp, smp_processor_id());
1280         print_cpu_stall_info_end();
1281         for_each_possible_cpu(cpu)
1282                 totqlen += per_cpu_ptr(rsp->rda, cpu)->qlen;
1283         pr_cont(" (t=%lu jiffies g=%ld c=%ld q=%lu)\n",
1284                 jiffies - rsp->gp_start,
1285                 (long)rsp->gpnum, (long)rsp->completed, totqlen);
1286
1287         rcu_check_gp_kthread_starvation(rsp);
1288
1289         rcu_dump_cpu_stacks(rsp);
1290
1291         raw_spin_lock_irqsave(&rnp->lock, flags);
1292         if (ULONG_CMP_GE(jiffies, ACCESS_ONCE(rsp->jiffies_stall)))
1293                 ACCESS_ONCE(rsp->jiffies_stall) = jiffies +
1294                                      3 * rcu_jiffies_till_stall_check() + 3;
1295         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1296
1297         /*
1298          * Attempt to revive the RCU machinery by forcing a context switch.
1299          *
1300          * A context switch would normally allow the RCU state machine to make
1301          * progress and it could be we're stuck in kernel space without context
1302          * switches for an entirely unreasonable amount of time.
1303          */
1304         resched_cpu(smp_processor_id());
1305 }
1306
1307 static void check_cpu_stall(struct rcu_state *rsp, struct rcu_data *rdp)
1308 {
1309         unsigned long completed;
1310         unsigned long gpnum;
1311         unsigned long gps;
1312         unsigned long j;
1313         unsigned long js;
1314         struct rcu_node *rnp;
1315
1316         if (rcu_cpu_stall_suppress || !rcu_gp_in_progress(rsp))
1317                 return;
1318         j = jiffies;
1319
1320         /*
1321          * Lots of memory barriers to reject false positives.
1322          *
1323          * The idea is to pick up rsp->gpnum, then rsp->jiffies_stall,
1324          * then rsp->gp_start, and finally rsp->completed.  These values
1325          * are updated in the opposite order with memory barriers (or
1326          * equivalent) during grace-period initialization and cleanup.
1327          * Now, a false positive can occur if we get an new value of
1328          * rsp->gp_start and a old value of rsp->jiffies_stall.  But given
1329          * the memory barriers, the only way that this can happen is if one
1330          * grace period ends and another starts between these two fetches.
1331          * Detect this by comparing rsp->completed with the previous fetch
1332          * from rsp->gpnum.
1333          *
1334          * Given this check, comparisons of jiffies, rsp->jiffies_stall,
1335          * and rsp->gp_start suffice to forestall false positives.
1336          */
1337         gpnum = ACCESS_ONCE(rsp->gpnum);
1338         smp_rmb(); /* Pick up ->gpnum first... */
1339         js = ACCESS_ONCE(rsp->jiffies_stall);
1340         smp_rmb(); /* ...then ->jiffies_stall before the rest... */
1341         gps = ACCESS_ONCE(rsp->gp_start);
1342         smp_rmb(); /* ...and finally ->gp_start before ->completed. */
1343         completed = ACCESS_ONCE(rsp->completed);
1344         if (ULONG_CMP_GE(completed, gpnum) ||
1345             ULONG_CMP_LT(j, js) ||
1346             ULONG_CMP_GE(gps, js))
1347                 return; /* No stall or GP completed since entering function. */
1348         rnp = rdp->mynode;
1349         if (rcu_gp_in_progress(rsp) &&
1350             (ACCESS_ONCE(rnp->qsmask) & rdp->grpmask)) {
1351
1352                 /* We haven't checked in, so go dump stack. */
1353                 print_cpu_stall(rsp);
1354
1355         } else if (rcu_gp_in_progress(rsp) &&
1356                    ULONG_CMP_GE(j, js + RCU_STALL_RAT_DELAY)) {
1357
1358                 /* They had a few time units to dump stack, so complain. */
1359                 print_other_cpu_stall(rsp, gpnum);
1360         }
1361 }
1362
1363 /**
1364  * rcu_cpu_stall_reset - prevent further stall warnings in current grace period
1365  *
1366  * Set the stall-warning timeout way off into the future, thus preventing
1367  * any RCU CPU stall-warning messages from appearing in the current set of
1368  * RCU grace periods.
1369  *
1370  * The caller must disable hard irqs.
1371  */
1372 void rcu_cpu_stall_reset(void)
1373 {
1374         struct rcu_state *rsp;
1375
1376         for_each_rcu_flavor(rsp)
1377                 ACCESS_ONCE(rsp->jiffies_stall) = jiffies + ULONG_MAX / 2;
1378 }
1379
1380 /*
1381  * Initialize the specified rcu_data structure's default callback list
1382  * to empty.  The default callback list is the one that is not used by
1383  * no-callbacks CPUs.
1384  */
1385 static void init_default_callback_list(struct rcu_data *rdp)
1386 {
1387         int i;
1388
1389         rdp->nxtlist = NULL;
1390         for (i = 0; i < RCU_NEXT_SIZE; i++)
1391                 rdp->nxttail[i] = &rdp->nxtlist;
1392 }
1393
1394 /*
1395  * Initialize the specified rcu_data structure's callback list to empty.
1396  */
1397 static void init_callback_list(struct rcu_data *rdp)
1398 {
1399         if (init_nocb_callback_list(rdp))
1400                 return;
1401         init_default_callback_list(rdp);
1402 }
1403
1404 /*
1405  * Determine the value that ->completed will have at the end of the
1406  * next subsequent grace period.  This is used to tag callbacks so that
1407  * a CPU can invoke callbacks in a timely fashion even if that CPU has
1408  * been dyntick-idle for an extended period with callbacks under the
1409  * influence of RCU_FAST_NO_HZ.
1410  *
1411  * The caller must hold rnp->lock with interrupts disabled.
1412  */
1413 static unsigned long rcu_cbs_completed(struct rcu_state *rsp,
1414                                        struct rcu_node *rnp)
1415 {
1416         /*
1417          * If RCU is idle, we just wait for the next grace period.
1418          * But we can only be sure that RCU is idle if we are looking
1419          * at the root rcu_node structure -- otherwise, a new grace
1420          * period might have started, but just not yet gotten around
1421          * to initializing the current non-root rcu_node structure.
1422          */
1423         if (rcu_get_root(rsp) == rnp && rnp->gpnum == rnp->completed)
1424                 return rnp->completed + 1;
1425
1426         /*
1427          * Otherwise, wait for a possible partial grace period and
1428          * then the subsequent full grace period.
1429          */
1430         return rnp->completed + 2;
1431 }
1432
1433 /*
1434  * Trace-event helper function for rcu_start_future_gp() and
1435  * rcu_nocb_wait_gp().
1436  */
1437 static void trace_rcu_future_gp(struct rcu_node *rnp, struct rcu_data *rdp,
1438                                 unsigned long c, const char *s)
1439 {
1440         trace_rcu_future_grace_period(rdp->rsp->name, rnp->gpnum,
1441                                       rnp->completed, c, rnp->level,
1442                                       rnp->grplo, rnp->grphi, s);
1443 }
1444
1445 /*
1446  * Start some future grace period, as needed to handle newly arrived
1447  * callbacks.  The required future grace periods are recorded in each
1448  * rcu_node structure's ->need_future_gp field.  Returns true if there
1449  * is reason to awaken the grace-period kthread.
1450  *
1451  * The caller must hold the specified rcu_node structure's ->lock.
1452  */
1453 static bool __maybe_unused
1454 rcu_start_future_gp(struct rcu_node *rnp, struct rcu_data *rdp,
1455                     unsigned long *c_out)
1456 {
1457         unsigned long c;
1458         int i;
1459         bool ret = false;
1460         struct rcu_node *rnp_root = rcu_get_root(rdp->rsp);
1461
1462         /*
1463          * Pick up grace-period number for new callbacks.  If this
1464          * grace period is already marked as needed, return to the caller.
1465          */
1466         c = rcu_cbs_completed(rdp->rsp, rnp);
1467         trace_rcu_future_gp(rnp, rdp, c, TPS("Startleaf"));
1468         if (rnp->need_future_gp[c & 0x1]) {
1469                 trace_rcu_future_gp(rnp, rdp, c, TPS("Prestartleaf"));
1470                 goto out;
1471         }
1472
1473         /*
1474          * If either this rcu_node structure or the root rcu_node structure
1475          * believe that a grace period is in progress, then we must wait
1476          * for the one following, which is in "c".  Because our request
1477          * will be noticed at the end of the current grace period, we don't
1478          * need to explicitly start one.  We only do the lockless check
1479          * of rnp_root's fields if the current rcu_node structure thinks
1480          * there is no grace period in flight, and because we hold rnp->lock,
1481          * the only possible change is when rnp_root's two fields are
1482          * equal, in which case rnp_root->gpnum might be concurrently
1483          * incremented.  But that is OK, as it will just result in our
1484          * doing some extra useless work.
1485          */
1486         if (rnp->gpnum != rnp->completed ||
1487             ACCESS_ONCE(rnp_root->gpnum) != ACCESS_ONCE(rnp_root->completed)) {
1488                 rnp->need_future_gp[c & 0x1]++;
1489                 trace_rcu_future_gp(rnp, rdp, c, TPS("Startedleaf"));
1490                 goto out;
1491         }
1492
1493         /*
1494          * There might be no grace period in progress.  If we don't already
1495          * hold it, acquire the root rcu_node structure's lock in order to
1496          * start one (if needed).
1497          */
1498         if (rnp != rnp_root) {
1499                 raw_spin_lock(&rnp_root->lock);
1500                 smp_mb__after_unlock_lock();
1501         }
1502
1503         /*
1504          * Get a new grace-period number.  If there really is no grace
1505          * period in progress, it will be smaller than the one we obtained
1506          * earlier.  Adjust callbacks as needed.  Note that even no-CBs
1507          * CPUs have a ->nxtcompleted[] array, so no no-CBs checks needed.
1508          */
1509         c = rcu_cbs_completed(rdp->rsp, rnp_root);
1510         for (i = RCU_DONE_TAIL; i < RCU_NEXT_TAIL; i++)
1511                 if (ULONG_CMP_LT(c, rdp->nxtcompleted[i]))
1512                         rdp->nxtcompleted[i] = c;
1513
1514         /*
1515          * If the needed for the required grace period is already
1516          * recorded, trace and leave.
1517          */
1518         if (rnp_root->need_future_gp[c & 0x1]) {
1519                 trace_rcu_future_gp(rnp, rdp, c, TPS("Prestartedroot"));
1520                 goto unlock_out;
1521         }
1522
1523         /* Record the need for the future grace period. */
1524         rnp_root->need_future_gp[c & 0x1]++;
1525
1526         /* If a grace period is not already in progress, start one. */
1527         if (rnp_root->gpnum != rnp_root->completed) {
1528                 trace_rcu_future_gp(rnp, rdp, c, TPS("Startedleafroot"));
1529         } else {
1530                 trace_rcu_future_gp(rnp, rdp, c, TPS("Startedroot"));
1531                 ret = rcu_start_gp_advanced(rdp->rsp, rnp_root, rdp);
1532         }
1533 unlock_out:
1534         if (rnp != rnp_root)
1535                 raw_spin_unlock(&rnp_root->lock);
1536 out:
1537         if (c_out != NULL)
1538                 *c_out = c;
1539         return ret;
1540 }
1541
1542 /*
1543  * Clean up any old requests for the just-ended grace period.  Also return
1544  * whether any additional grace periods have been requested.  Also invoke
1545  * rcu_nocb_gp_cleanup() in order to wake up any no-callbacks kthreads
1546  * waiting for this grace period to complete.
1547  */
1548 static int rcu_future_gp_cleanup(struct rcu_state *rsp, struct rcu_node *rnp)
1549 {
1550         int c = rnp->completed;
1551         int needmore;
1552         struct rcu_data *rdp = this_cpu_ptr(rsp->rda);
1553
1554         rcu_nocb_gp_cleanup(rsp, rnp);
1555         rnp->need_future_gp[c & 0x1] = 0;
1556         needmore = rnp->need_future_gp[(c + 1) & 0x1];
1557         trace_rcu_future_gp(rnp, rdp, c,
1558                             needmore ? TPS("CleanupMore") : TPS("Cleanup"));
1559         return needmore;
1560 }
1561
1562 /*
1563  * Awaken the grace-period kthread for the specified flavor of RCU.
1564  * Don't do a self-awaken, and don't bother awakening when there is
1565  * nothing for the grace-period kthread to do (as in several CPUs
1566  * raced to awaken, and we lost), and finally don't try to awaken
1567  * a kthread that has not yet been created.
1568  */
1569 static void rcu_gp_kthread_wake(struct rcu_state *rsp)
1570 {
1571         if (current == rsp->gp_kthread ||
1572             !ACCESS_ONCE(rsp->gp_flags) ||
1573             !rsp->gp_kthread)
1574                 return;
1575         swait_wake(&rsp->gp_wq);
1576 }
1577
1578 /*
1579  * If there is room, assign a ->completed number to any callbacks on
1580  * this CPU that have not already been assigned.  Also accelerate any
1581  * callbacks that were previously assigned a ->completed number that has
1582  * since proven to be too conservative, which can happen if callbacks get
1583  * assigned a ->completed number while RCU is idle, but with reference to
1584  * a non-root rcu_node structure.  This function is idempotent, so it does
1585  * not hurt to call it repeatedly.  Returns an flag saying that we should
1586  * awaken the RCU grace-period kthread.
1587  *
1588  * The caller must hold rnp->lock with interrupts disabled.
1589  */
1590 static bool rcu_accelerate_cbs(struct rcu_state *rsp, struct rcu_node *rnp,
1591                                struct rcu_data *rdp)
1592 {
1593         unsigned long c;
1594         int i;
1595         bool ret;
1596
1597         /* If the CPU has no callbacks, nothing to do. */
1598         if (!rdp->nxttail[RCU_NEXT_TAIL] || !*rdp->nxttail[RCU_DONE_TAIL])
1599                 return false;
1600
1601         /*
1602          * Starting from the sublist containing the callbacks most
1603          * recently assigned a ->completed number and working down, find the
1604          * first sublist that is not assignable to an upcoming grace period.
1605          * Such a sublist has something in it (first two tests) and has
1606          * a ->completed number assigned that will complete sooner than
1607          * the ->completed number for newly arrived callbacks (last test).
1608          *
1609          * The key point is that any later sublist can be assigned the
1610          * same ->completed number as the newly arrived callbacks, which
1611          * means that the callbacks in any of these later sublist can be
1612          * grouped into a single sublist, whether or not they have already
1613          * been assigned a ->completed number.
1614          */
1615         c = rcu_cbs_completed(rsp, rnp);
1616         for (i = RCU_NEXT_TAIL - 1; i > RCU_DONE_TAIL; i--)
1617                 if (rdp->nxttail[i] != rdp->nxttail[i - 1] &&
1618                     !ULONG_CMP_GE(rdp->nxtcompleted[i], c))
1619                         break;
1620
1621         /*
1622          * If there are no sublist for unassigned callbacks, leave.
1623          * At the same time, advance "i" one sublist, so that "i" will
1624          * index into the sublist where all the remaining callbacks should
1625          * be grouped into.
1626          */
1627         if (++i >= RCU_NEXT_TAIL)
1628                 return false;
1629
1630         /*
1631          * Assign all subsequent callbacks' ->completed number to the next
1632          * full grace period and group them all in the sublist initially
1633          * indexed by "i".
1634          */
1635         for (; i <= RCU_NEXT_TAIL; i++) {
1636                 rdp->nxttail[i] = rdp->nxttail[RCU_NEXT_TAIL];
1637                 rdp->nxtcompleted[i] = c;
1638         }
1639         /* Record any needed additional grace periods. */
1640         ret = rcu_start_future_gp(rnp, rdp, NULL);
1641
1642         /* Trace depending on how much we were able to accelerate. */
1643         if (!*rdp->nxttail[RCU_WAIT_TAIL])
1644                 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("AccWaitCB"));
1645         else
1646                 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("AccReadyCB"));
1647         return ret;
1648 }
1649
1650 /*
1651  * Move any callbacks whose grace period has completed to the
1652  * RCU_DONE_TAIL sublist, then compact the remaining sublists and
1653  * assign ->completed numbers to any callbacks in the RCU_NEXT_TAIL
1654  * sublist.  This function is idempotent, so it does not hurt to
1655  * invoke it repeatedly.  As long as it is not invoked -too- often...
1656  * Returns true if the RCU grace-period kthread needs to be awakened.
1657  *
1658  * The caller must hold rnp->lock with interrupts disabled.
1659  */
1660 static bool rcu_advance_cbs(struct rcu_state *rsp, struct rcu_node *rnp,
1661                             struct rcu_data *rdp)
1662 {
1663         int i, j;
1664
1665         /* If the CPU has no callbacks, nothing to do. */
1666         if (!rdp->nxttail[RCU_NEXT_TAIL] || !*rdp->nxttail[RCU_DONE_TAIL])
1667                 return false;
1668
1669         /*
1670          * Find all callbacks whose ->completed numbers indicate that they
1671          * are ready to invoke, and put them into the RCU_DONE_TAIL sublist.
1672          */
1673         for (i = RCU_WAIT_TAIL; i < RCU_NEXT_TAIL; i++) {
1674                 if (ULONG_CMP_LT(rnp->completed, rdp->nxtcompleted[i]))
1675                         break;
1676                 rdp->nxttail[RCU_DONE_TAIL] = rdp->nxttail[i];
1677         }
1678         /* Clean up any sublist tail pointers that were misordered above. */
1679         for (j = RCU_WAIT_TAIL; j < i; j++)
1680                 rdp->nxttail[j] = rdp->nxttail[RCU_DONE_TAIL];
1681
1682         /* Copy down callbacks to fill in empty sublists. */
1683         for (j = RCU_WAIT_TAIL; i < RCU_NEXT_TAIL; i++, j++) {
1684                 if (rdp->nxttail[j] == rdp->nxttail[RCU_NEXT_TAIL])
1685                         break;
1686                 rdp->nxttail[j] = rdp->nxttail[i];
1687                 rdp->nxtcompleted[j] = rdp->nxtcompleted[i];
1688         }
1689
1690         /* Classify any remaining callbacks. */
1691         return rcu_accelerate_cbs(rsp, rnp, rdp);
1692 }
1693
1694 /*
1695  * Update CPU-local rcu_data state to record the beginnings and ends of
1696  * grace periods.  The caller must hold the ->lock of the leaf rcu_node
1697  * structure corresponding to the current CPU, and must have irqs disabled.
1698  * Returns true if the grace-period kthread needs to be awakened.
1699  */
1700 static bool __note_gp_changes(struct rcu_state *rsp, struct rcu_node *rnp,
1701                               struct rcu_data *rdp)
1702 {
1703         bool ret;
1704
1705         /* Handle the ends of any preceding grace periods first. */
1706         if (rdp->completed == rnp->completed &&
1707             !unlikely(ACCESS_ONCE(rdp->gpwrap))) {
1708
1709                 /* No grace period end, so just accelerate recent callbacks. */
1710                 ret = rcu_accelerate_cbs(rsp, rnp, rdp);
1711
1712         } else {
1713
1714                 /* Advance callbacks. */
1715                 ret = rcu_advance_cbs(rsp, rnp, rdp);
1716
1717                 /* Remember that we saw this grace-period completion. */
1718                 rdp->completed = rnp->completed;
1719                 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("cpuend"));
1720         }
1721
1722         if (rdp->gpnum != rnp->gpnum || unlikely(ACCESS_ONCE(rdp->gpwrap))) {
1723                 /*
1724                  * If the current grace period is waiting for this CPU,
1725                  * set up to detect a quiescent state, otherwise don't
1726                  * go looking for one.
1727                  */
1728                 rdp->gpnum = rnp->gpnum;
1729                 trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("cpustart"));
1730                 rdp->passed_quiesce = 0;
1731                 rdp->rcu_qs_ctr_snap = __this_cpu_read(rcu_qs_ctr);
1732                 rdp->qs_pending = !!(rnp->qsmask & rdp->grpmask);
1733                 zero_cpu_stall_ticks(rdp);
1734                 ACCESS_ONCE(rdp->gpwrap) = false;
1735         }
1736         return ret;
1737 }
1738
1739 static void note_gp_changes(struct rcu_state *rsp, struct rcu_data *rdp)
1740 {
1741         unsigned long flags;
1742         bool needwake;
1743         struct rcu_node *rnp;
1744
1745         local_irq_save(flags);
1746         rnp = rdp->mynode;
1747         if ((rdp->gpnum == ACCESS_ONCE(rnp->gpnum) &&
1748              rdp->completed == ACCESS_ONCE(rnp->completed) &&
1749              !unlikely(ACCESS_ONCE(rdp->gpwrap))) || /* w/out lock. */
1750             !raw_spin_trylock(&rnp->lock)) { /* irqs already off, so later. */
1751                 local_irq_restore(flags);
1752                 return;
1753         }
1754         smp_mb__after_unlock_lock();
1755         needwake = __note_gp_changes(rsp, rnp, rdp);
1756         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1757         if (needwake)
1758                 rcu_gp_kthread_wake(rsp);
1759 }
1760
1761 /*
1762  * Initialize a new grace period.  Return 0 if no grace period required.
1763  */
1764 static int rcu_gp_init(struct rcu_state *rsp)
1765 {
1766         unsigned long oldmask;
1767         struct rcu_data *rdp;
1768         struct rcu_node *rnp = rcu_get_root(rsp);
1769
1770         ACCESS_ONCE(rsp->gp_activity) = jiffies;
1771         raw_spin_lock_irq(&rnp->lock);
1772         smp_mb__after_unlock_lock();
1773         if (!ACCESS_ONCE(rsp->gp_flags)) {
1774                 /* Spurious wakeup, tell caller to go back to sleep.  */
1775                 raw_spin_unlock_irq(&rnp->lock);
1776                 return 0;
1777         }
1778         ACCESS_ONCE(rsp->gp_flags) = 0; /* Clear all flags: New grace period. */
1779
1780         if (WARN_ON_ONCE(rcu_gp_in_progress(rsp))) {
1781                 /*
1782                  * Grace period already in progress, don't start another.
1783                  * Not supposed to be able to happen.
1784                  */
1785                 raw_spin_unlock_irq(&rnp->lock);
1786                 return 0;
1787         }
1788
1789         /* Advance to a new grace period and initialize state. */
1790         record_gp_stall_check_time(rsp);
1791         /* Record GP times before starting GP, hence smp_store_release(). */
1792         smp_store_release(&rsp->gpnum, rsp->gpnum + 1);
1793         trace_rcu_grace_period(rsp->name, rsp->gpnum, TPS("start"));
1794         raw_spin_unlock_irq(&rnp->lock);
1795
1796         /*
1797          * Apply per-leaf buffered online and offline operations to the
1798          * rcu_node tree.  Note that this new grace period need not wait
1799          * for subsequent online CPUs, and that quiescent-state forcing
1800          * will handle subsequent offline CPUs.
1801          */
1802         rcu_for_each_leaf_node(rsp, rnp) {
1803                 raw_spin_lock_irq(&rnp->lock);
1804                 smp_mb__after_unlock_lock();
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(&rnp->lock);
1809                         continue;
1810                 }
1811
1812                 /* Record old state, apply changes to ->qsmaskinit field. */
1813                 oldmask = rnp->qsmaskinit;
1814                 rnp->qsmaskinit = rnp->qsmaskinitnext;
1815
1816                 /* If zero-ness of ->qsmaskinit changed, propagate up tree. */
1817                 if (!oldmask != !rnp->qsmaskinit) {
1818                         if (!oldmask) /* First online CPU for this rcu_node. */
1819                                 rcu_init_new_rnp(rnp);
1820                         else if (rcu_preempt_has_tasks(rnp)) /* blocked tasks */
1821                                 rnp->wait_blkd_tasks = true;
1822                         else /* Last offline CPU and can propagate. */
1823                                 rcu_cleanup_dead_rnp(rnp);
1824                 }
1825
1826                 /*
1827                  * If all waited-on tasks from prior grace period are
1828                  * done, and if all this rcu_node structure's CPUs are
1829                  * still offline, propagate up the rcu_node tree and
1830                  * clear ->wait_blkd_tasks.  Otherwise, if one of this
1831                  * rcu_node structure's CPUs has since come back online,
1832                  * simply clear ->wait_blkd_tasks (but rcu_cleanup_dead_rnp()
1833                  * checks for this, so just call it unconditionally).
1834                  */
1835                 if (rnp->wait_blkd_tasks &&
1836                     (!rcu_preempt_has_tasks(rnp) ||
1837                      rnp->qsmaskinit)) {
1838                         rnp->wait_blkd_tasks = false;
1839                         rcu_cleanup_dead_rnp(rnp);
1840                 }
1841
1842                 raw_spin_unlock_irq(&rnp->lock);
1843         }
1844
1845         /*
1846          * Set the quiescent-state-needed bits in all the rcu_node
1847          * structures for all currently online CPUs in breadth-first order,
1848          * starting from the root rcu_node structure, relying on the layout
1849          * of the tree within the rsp->node[] array.  Note that other CPUs
1850          * will access only the leaves of the hierarchy, thus seeing that no
1851          * grace period is in progress, at least until the corresponding
1852          * leaf node has been initialized.  In addition, we have excluded
1853          * CPU-hotplug operations.
1854          *
1855          * The grace period cannot complete until the initialization
1856          * process finishes, because this kthread handles both.
1857          */
1858         rcu_for_each_node_breadth_first(rsp, rnp) {
1859                 raw_spin_lock_irq(&rnp->lock);
1860                 smp_mb__after_unlock_lock();
1861                 rdp = this_cpu_ptr(rsp->rda);
1862                 rcu_preempt_check_blocked_tasks(rnp);
1863                 rnp->qsmask = rnp->qsmaskinit;
1864                 ACCESS_ONCE(rnp->gpnum) = rsp->gpnum;
1865                 if (WARN_ON_ONCE(rnp->completed != rsp->completed))
1866                         ACCESS_ONCE(rnp->completed) = rsp->completed;
1867                 if (rnp == rdp->mynode)
1868                         (void)__note_gp_changes(rsp, rnp, rdp);
1869                 rcu_preempt_boost_start_gp(rnp);
1870                 trace_rcu_grace_period_init(rsp->name, rnp->gpnum,
1871                                             rnp->level, rnp->grplo,
1872                                             rnp->grphi, rnp->qsmask);
1873                 raw_spin_unlock_irq(&rnp->lock);
1874                 cond_resched_rcu_qs();
1875                 ACCESS_ONCE(rsp->gp_activity) = jiffies;
1876                 if (gp_init_delay > 0 &&
1877                     !(rsp->gpnum % (rcu_num_nodes * PER_RCU_NODE_PERIOD)))
1878                         schedule_timeout_uninterruptible(gp_init_delay);
1879         }
1880
1881         return 1;
1882 }
1883
1884 /*
1885  * Do one round of quiescent-state forcing.
1886  */
1887 static int rcu_gp_fqs(struct rcu_state *rsp, int fqs_state_in)
1888 {
1889         int fqs_state = fqs_state_in;
1890         bool isidle = false;
1891         unsigned long maxj;
1892         struct rcu_node *rnp = rcu_get_root(rsp);
1893
1894         ACCESS_ONCE(rsp->gp_activity) = jiffies;
1895         rsp->n_force_qs++;
1896         if (fqs_state == RCU_SAVE_DYNTICK) {
1897                 /* Collect dyntick-idle snapshots. */
1898                 if (is_sysidle_rcu_state(rsp)) {
1899                         isidle = true;
1900                         maxj = jiffies - ULONG_MAX / 4;
1901                 }
1902                 force_qs_rnp(rsp, dyntick_save_progress_counter,
1903                              &isidle, &maxj);
1904                 rcu_sysidle_report_gp(rsp, isidle, maxj);
1905                 fqs_state = RCU_FORCE_QS;
1906         } else {
1907                 /* Handle dyntick-idle and offline CPUs. */
1908                 isidle = true;
1909                 force_qs_rnp(rsp, rcu_implicit_dynticks_qs, &isidle, &maxj);
1910         }
1911         /* Clear flag to prevent immediate re-entry. */
1912         if (ACCESS_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) {
1913                 raw_spin_lock_irq(&rnp->lock);
1914                 smp_mb__after_unlock_lock();
1915                 ACCESS_ONCE(rsp->gp_flags) =
1916                         ACCESS_ONCE(rsp->gp_flags) & ~RCU_GP_FLAG_FQS;
1917                 raw_spin_unlock_irq(&rnp->lock);
1918         }
1919         return fqs_state;
1920 }
1921
1922 /*
1923  * Clean up after the old grace period.
1924  */
1925 static void rcu_gp_cleanup(struct rcu_state *rsp)
1926 {
1927         unsigned long gp_duration;
1928         bool needgp = false;
1929         int nocb = 0;
1930         struct rcu_data *rdp;
1931         struct rcu_node *rnp = rcu_get_root(rsp);
1932
1933         ACCESS_ONCE(rsp->gp_activity) = jiffies;
1934         raw_spin_lock_irq(&rnp->lock);
1935         smp_mb__after_unlock_lock();
1936         gp_duration = jiffies - rsp->gp_start;
1937         if (gp_duration > rsp->gp_max)
1938                 rsp->gp_max = gp_duration;
1939
1940         /*
1941          * We know the grace period is complete, but to everyone else
1942          * it appears to still be ongoing.  But it is also the case
1943          * that to everyone else it looks like there is nothing that
1944          * they can do to advance the grace period.  It is therefore
1945          * safe for us to drop the lock in order to mark the grace
1946          * period as completed in all of the rcu_node structures.
1947          */
1948         raw_spin_unlock_irq(&rnp->lock);
1949
1950         /*
1951          * Propagate new ->completed value to rcu_node structures so
1952          * that other CPUs don't have to wait until the start of the next
1953          * grace period to process their callbacks.  This also avoids
1954          * some nasty RCU grace-period initialization races by forcing
1955          * the end of the current grace period to be completely recorded in
1956          * all of the rcu_node structures before the beginning of the next
1957          * grace period is recorded in any of the rcu_node structures.
1958          */
1959         rcu_for_each_node_breadth_first(rsp, rnp) {
1960                 raw_spin_lock_irq(&rnp->lock);
1961                 smp_mb__after_unlock_lock();
1962                 WARN_ON_ONCE(rcu_preempt_blocked_readers_cgp(rnp));
1963                 WARN_ON_ONCE(rnp->qsmask);
1964                 ACCESS_ONCE(rnp->completed) = rsp->gpnum;
1965                 rdp = this_cpu_ptr(rsp->rda);
1966                 if (rnp == rdp->mynode)
1967                         needgp = __note_gp_changes(rsp, rnp, rdp) || needgp;
1968                 /* smp_mb() provided by prior unlock-lock pair. */
1969                 nocb += rcu_future_gp_cleanup(rsp, rnp);
1970                 raw_spin_unlock_irq(&rnp->lock);
1971                 cond_resched_rcu_qs();
1972                 ACCESS_ONCE(rsp->gp_activity) = jiffies;
1973         }
1974         rnp = rcu_get_root(rsp);
1975         raw_spin_lock_irq(&rnp->lock);
1976         smp_mb__after_unlock_lock(); /* Order GP before ->completed update. */
1977         rcu_nocb_gp_set(rnp, nocb);
1978
1979         /* Declare grace period done. */
1980         ACCESS_ONCE(rsp->completed) = rsp->gpnum;
1981         trace_rcu_grace_period(rsp->name, rsp->completed, TPS("end"));
1982         rsp->fqs_state = RCU_GP_IDLE;
1983         rdp = this_cpu_ptr(rsp->rda);
1984         /* Advance CBs to reduce false positives below. */
1985         needgp = rcu_advance_cbs(rsp, rnp, rdp) || needgp;
1986         if (needgp || cpu_needs_another_gp(rsp, rdp)) {
1987                 ACCESS_ONCE(rsp->gp_flags) = RCU_GP_FLAG_INIT;
1988                 trace_rcu_grace_period(rsp->name,
1989                                        ACCESS_ONCE(rsp->gpnum),
1990                                        TPS("newreq"));
1991         }
1992         raw_spin_unlock_irq(&rnp->lock);
1993 }
1994
1995 /*
1996  * Body of kthread that handles grace periods.
1997  */
1998 static int __noreturn rcu_gp_kthread(void *arg)
1999 {
2000         int fqs_state;
2001         int gf;
2002         unsigned long j;
2003         int ret;
2004         struct rcu_state *rsp = arg;
2005         struct rcu_node *rnp = rcu_get_root(rsp);
2006
2007         rcu_bind_gp_kthread();
2008         for (;;) {
2009
2010                 /* Handle grace-period start. */
2011                 for (;;) {
2012                         trace_rcu_grace_period(rsp->name,
2013                                                ACCESS_ONCE(rsp->gpnum),
2014                                                TPS("reqwait"));
2015                         rsp->gp_state = RCU_GP_WAIT_GPS;
2016                         swait_event_interruptible(rsp->gp_wq,
2017                                                  ACCESS_ONCE(rsp->gp_flags) &
2018                                                  RCU_GP_FLAG_INIT);
2019                         /* Locking provides needed memory barrier. */
2020                         if (rcu_gp_init(rsp))
2021                                 break;
2022                         cond_resched_rcu_qs();
2023                         ACCESS_ONCE(rsp->gp_activity) = jiffies;
2024                         WARN_ON(signal_pending(current));
2025                         trace_rcu_grace_period(rsp->name,
2026                                                ACCESS_ONCE(rsp->gpnum),
2027                                                TPS("reqwaitsig"));
2028                 }
2029
2030                 /* Handle quiescent-state forcing. */
2031                 fqs_state = RCU_SAVE_DYNTICK;
2032                 j = jiffies_till_first_fqs;
2033                 if (j > HZ) {
2034                         j = HZ;
2035                         jiffies_till_first_fqs = HZ;
2036                 }
2037                 ret = 0;
2038                 for (;;) {
2039                         if (!ret)
2040                                 rsp->jiffies_force_qs = jiffies + j;
2041                         trace_rcu_grace_period(rsp->name,
2042                                                ACCESS_ONCE(rsp->gpnum),
2043                                                TPS("fqswait"));
2044                         rsp->gp_state = RCU_GP_WAIT_FQS;
2045                         ret = swait_event_interruptible_timeout(rsp->gp_wq,
2046                                         ((gf = ACCESS_ONCE(rsp->gp_flags)) &
2047                                          RCU_GP_FLAG_FQS) ||
2048                                         (!ACCESS_ONCE(rnp->qsmask) &&
2049                                          !rcu_preempt_blocked_readers_cgp(rnp)),
2050                                         j);
2051                         /* Locking provides needed memory barriers. */
2052                         /* If grace period done, leave loop. */
2053                         if (!ACCESS_ONCE(rnp->qsmask) &&
2054                             !rcu_preempt_blocked_readers_cgp(rnp))
2055                                 break;
2056                         /* If time for quiescent-state forcing, do it. */
2057                         if (ULONG_CMP_GE(jiffies, rsp->jiffies_force_qs) ||
2058                             (gf & RCU_GP_FLAG_FQS)) {
2059                                 trace_rcu_grace_period(rsp->name,
2060                                                        ACCESS_ONCE(rsp->gpnum),
2061                                                        TPS("fqsstart"));
2062                                 fqs_state = rcu_gp_fqs(rsp, fqs_state);
2063                                 trace_rcu_grace_period(rsp->name,
2064                                                        ACCESS_ONCE(rsp->gpnum),
2065                                                        TPS("fqsend"));
2066                                 cond_resched_rcu_qs();
2067                                 ACCESS_ONCE(rsp->gp_activity) = jiffies;
2068                         } else {
2069                                 /* Deal with stray signal. */
2070                                 cond_resched_rcu_qs();
2071                                 ACCESS_ONCE(rsp->gp_activity) = jiffies;
2072                                 WARN_ON(signal_pending(current));
2073                                 trace_rcu_grace_period(rsp->name,
2074                                                        ACCESS_ONCE(rsp->gpnum),
2075                                                        TPS("fqswaitsig"));
2076                         }
2077                         j = jiffies_till_next_fqs;
2078                         if (j > HZ) {
2079                                 j = HZ;
2080                                 jiffies_till_next_fqs = HZ;
2081                         } else if (j < 1) {
2082                                 j = 1;
2083                                 jiffies_till_next_fqs = 1;
2084                         }
2085                 }
2086
2087                 /* Handle grace-period end. */
2088                 rcu_gp_cleanup(rsp);
2089         }
2090 }
2091
2092 /*
2093  * Start a new RCU grace period if warranted, re-initializing the hierarchy
2094  * in preparation for detecting the next grace period.  The caller must hold
2095  * the root node's ->lock and hard irqs must be disabled.
2096  *
2097  * Note that it is legal for a dying CPU (which is marked as offline) to
2098  * invoke this function.  This can happen when the dying CPU reports its
2099  * quiescent state.
2100  *
2101  * Returns true if the grace-period kthread must be awakened.
2102  */
2103 static bool
2104 rcu_start_gp_advanced(struct rcu_state *rsp, struct rcu_node *rnp,
2105                       struct rcu_data *rdp)
2106 {
2107         if (!rsp->gp_kthread || !cpu_needs_another_gp(rsp, rdp)) {
2108                 /*
2109                  * Either we have not yet spawned the grace-period
2110                  * task, this CPU does not need another grace period,
2111                  * or a grace period is already in progress.
2112                  * Either way, don't start a new grace period.
2113                  */
2114                 return false;
2115         }
2116         ACCESS_ONCE(rsp->gp_flags) = RCU_GP_FLAG_INIT;
2117         trace_rcu_grace_period(rsp->name, ACCESS_ONCE(rsp->gpnum),
2118                                TPS("newreq"));
2119
2120         /*
2121          * We can't do wakeups while holding the rnp->lock, as that
2122          * could cause possible deadlocks with the rq->lock. Defer
2123          * the wakeup to our caller.
2124          */
2125         return true;
2126 }
2127
2128 /*
2129  * Similar to rcu_start_gp_advanced(), but also advance the calling CPU's
2130  * callbacks.  Note that rcu_start_gp_advanced() cannot do this because it
2131  * is invoked indirectly from rcu_advance_cbs(), which would result in
2132  * endless recursion -- or would do so if it wasn't for the self-deadlock
2133  * that is encountered beforehand.
2134  *
2135  * Returns true if the grace-period kthread needs to be awakened.
2136  */
2137 static bool rcu_start_gp(struct rcu_state *rsp)
2138 {
2139         struct rcu_data *rdp = this_cpu_ptr(rsp->rda);
2140         struct rcu_node *rnp = rcu_get_root(rsp);
2141         bool ret = false;
2142
2143         /*
2144          * If there is no grace period in progress right now, any
2145          * callbacks we have up to this point will be satisfied by the
2146          * next grace period.  Also, advancing the callbacks reduces the
2147          * probability of false positives from cpu_needs_another_gp()
2148          * resulting in pointless grace periods.  So, advance callbacks
2149          * then start the grace period!
2150          */
2151         ret = rcu_advance_cbs(rsp, rnp, rdp) || ret;
2152         ret = rcu_start_gp_advanced(rsp, rnp, rdp) || ret;
2153         return ret;
2154 }
2155
2156 /*
2157  * Report a full set of quiescent states to the specified rcu_state
2158  * data structure.  This involves cleaning up after the prior grace
2159  * period and letting rcu_start_gp() start up the next grace period
2160  * if one is needed.  Note that the caller must hold rnp->lock, which
2161  * is released before return.
2162  */
2163 static void rcu_report_qs_rsp(struct rcu_state *rsp, unsigned long flags)
2164         __releases(rcu_get_root(rsp)->lock)
2165 {
2166         WARN_ON_ONCE(!rcu_gp_in_progress(rsp));
2167         raw_spin_unlock_irqrestore(&rcu_get_root(rsp)->lock, flags);
2168         rcu_gp_kthread_wake(rsp);
2169 }
2170
2171 /*
2172  * Similar to rcu_report_qs_rdp(), for which it is a helper function.
2173  * Allows quiescent states for a group of CPUs to be reported at one go
2174  * to the specified rcu_node structure, though all the CPUs in the group
2175  * must be represented by the same rcu_node structure (which need not be a
2176  * leaf rcu_node structure, though it often will be).  The gps parameter
2177  * is the grace-period snapshot, which means that the quiescent states
2178  * are valid only if rnp->gpnum is equal to gps.  That structure's lock
2179  * must be held upon entry, and it is released before return.
2180  */
2181 static void
2182 rcu_report_qs_rnp(unsigned long mask, struct rcu_state *rsp,
2183                   struct rcu_node *rnp, unsigned long gps, unsigned long flags)
2184         __releases(rnp->lock)
2185 {
2186         unsigned long oldmask = 0;
2187         struct rcu_node *rnp_c;
2188
2189         /* Walk up the rcu_node hierarchy. */
2190         for (;;) {
2191                 if (!(rnp->qsmask & mask) || rnp->gpnum != gps) {
2192
2193                         /*
2194                          * Our bit has already been cleared, or the
2195                          * relevant grace period is already over, so done.
2196                          */
2197                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
2198                         return;
2199                 }
2200                 WARN_ON_ONCE(oldmask); /* Any child must be all zeroed! */
2201                 rnp->qsmask &= ~mask;
2202                 trace_rcu_quiescent_state_report(rsp->name, rnp->gpnum,
2203                                                  mask, rnp->qsmask, rnp->level,
2204                                                  rnp->grplo, rnp->grphi,
2205                                                  !!rnp->gp_tasks);
2206                 if (rnp->qsmask != 0 || rcu_preempt_blocked_readers_cgp(rnp)) {
2207
2208                         /* Other bits still set at this level, so done. */
2209                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
2210                         return;
2211                 }
2212                 mask = rnp->grpmask;
2213                 if (rnp->parent == NULL) {
2214
2215                         /* No more levels.  Exit loop holding root lock. */
2216
2217                         break;
2218                 }
2219                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2220                 rnp_c = rnp;
2221                 rnp = rnp->parent;
2222                 raw_spin_lock_irqsave(&rnp->lock, flags);
2223                 smp_mb__after_unlock_lock();
2224                 oldmask = rnp_c->qsmask;
2225         }
2226
2227         /*
2228          * Get here if we are the last CPU to pass through a quiescent
2229          * state for this grace period.  Invoke rcu_report_qs_rsp()
2230          * to clean up and start the next grace period if one is needed.
2231          */
2232         rcu_report_qs_rsp(rsp, flags); /* releases rnp->lock. */
2233 }
2234
2235 /*
2236  * Record a quiescent state for all tasks that were previously queued
2237  * on the specified rcu_node structure and that were blocking the current
2238  * RCU grace period.  The caller must hold the specified rnp->lock with
2239  * irqs disabled, and this lock is released upon return, but irqs remain
2240  * disabled.
2241  */
2242 static void rcu_report_unblock_qs_rnp(struct rcu_state *rsp,
2243                                       struct rcu_node *rnp, unsigned long flags)
2244         __releases(rnp->lock)
2245 {
2246         unsigned long gps;
2247         unsigned long mask;
2248         struct rcu_node *rnp_p;
2249
2250         if (rcu_state_p == &rcu_sched_state || rsp != rcu_state_p ||
2251             rnp->qsmask != 0 || rcu_preempt_blocked_readers_cgp(rnp)) {
2252                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2253                 return;  /* Still need more quiescent states! */
2254         }
2255
2256         rnp_p = rnp->parent;
2257         if (rnp_p == NULL) {
2258                 /*
2259                  * Only one rcu_node structure in the tree, so don't
2260                  * try to report up to its nonexistent parent!
2261                  */
2262                 rcu_report_qs_rsp(rsp, flags);
2263                 return;
2264         }
2265
2266         /* Report up the rest of the hierarchy, tracking current ->gpnum. */
2267         gps = rnp->gpnum;
2268         mask = rnp->grpmask;
2269         raw_spin_unlock(&rnp->lock);    /* irqs remain disabled. */
2270         raw_spin_lock(&rnp_p->lock);    /* irqs already disabled. */
2271         smp_mb__after_unlock_lock();
2272         rcu_report_qs_rnp(mask, rsp, rnp_p, gps, flags);
2273 }
2274
2275 /*
2276  * Record a quiescent state for the specified CPU to that CPU's rcu_data
2277  * structure.  This must be either called from the specified CPU, or
2278  * called when the specified CPU is known to be offline (and when it is
2279  * also known that no other CPU is concurrently trying to help the offline
2280  * CPU).  The lastcomp argument is used to make sure we are still in the
2281  * grace period of interest.  We don't want to end the current grace period
2282  * based on quiescent states detected in an earlier grace period!
2283  */
2284 static void
2285 rcu_report_qs_rdp(int cpu, struct rcu_state *rsp, struct rcu_data *rdp)
2286 {
2287         unsigned long flags;
2288         unsigned long mask;
2289         bool needwake;
2290         struct rcu_node *rnp;
2291
2292         rnp = rdp->mynode;
2293         raw_spin_lock_irqsave(&rnp->lock, flags);
2294         smp_mb__after_unlock_lock();
2295         if ((rdp->passed_quiesce == 0 &&
2296              rdp->rcu_qs_ctr_snap == __this_cpu_read(rcu_qs_ctr)) ||
2297             rdp->gpnum != rnp->gpnum || rnp->completed == rnp->gpnum ||
2298             rdp->gpwrap) {
2299
2300                 /*
2301                  * The grace period in which this quiescent state was
2302                  * recorded has ended, so don't report it upwards.
2303                  * We will instead need a new quiescent state that lies
2304                  * within the current grace period.
2305                  */
2306                 rdp->passed_quiesce = 0;        /* need qs for new gp. */
2307                 rdp->rcu_qs_ctr_snap = __this_cpu_read(rcu_qs_ctr);
2308                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2309                 return;
2310         }
2311         mask = rdp->grpmask;
2312         if ((rnp->qsmask & mask) == 0) {
2313                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2314         } else {
2315                 rdp->qs_pending = 0;
2316
2317                 /*
2318                  * This GP can't end until cpu checks in, so all of our
2319                  * callbacks can be processed during the next GP.
2320                  */
2321                 needwake = rcu_accelerate_cbs(rsp, rnp, rdp);
2322
2323                 rcu_report_qs_rnp(mask, rsp, rnp, rnp->gpnum, flags);
2324                 /* ^^^ Released rnp->lock */
2325                 if (needwake)
2326                         rcu_gp_kthread_wake(rsp);
2327         }
2328 }
2329
2330 /*
2331  * Check to see if there is a new grace period of which this CPU
2332  * is not yet aware, and if so, set up local rcu_data state for it.
2333  * Otherwise, see if this CPU has just passed through its first
2334  * quiescent state for this grace period, and record that fact if so.
2335  */
2336 static void
2337 rcu_check_quiescent_state(struct rcu_state *rsp, struct rcu_data *rdp)
2338 {
2339         /* Check for grace-period ends and beginnings. */
2340         note_gp_changes(rsp, rdp);
2341
2342         /*
2343          * Does this CPU still need to do its part for current grace period?
2344          * If no, return and let the other CPUs do their part as well.
2345          */
2346         if (!rdp->qs_pending)
2347                 return;
2348
2349         /*
2350          * Was there a quiescent state since the beginning of the grace
2351          * period? If no, then exit and wait for the next call.
2352          */
2353         if (!rdp->passed_quiesce &&
2354             rdp->rcu_qs_ctr_snap == __this_cpu_read(rcu_qs_ctr))
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->cpu, rsp, rdp);
2362 }
2363
2364 #ifdef CONFIG_HOTPLUG_CPU
2365
2366 /*
2367  * Send the specified CPU's RCU callbacks to the orphanage.  The
2368  * specified CPU must be offline, and the caller must hold the
2369  * ->orphan_lock.
2370  */
2371 static void
2372 rcu_send_cbs_to_orphanage(int cpu, struct rcu_state *rsp,
2373                           struct rcu_node *rnp, struct rcu_data *rdp)
2374 {
2375         /* No-CBs CPUs do not have orphanable callbacks. */
2376         if (rcu_is_nocb_cpu(rdp->cpu))
2377                 return;
2378
2379         /*
2380          * Orphan the callbacks.  First adjust the counts.  This is safe
2381          * because _rcu_barrier() excludes CPU-hotplug operations, so it
2382          * cannot be running now.  Thus no memory barrier is required.
2383          */
2384         if (rdp->nxtlist != NULL) {
2385                 rsp->qlen_lazy += rdp->qlen_lazy;
2386                 rsp->qlen += rdp->qlen;
2387                 rdp->n_cbs_orphaned += rdp->qlen;
2388                 rdp->qlen_lazy = 0;
2389                 ACCESS_ONCE(rdp->qlen) = 0;
2390         }
2391
2392         /*
2393          * Next, move those callbacks still needing a grace period to
2394          * the orphanage, where some other CPU will pick them up.
2395          * Some of the callbacks might have gone partway through a grace
2396          * period, but that is too bad.  They get to start over because we
2397          * cannot assume that grace periods are synchronized across CPUs.
2398          * We don't bother updating the ->nxttail[] array yet, instead
2399          * we just reset the whole thing later on.
2400          */
2401         if (*rdp->nxttail[RCU_DONE_TAIL] != NULL) {
2402                 *rsp->orphan_nxttail = *rdp->nxttail[RCU_DONE_TAIL];
2403                 rsp->orphan_nxttail = rdp->nxttail[RCU_NEXT_TAIL];
2404                 *rdp->nxttail[RCU_DONE_TAIL] = NULL;
2405         }
2406
2407         /*
2408          * Then move the ready-to-invoke callbacks to the orphanage,
2409          * where some other CPU will pick them up.  These will not be
2410          * required to pass though another grace period: They are done.
2411          */
2412         if (rdp->nxtlist != NULL) {
2413                 *rsp->orphan_donetail = rdp->nxtlist;
2414                 rsp->orphan_donetail = rdp->nxttail[RCU_DONE_TAIL];
2415         }
2416
2417         /*
2418          * Finally, initialize the rcu_data structure's list to empty and
2419          * disallow further callbacks on this CPU.
2420          */
2421         init_callback_list(rdp);
2422         rdp->nxttail[RCU_NEXT_TAIL] = NULL;
2423 }
2424
2425 /*
2426  * Adopt the RCU callbacks from the specified rcu_state structure's
2427  * orphanage.  The caller must hold the ->orphan_lock.
2428  */
2429 static void rcu_adopt_orphan_cbs(struct rcu_state *rsp, unsigned long flags)
2430 {
2431         int i;
2432         struct rcu_data *rdp = raw_cpu_ptr(rsp->rda);
2433
2434         /* No-CBs CPUs are handled specially. */
2435         if (rcu_nocb_adopt_orphan_cbs(rsp, rdp, flags))
2436                 return;
2437
2438         /* Do the accounting first. */
2439         rdp->qlen_lazy += rsp->qlen_lazy;
2440         rdp->qlen += rsp->qlen;
2441         rdp->n_cbs_adopted += rsp->qlen;
2442         if (rsp->qlen_lazy != rsp->qlen)
2443                 rcu_idle_count_callbacks_posted();
2444         rsp->qlen_lazy = 0;
2445         rsp->qlen = 0;
2446
2447         /*
2448          * We do not need a memory barrier here because the only way we
2449          * can get here if there is an rcu_barrier() in flight is if
2450          * we are the task doing the rcu_barrier().
2451          */
2452
2453         /* First adopt the ready-to-invoke callbacks. */
2454         if (rsp->orphan_donelist != NULL) {
2455                 *rsp->orphan_donetail = *rdp->nxttail[RCU_DONE_TAIL];
2456                 *rdp->nxttail[RCU_DONE_TAIL] = rsp->orphan_donelist;
2457                 for (i = RCU_NEXT_SIZE - 1; i >= RCU_DONE_TAIL; i--)
2458                         if (rdp->nxttail[i] == rdp->nxttail[RCU_DONE_TAIL])
2459                                 rdp->nxttail[i] = rsp->orphan_donetail;
2460                 rsp->orphan_donelist = NULL;
2461                 rsp->orphan_donetail = &rsp->orphan_donelist;
2462         }
2463
2464         /* And then adopt the callbacks that still need a grace period. */
2465         if (rsp->orphan_nxtlist != NULL) {
2466                 *rdp->nxttail[RCU_NEXT_TAIL] = rsp->orphan_nxtlist;
2467                 rdp->nxttail[RCU_NEXT_TAIL] = rsp->orphan_nxttail;
2468                 rsp->orphan_nxtlist = NULL;
2469                 rsp->orphan_nxttail = &rsp->orphan_nxtlist;
2470         }
2471 }
2472
2473 /*
2474  * Trace the fact that this CPU is going offline.
2475  */
2476 static void rcu_cleanup_dying_cpu(struct rcu_state *rsp)
2477 {
2478         RCU_TRACE(unsigned long mask);
2479         RCU_TRACE(struct rcu_data *rdp = this_cpu_ptr(rsp->rda));
2480         RCU_TRACE(struct rcu_node *rnp = rdp->mynode);
2481
2482         RCU_TRACE(mask = rdp->grpmask);
2483         trace_rcu_grace_period(rsp->name,
2484                                rnp->gpnum + 1 - !!(rnp->qsmask & mask),
2485                                TPS("cpuofl"));
2486 }
2487
2488 /*
2489  * All CPUs for the specified rcu_node structure have gone offline,
2490  * and all tasks that were preempted within an RCU read-side critical
2491  * section while running on one of those CPUs have since exited their RCU
2492  * read-side critical section.  Some other CPU is reporting this fact with
2493  * the specified rcu_node structure's ->lock held and interrupts disabled.
2494  * This function therefore goes up the tree of rcu_node structures,
2495  * clearing the corresponding bits in the ->qsmaskinit fields.  Note that
2496  * the leaf rcu_node structure's ->qsmaskinit field has already been
2497  * updated
2498  *
2499  * This function does check that the specified rcu_node structure has
2500  * all CPUs offline and no blocked tasks, so it is OK to invoke it
2501  * prematurely.  That said, invoking it after the fact will cost you
2502  * a needless lock acquisition.  So once it has done its work, don't
2503  * invoke it again.
2504  */
2505 static void rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf)
2506 {
2507         long mask;
2508         struct rcu_node *rnp = rnp_leaf;
2509
2510         if (rnp->qsmaskinit || rcu_preempt_has_tasks(rnp))
2511                 return;
2512         for (;;) {
2513                 mask = rnp->grpmask;
2514                 rnp = rnp->parent;
2515                 if (!rnp)
2516                         break;
2517                 raw_spin_lock(&rnp->lock); /* irqs already disabled. */
2518                 smp_mb__after_unlock_lock(); /* GP memory ordering. */
2519                 rnp->qsmaskinit &= ~mask;
2520                 rnp->qsmask &= ~mask;
2521                 if (rnp->qsmaskinit) {
2522                         raw_spin_unlock(&rnp->lock); /* irqs remain disabled. */
2523                         return;
2524                 }
2525                 raw_spin_unlock(&rnp->lock); /* irqs remain disabled. */
2526         }
2527 }
2528
2529 /*
2530  * The CPU is exiting the idle loop into the arch_cpu_idle_dead()
2531  * function.  We now remove it from the rcu_node tree's ->qsmaskinit
2532  * bit masks.
2533  */
2534 static void rcu_cleanup_dying_idle_cpu(int cpu, struct rcu_state *rsp)
2535 {
2536         unsigned long flags;
2537         unsigned long mask;
2538         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
2539         struct rcu_node *rnp = rdp->mynode;  /* Outgoing CPU's rdp & rnp. */
2540
2541         /* Remove outgoing CPU from mask in the leaf rcu_node structure. */
2542         mask = rdp->grpmask;
2543         raw_spin_lock_irqsave(&rnp->lock, flags);
2544         smp_mb__after_unlock_lock();    /* Enforce GP memory-order guarantee. */
2545         rnp->qsmaskinitnext &= ~mask;
2546         raw_spin_unlock_irqrestore(&rnp->lock, flags);
2547 }
2548
2549 /*
2550  * The CPU has been completely removed, and some other CPU is reporting
2551  * this fact from process context.  Do the remainder of the cleanup,
2552  * including orphaning the outgoing CPU's RCU callbacks, and also
2553  * adopting them.  There can only be one CPU hotplug operation at a time,
2554  * so no other CPU can be attempting to update rcu_cpu_kthread_task.
2555  */
2556 static void rcu_cleanup_dead_cpu(int cpu, struct rcu_state *rsp)
2557 {
2558         unsigned long flags;
2559         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
2560         struct rcu_node *rnp = rdp->mynode;  /* Outgoing CPU's rdp & rnp. */
2561
2562         /* Adjust any no-longer-needed kthreads. */
2563         rcu_boost_kthread_setaffinity(rnp, -1);
2564
2565         /* Orphan the dead CPU's callbacks, and adopt them if appropriate. */
2566         raw_spin_lock_irqsave(&rsp->orphan_lock, flags);
2567         rcu_send_cbs_to_orphanage(cpu, rsp, rnp, rdp);
2568         rcu_adopt_orphan_cbs(rsp, flags);
2569         raw_spin_unlock_irqrestore(&rsp->orphan_lock, flags);
2570
2571         WARN_ONCE(rdp->qlen != 0 || rdp->nxtlist != NULL,
2572                   "rcu_cleanup_dead_cpu: Callbacks on offline CPU %d: qlen=%lu, nxtlist=%p\n",
2573                   cpu, rdp->qlen, rdp->nxtlist);
2574 }
2575
2576 #else /* #ifdef CONFIG_HOTPLUG_CPU */
2577
2578 static void rcu_cleanup_dying_cpu(struct rcu_state *rsp)
2579 {
2580 }
2581
2582 static void __maybe_unused rcu_cleanup_dead_rnp(struct rcu_node *rnp_leaf)
2583 {
2584 }
2585
2586 static void rcu_cleanup_dying_idle_cpu(int cpu, struct rcu_state *rsp)
2587 {
2588 }
2589
2590 static void rcu_cleanup_dead_cpu(int cpu, struct rcu_state *rsp)
2591 {
2592 }
2593
2594 #endif /* #else #ifdef CONFIG_HOTPLUG_CPU */
2595
2596 /*
2597  * Invoke any RCU callbacks that have made it to the end of their grace
2598  * period.  Thottle as specified by rdp->blimit.
2599  */
2600 static void rcu_do_batch(struct rcu_state *rsp, struct rcu_data *rdp)
2601 {
2602         unsigned long flags;
2603         struct rcu_head *next, *list, **tail;
2604         long bl, count, count_lazy;
2605         int i;
2606
2607         /* If no callbacks are ready, just return. */
2608         if (!cpu_has_callbacks_ready_to_invoke(rdp)) {
2609                 trace_rcu_batch_start(rsp->name, rdp->qlen_lazy, rdp->qlen, 0);
2610                 trace_rcu_batch_end(rsp->name, 0, !!ACCESS_ONCE(rdp->nxtlist),
2611                                     need_resched(), is_idle_task(current),
2612                                     rcu_is_callbacks_kthread());
2613                 return;
2614         }
2615
2616         /*
2617          * Extract the list of ready callbacks, disabling to prevent
2618          * races with call_rcu() from interrupt handlers.
2619          */
2620         local_irq_save(flags);
2621         WARN_ON_ONCE(cpu_is_offline(smp_processor_id()));
2622         bl = rdp->blimit;
2623         trace_rcu_batch_start(rsp->name, rdp->qlen_lazy, rdp->qlen, bl);
2624         list = rdp->nxtlist;
2625         rdp->nxtlist = *rdp->nxttail[RCU_DONE_TAIL];
2626         *rdp->nxttail[RCU_DONE_TAIL] = NULL;
2627         tail = rdp->nxttail[RCU_DONE_TAIL];
2628         for (i = RCU_NEXT_SIZE - 1; i >= 0; i--)
2629                 if (rdp->nxttail[i] == rdp->nxttail[RCU_DONE_TAIL])
2630                         rdp->nxttail[i] = &rdp->nxtlist;
2631         local_irq_restore(flags);
2632
2633         /* Invoke callbacks. */
2634         count = count_lazy = 0;
2635         while (list) {
2636                 next = list->next;
2637                 prefetch(next);
2638                 debug_rcu_head_unqueue(list);
2639                 if (__rcu_reclaim(rsp->name, list))
2640                         count_lazy++;
2641                 list = next;
2642                 /* Stop only if limit reached and CPU has something to do. */
2643                 if (++count >= bl &&
2644                     (need_resched() ||
2645                      (!is_idle_task(current) && !rcu_is_callbacks_kthread())))
2646                         break;
2647         }
2648
2649         local_irq_save(flags);
2650         trace_rcu_batch_end(rsp->name, count, !!list, need_resched(),
2651                             is_idle_task(current),
2652                             rcu_is_callbacks_kthread());
2653
2654         /* Update count, and requeue any remaining callbacks. */
2655         if (list != NULL) {
2656                 *tail = rdp->nxtlist;
2657                 rdp->nxtlist = list;
2658                 for (i = 0; i < RCU_NEXT_SIZE; i++)
2659                         if (&rdp->nxtlist == rdp->nxttail[i])
2660                                 rdp->nxttail[i] = tail;
2661                         else
2662                                 break;
2663         }
2664         smp_mb(); /* List handling before counting for rcu_barrier(). */
2665         rdp->qlen_lazy -= count_lazy;
2666         ACCESS_ONCE(rdp->qlen) = rdp->qlen - count;
2667         rdp->n_cbs_invoked += count;
2668
2669         /* Reinstate batch limit if we have worked down the excess. */
2670         if (rdp->blimit == LONG_MAX && rdp->qlen <= qlowmark)
2671                 rdp->blimit = blimit;
2672
2673         /* Reset ->qlen_last_fqs_check trigger if enough CBs have drained. */
2674         if (rdp->qlen == 0 && rdp->qlen_last_fqs_check != 0) {
2675                 rdp->qlen_last_fqs_check = 0;
2676                 rdp->n_force_qs_snap = rsp->n_force_qs;
2677         } else if (rdp->qlen < rdp->qlen_last_fqs_check - qhimark)
2678                 rdp->qlen_last_fqs_check = rdp->qlen;
2679         WARN_ON_ONCE((rdp->nxtlist == NULL) != (rdp->qlen == 0));
2680
2681         local_irq_restore(flags);
2682
2683         /* Re-invoke RCU core processing if there are callbacks remaining. */
2684         if (cpu_has_callbacks_ready_to_invoke(rdp))
2685                 invoke_rcu_core();
2686 }
2687
2688 /*
2689  * Check to see if this CPU is in a non-context-switch quiescent state
2690  * (user mode or idle loop for rcu, non-softirq execution for rcu_bh).
2691  * Also schedule RCU core processing.
2692  *
2693  * This function must be called from hardirq context.  It is normally
2694  * invoked from the scheduling-clock interrupt.  If rcu_pending returns
2695  * false, there is no point in invoking rcu_check_callbacks().
2696  */
2697 void rcu_check_callbacks(int user)
2698 {
2699         trace_rcu_utilization(TPS("Start scheduler-tick"));
2700         increment_cpu_stall_ticks();
2701         if (user || rcu_is_cpu_rrupt_from_idle()) {
2702
2703                 /*
2704                  * Get here if this CPU took its interrupt from user
2705                  * mode or from the idle loop, and if this is not a
2706                  * nested interrupt.  In this case, the CPU is in
2707                  * a quiescent state, so note it.
2708                  *
2709                  * No memory barrier is required here because both
2710                  * rcu_sched_qs() and rcu_bh_qs() reference only CPU-local
2711                  * variables that other CPUs neither access nor modify,
2712                  * at least not while the corresponding CPU is online.
2713                  */
2714
2715                 rcu_sched_qs();
2716                 rcu_bh_qs();
2717
2718         } else if (!in_softirq()) {
2719
2720                 /*
2721                  * Get here if this CPU did not take its interrupt from
2722                  * softirq, in other words, if it is not interrupting
2723                  * a rcu_bh read-side critical section.  This is an _bh
2724                  * critical section, so note it.
2725                  */
2726
2727                 rcu_bh_qs();
2728         }
2729         rcu_preempt_check_callbacks();
2730         if (rcu_pending())
2731                 invoke_rcu_core();
2732         if (user)
2733                 rcu_note_voluntary_context_switch(current);
2734         trace_rcu_utilization(TPS("End scheduler-tick"));
2735 }
2736
2737 /*
2738  * Scan the leaf rcu_node structures, processing dyntick state for any that
2739  * have not yet encountered a quiescent state, using the function specified.
2740  * Also initiate boosting for any threads blocked on the root rcu_node.
2741  *
2742  * The caller must have suppressed start of new grace periods.
2743  */
2744 static void force_qs_rnp(struct rcu_state *rsp,
2745                          int (*f)(struct rcu_data *rsp, bool *isidle,
2746                                   unsigned long *maxj),
2747                          bool *isidle, unsigned long *maxj)
2748 {
2749         unsigned long bit;
2750         int cpu;
2751         unsigned long flags;
2752         unsigned long mask;
2753         struct rcu_node *rnp;
2754
2755         rcu_for_each_leaf_node(rsp, rnp) {
2756                 cond_resched_rcu_qs();
2757                 mask = 0;
2758                 raw_spin_lock_irqsave(&rnp->lock, flags);
2759                 smp_mb__after_unlock_lock();
2760                 if (!rcu_gp_in_progress(rsp)) {
2761                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
2762                         return;
2763                 }
2764                 if (rnp->qsmask == 0) {
2765                         if (rcu_state_p == &rcu_sched_state ||
2766                             rsp != rcu_state_p ||
2767                             rcu_preempt_blocked_readers_cgp(rnp)) {
2768                                 /*
2769                                  * No point in scanning bits because they
2770                                  * are all zero.  But we might need to
2771                                  * priority-boost blocked readers.
2772                                  */
2773                                 rcu_initiate_boost(rnp, flags);
2774                                 /* rcu_initiate_boost() releases rnp->lock */
2775                                 continue;
2776                         }
2777                         if (rnp->parent &&
2778                             (rnp->parent->qsmask & rnp->grpmask)) {
2779                                 /*
2780                                  * Race between grace-period
2781                                  * initialization and task exiting RCU
2782                                  * read-side critical section: Report.
2783                                  */
2784                                 rcu_report_unblock_qs_rnp(rsp, rnp, flags);
2785                                 /* rcu_report_unblock_qs_rnp() rlses ->lock */
2786                                 continue;
2787                         }
2788                 }
2789                 cpu = rnp->grplo;
2790                 bit = 1;
2791                 for (; cpu <= rnp->grphi; cpu++, bit <<= 1) {
2792                         if ((rnp->qsmask & bit) != 0) {
2793                                 if ((rnp->qsmaskinit & bit) == 0)
2794                                         *isidle = false; /* Pending hotplug. */
2795                                 if (f(per_cpu_ptr(rsp->rda, cpu), isidle, maxj))
2796                                         mask |= bit;
2797                         }
2798                 }
2799                 if (mask != 0) {
2800                         /* Idle/offline CPUs, report (releases rnp->lock. */
2801                         rcu_report_qs_rnp(mask, rsp, rnp, rnp->gpnum, flags);
2802                 } else {
2803                         /* Nothing to do here, so just drop the lock. */
2804                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
2805                 }
2806         }
2807 }
2808
2809 /*
2810  * Force quiescent states on reluctant CPUs, and also detect which
2811  * CPUs are in dyntick-idle mode.
2812  */
2813 static void force_quiescent_state(struct rcu_state *rsp)
2814 {
2815         unsigned long flags;
2816         bool ret;
2817         struct rcu_node *rnp;
2818         struct rcu_node *rnp_old = NULL;
2819
2820         /* Funnel through hierarchy to reduce memory contention. */
2821         rnp = __this_cpu_read(rsp->rda->mynode);
2822         for (; rnp != NULL; rnp = rnp->parent) {
2823                 ret = (ACCESS_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) ||
2824                       !raw_spin_trylock(&rnp->fqslock);
2825                 if (rnp_old != NULL)
2826                         raw_spin_unlock(&rnp_old->fqslock);
2827                 if (ret) {
2828                         rsp->n_force_qs_lh++;
2829                         return;
2830                 }
2831                 rnp_old = rnp;
2832         }
2833         /* rnp_old == rcu_get_root(rsp), rnp == NULL. */
2834
2835         /* Reached the root of the rcu_node tree, acquire lock. */
2836         raw_spin_lock_irqsave(&rnp_old->lock, flags);
2837         smp_mb__after_unlock_lock();
2838         raw_spin_unlock(&rnp_old->fqslock);
2839         if (ACCESS_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) {
2840                 rsp->n_force_qs_lh++;
2841                 raw_spin_unlock_irqrestore(&rnp_old->lock, flags);
2842                 return;  /* Someone beat us to it. */
2843         }
2844         ACCESS_ONCE(rsp->gp_flags) =
2845                 ACCESS_ONCE(rsp->gp_flags) | RCU_GP_FLAG_FQS;
2846         raw_spin_unlock_irqrestore(&rnp_old->lock, flags);
2847         rcu_gp_kthread_wake(rsp);
2848 }
2849
2850 /*
2851  * This does the RCU core processing work for the specified rcu_state
2852  * and rcu_data structures.  This may be called only from the CPU to
2853  * whom the rdp belongs.
2854  */
2855 static void
2856 __rcu_process_callbacks(struct rcu_state *rsp)
2857 {
2858         unsigned long flags;
2859         bool needwake;
2860         struct rcu_data *rdp = raw_cpu_ptr(rsp->rda);
2861
2862         WARN_ON_ONCE(rdp->beenonline == 0);
2863
2864         /* Update RCU state based on any recent quiescent states. */
2865         rcu_check_quiescent_state(rsp, rdp);
2866
2867         /* Does this CPU require a not-yet-started grace period? */
2868         local_irq_save(flags);
2869         if (cpu_needs_another_gp(rsp, rdp)) {
2870                 raw_spin_lock(&rcu_get_root(rsp)->lock); /* irqs disabled. */
2871                 needwake = rcu_start_gp(rsp);
2872                 raw_spin_unlock_irqrestore(&rcu_get_root(rsp)->lock, flags);
2873                 if (needwake)
2874                         rcu_gp_kthread_wake(rsp);
2875         } else {
2876                 local_irq_restore(flags);
2877         }
2878
2879         /* If there are callbacks ready, invoke them. */
2880         if (cpu_has_callbacks_ready_to_invoke(rdp))
2881                 invoke_rcu_callbacks(rsp, rdp);
2882
2883         /* Do any needed deferred wakeups of rcuo kthreads. */
2884         do_nocb_deferred_wakeup(rdp);
2885 }
2886
2887 /*
2888  * Do RCU core processing for the current CPU.
2889  */
2890 static void rcu_process_callbacks(void)
2891 {
2892         struct rcu_state *rsp;
2893
2894         if (cpu_is_offline(smp_processor_id()))
2895                 return;
2896         for_each_rcu_flavor(rsp)
2897                 __rcu_process_callbacks(rsp);
2898 }
2899
2900 static DEFINE_PER_CPU(struct task_struct *, rcu_cpu_kthread_task);
2901 /*
2902  * Schedule RCU callback invocation.  If the specified type of RCU
2903  * does not support RCU priority boosting, just do a direct call,
2904  * otherwise wake up the per-CPU kernel kthread.  Note that because we
2905  * are running on the current CPU with softirqs disabled, the
2906  * rcu_cpu_kthread_task cannot disappear out from under us.
2907  */
2908 static void invoke_rcu_callbacks(struct rcu_state *rsp, struct rcu_data *rdp)
2909 {
2910         if (unlikely(!ACCESS_ONCE(rcu_scheduler_fully_active)))
2911                 return;
2912         rcu_do_batch(rsp, rdp);
2913 }
2914
2915 static void rcu_wake_cond(struct task_struct *t, int status)
2916 {
2917         /*
2918          * If the thread is yielding, only wake it when this
2919          * is invoked from idle
2920          */
2921         if (t && (status != RCU_KTHREAD_YIELDING || is_idle_task(current)))
2922                 wake_up_process(t);
2923 }
2924
2925 /*
2926  * Wake up this CPU's rcuc kthread to do RCU core processing.
2927  */
2928 static void invoke_rcu_core(void)
2929 {
2930         unsigned long flags;
2931         struct task_struct *t;
2932
2933         if (!cpu_online(smp_processor_id()))
2934                 return;
2935         local_irq_save(flags);
2936         __this_cpu_write(rcu_cpu_has_work, 1);
2937         t = __this_cpu_read(rcu_cpu_kthread_task);
2938         if (t != NULL && current != t)
2939                 rcu_wake_cond(t, __this_cpu_read(rcu_cpu_kthread_status));
2940         local_irq_restore(flags);
2941 }
2942
2943 static void rcu_cpu_kthread_park(unsigned int cpu)
2944 {
2945         per_cpu(rcu_cpu_kthread_status, cpu) = RCU_KTHREAD_OFFCPU;
2946 }
2947
2948 static int rcu_cpu_kthread_should_run(unsigned int cpu)
2949 {
2950         return __this_cpu_read(rcu_cpu_has_work);
2951 }
2952
2953 /*
2954  * Per-CPU kernel thread that invokes RCU callbacks.  This replaces the
2955  * RCU softirq used in flavors and configurations of RCU that do not
2956  * support RCU priority boosting.
2957  */
2958 static void rcu_cpu_kthread(unsigned int cpu)
2959 {
2960         unsigned int *statusp = this_cpu_ptr(&rcu_cpu_kthread_status);
2961         char work, *workp = this_cpu_ptr(&rcu_cpu_has_work);
2962         int spincnt;
2963
2964         for (spincnt = 0; spincnt < 10; spincnt++) {
2965                 trace_rcu_utilization(TPS("Start CPU kthread@rcu_wait"));
2966                 local_bh_disable();
2967                 *statusp = RCU_KTHREAD_RUNNING;
2968                 this_cpu_inc(rcu_cpu_kthread_loops);
2969                 local_irq_disable();
2970                 work = *workp;
2971                 *workp = 0;
2972                 local_irq_enable();
2973                 if (work)
2974                         rcu_process_callbacks();
2975                 local_bh_enable();
2976                 if (*workp == 0) {
2977                         trace_rcu_utilization(TPS("End CPU kthread@rcu_wait"));
2978                         *statusp = RCU_KTHREAD_WAITING;
2979                         return;
2980                 }
2981         }
2982         *statusp = RCU_KTHREAD_YIELDING;
2983         trace_rcu_utilization(TPS("Start CPU kthread@rcu_yield"));
2984         schedule_timeout_interruptible(2);
2985         trace_rcu_utilization(TPS("End CPU kthread@rcu_yield"));
2986         *statusp = RCU_KTHREAD_WAITING;
2987 }
2988
2989 static struct smp_hotplug_thread rcu_cpu_thread_spec = {
2990         .store                  = &rcu_cpu_kthread_task,
2991         .thread_should_run      = rcu_cpu_kthread_should_run,
2992         .thread_fn              = rcu_cpu_kthread,
2993         .thread_comm            = "rcuc/%u",
2994         .setup                  = rcu_cpu_kthread_setup,
2995         .park                   = rcu_cpu_kthread_park,
2996 };
2997
2998 /*
2999  * Spawn per-CPU RCU core processing kthreads.
3000  */
3001 static int __init rcu_spawn_core_kthreads(void)
3002 {
3003         int cpu;
3004
3005         for_each_possible_cpu(cpu)
3006                 per_cpu(rcu_cpu_has_work, cpu) = 0;
3007         BUG_ON(smpboot_register_percpu_thread(&rcu_cpu_thread_spec));
3008         return 0;
3009 }
3010 early_initcall(rcu_spawn_core_kthreads);
3011
3012 /*
3013  * Handle any core-RCU processing required by a call_rcu() invocation.
3014  */
3015 static void __call_rcu_core(struct rcu_state *rsp, struct rcu_data *rdp,
3016                             struct rcu_head *head, unsigned long flags)
3017 {
3018         bool needwake;
3019
3020         /*
3021          * If called from an extended quiescent state, invoke the RCU
3022          * core in order to force a re-evaluation of RCU's idleness.
3023          */
3024         if (!rcu_is_watching())
3025                 invoke_rcu_core();
3026
3027         /* If interrupts were disabled or CPU offline, don't invoke RCU core. */
3028         if (irqs_disabled_flags(flags) || cpu_is_offline(smp_processor_id()))
3029                 return;
3030
3031         /*
3032          * Force the grace period if too many callbacks or too long waiting.
3033          * Enforce hysteresis, and don't invoke force_quiescent_state()
3034          * if some other CPU has recently done so.  Also, don't bother
3035          * invoking force_quiescent_state() if the newly enqueued callback
3036          * is the only one waiting for a grace period to complete.
3037          */
3038         if (unlikely(rdp->qlen > rdp->qlen_last_fqs_check + qhimark)) {
3039
3040                 /* Are we ignoring a completed grace period? */
3041                 note_gp_changes(rsp, rdp);
3042
3043                 /* Start a new grace period if one not already started. */
3044                 if (!rcu_gp_in_progress(rsp)) {
3045                         struct rcu_node *rnp_root = rcu_get_root(rsp);
3046
3047                         raw_spin_lock(&rnp_root->lock);
3048                         smp_mb__after_unlock_lock();
3049                         needwake = rcu_start_gp(rsp);
3050                         raw_spin_unlock(&rnp_root->lock);
3051                         if (needwake)
3052                                 rcu_gp_kthread_wake(rsp);
3053                 } else {
3054                         /* Give the grace period a kick. */
3055                         rdp->blimit = LONG_MAX;
3056                         if (rsp->n_force_qs == rdp->n_force_qs_snap &&
3057                             *rdp->nxttail[RCU_DONE_TAIL] != head)
3058                                 force_quiescent_state(rsp);
3059                         rdp->n_force_qs_snap = rsp->n_force_qs;
3060                         rdp->qlen_last_fqs_check = rdp->qlen;
3061                 }
3062         }
3063 }
3064
3065 /*
3066  * RCU callback function to leak a callback.
3067  */
3068 static void rcu_leak_callback(struct rcu_head *rhp)
3069 {
3070 }
3071
3072 /*
3073  * Helper function for call_rcu() and friends.  The cpu argument will
3074  * normally be -1, indicating "currently running CPU".  It may specify
3075  * a CPU only if that CPU is a no-CBs CPU.  Currently, only _rcu_barrier()
3076  * is expected to specify a CPU.
3077  */
3078 static void
3079 __call_rcu(struct rcu_head *head, void (*func)(struct rcu_head *rcu),
3080            struct rcu_state *rsp, int cpu, bool lazy)
3081 {
3082         unsigned long flags;
3083         struct rcu_data *rdp;
3084
3085         WARN_ON_ONCE((unsigned long)head & 0x1); /* Misaligned rcu_head! */
3086         if (debug_rcu_head_queue(head)) {
3087                 /* Probable double call_rcu(), so leak the callback. */
3088                 ACCESS_ONCE(head->func) = rcu_leak_callback;
3089                 WARN_ONCE(1, "__call_rcu(): Leaked duplicate callback\n");
3090                 return;
3091         }
3092         head->func = func;
3093         head->next = NULL;
3094
3095         /*
3096          * Opportunistically note grace-period endings and beginnings.
3097          * Note that we might see a beginning right after we see an
3098          * end, but never vice versa, since this CPU has to pass through
3099          * a quiescent state betweentimes.
3100          */
3101         local_irq_save(flags);
3102         rdp = this_cpu_ptr(rsp->rda);
3103
3104         /* Add the callback to our list. */
3105         if (unlikely(rdp->nxttail[RCU_NEXT_TAIL] == NULL) || cpu != -1) {
3106                 int offline;
3107
3108                 if (cpu != -1)
3109                         rdp = per_cpu_ptr(rsp->rda, cpu);
3110                 if (likely(rdp->mynode)) {
3111                         /* Post-boot, so this should be for a no-CBs CPU. */
3112                         offline = !__call_rcu_nocb(rdp, head, lazy, flags);
3113                         WARN_ON_ONCE(offline);
3114                         /* Offline CPU, _call_rcu() illegal, leak callback.  */
3115                         local_irq_restore(flags);
3116                         return;
3117                 }
3118                 /*
3119                  * Very early boot, before rcu_init().  Initialize if needed
3120                  * and then drop through to queue the callback.
3121                  */
3122                 BUG_ON(cpu != -1);
3123                 WARN_ON_ONCE(!rcu_is_watching());
3124                 if (!likely(rdp->nxtlist))
3125                         init_default_callback_list(rdp);
3126         }
3127         ACCESS_ONCE(rdp->qlen) = rdp->qlen + 1;
3128         if (lazy)
3129                 rdp->qlen_lazy++;
3130         else
3131                 rcu_idle_count_callbacks_posted();
3132         smp_mb();  /* Count before adding callback for rcu_barrier(). */
3133         *rdp->nxttail[RCU_NEXT_TAIL] = head;
3134         rdp->nxttail[RCU_NEXT_TAIL] = &head->next;
3135
3136         if (__is_kfree_rcu_offset((unsigned long)func))
3137                 trace_rcu_kfree_callback(rsp->name, head, (unsigned long)func,
3138                                          rdp->qlen_lazy, rdp->qlen);
3139         else
3140                 trace_rcu_callback(rsp->name, head, rdp->qlen_lazy, rdp->qlen);
3141
3142         /* Go handle any RCU core processing required. */
3143         __call_rcu_core(rsp, rdp, head, flags);
3144         local_irq_restore(flags);
3145 }
3146
3147 /*
3148  * Queue an RCU-sched callback for invocation after a grace period.
3149  */
3150 void call_rcu_sched(struct rcu_head *head, void (*func)(struct rcu_head *rcu))
3151 {
3152         __call_rcu(head, func, &rcu_sched_state, -1, 0);
3153 }
3154 EXPORT_SYMBOL_GPL(call_rcu_sched);
3155
3156 #ifndef CONFIG_PREEMPT_RT_FULL
3157 /*
3158  * Queue an RCU callback for invocation after a quicker grace period.
3159  */
3160 void call_rcu_bh(struct rcu_head *head, void (*func)(struct rcu_head *rcu))
3161 {
3162         __call_rcu(head, func, &rcu_bh_state, -1, 0);
3163 }
3164 EXPORT_SYMBOL_GPL(call_rcu_bh);
3165 #endif
3166
3167 /*
3168  * Queue an RCU callback for lazy invocation after a grace period.
3169  * This will likely be later named something like "call_rcu_lazy()",
3170  * but this change will require some way of tagging the lazy RCU
3171  * callbacks in the list of pending callbacks. Until then, this
3172  * function may only be called from __kfree_rcu().
3173  */
3174 void kfree_call_rcu(struct rcu_head *head,
3175                     void (*func)(struct rcu_head *rcu))
3176 {
3177         __call_rcu(head, func, rcu_state_p, -1, 1);
3178 }
3179 EXPORT_SYMBOL_GPL(kfree_call_rcu);
3180
3181 /*
3182  * Because a context switch is a grace period for RCU-sched and RCU-bh,
3183  * any blocking grace-period wait automatically implies a grace period
3184  * if there is only one CPU online at any point time during execution
3185  * of either synchronize_sched() or synchronize_rcu_bh().  It is OK to
3186  * occasionally incorrectly indicate that there are multiple CPUs online
3187  * when there was in fact only one the whole time, as this just adds
3188  * some overhead: RCU still operates correctly.
3189  */
3190 static inline int rcu_blocking_is_gp(void)
3191 {
3192         int ret;
3193
3194         might_sleep();  /* Check for RCU read-side critical section. */
3195         preempt_disable();
3196         ret = num_online_cpus() <= 1;
3197         preempt_enable();
3198         return ret;
3199 }
3200
3201 /**
3202  * synchronize_sched - wait until an rcu-sched grace period has elapsed.
3203  *
3204  * Control will return to the caller some time after a full rcu-sched
3205  * grace period has elapsed, in other words after all currently executing
3206  * rcu-sched read-side critical sections have completed.   These read-side
3207  * critical sections are delimited by rcu_read_lock_sched() and
3208  * rcu_read_unlock_sched(), and may be nested.  Note that preempt_disable(),
3209  * local_irq_disable(), and so on may be used in place of
3210  * rcu_read_lock_sched().
3211  *
3212  * This means that all preempt_disable code sequences, including NMI and
3213  * non-threaded hardware-interrupt handlers, in progress on entry will
3214  * have completed before this primitive returns.  However, this does not
3215  * guarantee that softirq handlers will have completed, since in some
3216  * kernels, these handlers can run in process context, and can block.
3217  *
3218  * Note that this guarantee implies further memory-ordering guarantees.
3219  * On systems with more than one CPU, when synchronize_sched() returns,
3220  * each CPU is guaranteed to have executed a full memory barrier since the
3221  * end of its last RCU-sched read-side critical section whose beginning
3222  * preceded the call to synchronize_sched().  In addition, each CPU having
3223  * an RCU read-side critical section that extends beyond the return from
3224  * synchronize_sched() is guaranteed to have executed a full memory barrier
3225  * after the beginning of synchronize_sched() and before the beginning of
3226  * that RCU read-side critical section.  Note that these guarantees include
3227  * CPUs that are offline, idle, or executing in user mode, as well as CPUs
3228  * that are executing in the kernel.
3229  *
3230  * Furthermore, if CPU A invoked synchronize_sched(), which returned
3231  * to its caller on CPU B, then both CPU A and CPU B are guaranteed
3232  * to have executed a full memory barrier during the execution of
3233  * synchronize_sched() -- even if CPU A and CPU B are the same CPU (but
3234  * again only if the system has more than one CPU).
3235  *
3236  * This primitive provides the guarantees made by the (now removed)
3237  * synchronize_kernel() API.  In contrast, synchronize_rcu() only
3238  * guarantees that rcu_read_lock() sections will have completed.
3239  * In "classic RCU", these two guarantees happen to be one and
3240  * the same, but can differ in realtime RCU implementations.
3241  */
3242 void synchronize_sched(void)
3243 {
3244         rcu_lockdep_assert(!lock_is_held(&rcu_bh_lock_map) &&
3245                            !lock_is_held(&rcu_lock_map) &&
3246                            !lock_is_held(&rcu_sched_lock_map),
3247                            "Illegal synchronize_sched() in RCU-sched read-side critical section");
3248         if (rcu_blocking_is_gp())
3249                 return;
3250         if (rcu_gp_is_expedited())
3251                 synchronize_sched_expedited();
3252         else
3253                 wait_rcu_gp(call_rcu_sched);
3254 }
3255 EXPORT_SYMBOL_GPL(synchronize_sched);
3256
3257 #ifndef CONFIG_PREEMPT_RT_FULL
3258 /**
3259  * synchronize_rcu_bh - wait until an rcu_bh grace period has elapsed.
3260  *
3261  * Control will return to the caller some time after a full rcu_bh grace
3262  * period has elapsed, in other words after all currently executing rcu_bh
3263  * read-side critical sections have completed.  RCU read-side critical
3264  * sections are delimited by rcu_read_lock_bh() and rcu_read_unlock_bh(),
3265  * and may be nested.
3266  *
3267  * See the description of synchronize_sched() for more detailed information
3268  * on memory ordering guarantees.
3269  */
3270 void synchronize_rcu_bh(void)
3271 {
3272         rcu_lockdep_assert(!lock_is_held(&rcu_bh_lock_map) &&
3273                            !lock_is_held(&rcu_lock_map) &&
3274                            !lock_is_held(&rcu_sched_lock_map),
3275                            "Illegal synchronize_rcu_bh() in RCU-bh read-side critical section");
3276         if (rcu_blocking_is_gp())
3277                 return;
3278         if (rcu_gp_is_expedited())
3279                 synchronize_rcu_bh_expedited();
3280         else
3281                 wait_rcu_gp(call_rcu_bh);
3282 }
3283 EXPORT_SYMBOL_GPL(synchronize_rcu_bh);
3284 #endif
3285
3286 /**
3287  * get_state_synchronize_rcu - Snapshot current RCU state
3288  *
3289  * Returns a cookie that is used by a later call to cond_synchronize_rcu()
3290  * to determine whether or not a full grace period has elapsed in the
3291  * meantime.
3292  */
3293 unsigned long get_state_synchronize_rcu(void)
3294 {
3295         /*
3296          * Any prior manipulation of RCU-protected data must happen
3297          * before the load from ->gpnum.
3298          */
3299         smp_mb();  /* ^^^ */
3300
3301         /*
3302          * Make sure this load happens before the purportedly
3303          * time-consuming work between get_state_synchronize_rcu()
3304          * and cond_synchronize_rcu().
3305          */
3306         return smp_load_acquire(&rcu_state_p->gpnum);
3307 }
3308 EXPORT_SYMBOL_GPL(get_state_synchronize_rcu);
3309
3310 /**
3311  * cond_synchronize_rcu - Conditionally wait for an RCU grace period
3312  *
3313  * @oldstate: return value from earlier call to get_state_synchronize_rcu()
3314  *
3315  * If a full RCU grace period has elapsed since the earlier call to
3316  * get_state_synchronize_rcu(), just return.  Otherwise, invoke
3317  * synchronize_rcu() to wait for a full grace period.
3318  *
3319  * Yes, this function does not take counter wrap into account.  But
3320  * counter wrap is harmless.  If the counter wraps, we have waited for
3321  * more than 2 billion grace periods (and way more on a 64-bit system!),
3322  * so waiting for one additional grace period should be just fine.
3323  */
3324 void cond_synchronize_rcu(unsigned long oldstate)
3325 {
3326         unsigned long newstate;
3327
3328         /*
3329          * Ensure that this load happens before any RCU-destructive
3330          * actions the caller might carry out after we return.
3331          */
3332         newstate = smp_load_acquire(&rcu_state_p->completed);
3333         if (ULONG_CMP_GE(oldstate, newstate))
3334                 synchronize_rcu();
3335 }
3336 EXPORT_SYMBOL_GPL(cond_synchronize_rcu);
3337
3338 static int synchronize_sched_expedited_cpu_stop(void *data)
3339 {
3340         /*
3341          * There must be a full memory barrier on each affected CPU
3342          * between the time that try_stop_cpus() is called and the
3343          * time that it returns.
3344          *
3345          * In the current initial implementation of cpu_stop, the
3346          * above condition is already met when the control reaches
3347          * this point and the following smp_mb() is not strictly
3348          * necessary.  Do smp_mb() anyway for documentation and
3349          * robustness against future implementation changes.
3350          */
3351         smp_mb(); /* See above comment block. */
3352         return 0;
3353 }
3354
3355 /**
3356  * synchronize_sched_expedited - Brute-force RCU-sched grace period
3357  *
3358  * Wait for an RCU-sched grace period to elapse, but use a "big hammer"
3359  * approach to force the grace period to end quickly.  This consumes
3360  * significant time on all CPUs and is unfriendly to real-time workloads,
3361  * so is thus not recommended for any sort of common-case code.  In fact,
3362  * if you are using synchronize_sched_expedited() in a loop, please
3363  * restructure your code to batch your updates, and then use a single
3364  * synchronize_sched() instead.
3365  *
3366  * This implementation can be thought of as an application of ticket
3367  * locking to RCU, with sync_sched_expedited_started and
3368  * sync_sched_expedited_done taking on the roles of the halves
3369  * of the ticket-lock word.  Each task atomically increments
3370  * sync_sched_expedited_started upon entry, snapshotting the old value,
3371  * then attempts to stop all the CPUs.  If this succeeds, then each
3372  * CPU will have executed a context switch, resulting in an RCU-sched
3373  * grace period.  We are then done, so we use atomic_cmpxchg() to
3374  * update sync_sched_expedited_done to match our snapshot -- but
3375  * only if someone else has not already advanced past our snapshot.
3376  *
3377  * On the other hand, if try_stop_cpus() fails, we check the value
3378  * of sync_sched_expedited_done.  If it has advanced past our
3379  * initial snapshot, then someone else must have forced a grace period
3380  * some time after we took our snapshot.  In this case, our work is
3381  * done for us, and we can simply return.  Otherwise, we try again,
3382  * but keep our initial snapshot for purposes of checking for someone
3383  * doing our work for us.
3384  *
3385  * If we fail too many times in a row, we fall back to synchronize_sched().
3386  */
3387 void synchronize_sched_expedited(void)
3388 {
3389         cpumask_var_t cm;
3390         bool cma = false;
3391         int cpu;
3392         long firstsnap, s, snap;
3393         int trycount = 0;
3394         struct rcu_state *rsp = &rcu_sched_state;
3395
3396         /*
3397          * If we are in danger of counter wrap, just do synchronize_sched().
3398          * By allowing sync_sched_expedited_started to advance no more than
3399          * ULONG_MAX/8 ahead of sync_sched_expedited_done, we are ensuring
3400          * that more than 3.5 billion CPUs would be required to force a
3401          * counter wrap on a 32-bit system.  Quite a few more CPUs would of
3402          * course be required on a 64-bit system.
3403          */
3404         if (ULONG_CMP_GE((ulong)atomic_long_read(&rsp->expedited_start),
3405                          (ulong)atomic_long_read(&rsp->expedited_done) +
3406                          ULONG_MAX / 8)) {
3407                 synchronize_sched();
3408                 atomic_long_inc(&rsp->expedited_wrap);
3409                 return;
3410         }
3411
3412         /*
3413          * Take a ticket.  Note that atomic_inc_return() implies a
3414          * full memory barrier.
3415          */
3416         snap = atomic_long_inc_return(&rsp->expedited_start);
3417         firstsnap = snap;
3418         if (!try_get_online_cpus()) {
3419                 /* CPU hotplug operation in flight, fall back to normal GP. */
3420                 wait_rcu_gp(call_rcu_sched);
3421                 atomic_long_inc(&rsp->expedited_normal);
3422                 return;
3423         }
3424         WARN_ON_ONCE(cpu_is_offline(raw_smp_processor_id()));
3425
3426         /* Offline CPUs, idle CPUs, and any CPU we run on are quiescent. */
3427         cma = zalloc_cpumask_var(&cm, GFP_KERNEL);
3428         if (cma) {
3429                 cpumask_copy(cm, cpu_online_mask);
3430                 cpumask_clear_cpu(raw_smp_processor_id(), cm);
3431                 for_each_cpu(cpu, cm) {
3432                         struct rcu_dynticks *rdtp = &per_cpu(rcu_dynticks, cpu);
3433
3434                         if (!(atomic_add_return(0, &rdtp->dynticks) & 0x1))
3435                                 cpumask_clear_cpu(cpu, cm);
3436                 }
3437                 if (cpumask_weight(cm) == 0)
3438                         goto all_cpus_idle;
3439         }
3440
3441         /*
3442          * Each pass through the following loop attempts to force a
3443          * context switch on each CPU.
3444          */
3445         while (try_stop_cpus(cma ? cm : cpu_online_mask,
3446                              synchronize_sched_expedited_cpu_stop,
3447                              NULL) == -EAGAIN) {
3448                 put_online_cpus();
3449                 atomic_long_inc(&rsp->expedited_tryfail);
3450
3451                 /* Check to see if someone else did our work for us. */
3452                 s = atomic_long_read(&rsp->expedited_done);
3453                 if (ULONG_CMP_GE((ulong)s, (ulong)firstsnap)) {
3454                         /* ensure test happens before caller kfree */
3455                         smp_mb__before_atomic(); /* ^^^ */
3456                         atomic_long_inc(&rsp->expedited_workdone1);
3457                         free_cpumask_var(cm);
3458                         return;
3459                 }
3460
3461                 /* No joy, try again later.  Or just synchronize_sched(). */
3462                 if (trycount++ < 10) {
3463                         udelay(trycount * num_online_cpus());
3464                 } else {
3465                         wait_rcu_gp(call_rcu_sched);
3466                         atomic_long_inc(&rsp->expedited_normal);
3467                         free_cpumask_var(cm);
3468                         return;
3469                 }
3470
3471                 /* Recheck to see if someone else did our work for us. */
3472                 s = atomic_long_read(&rsp->expedited_done);
3473                 if (ULONG_CMP_GE((ulong)s, (ulong)firstsnap)) {
3474                         /* ensure test happens before caller kfree */
3475                         smp_mb__before_atomic(); /* ^^^ */
3476                         atomic_long_inc(&rsp->expedited_workdone2);
3477                         free_cpumask_var(cm);
3478                         return;
3479                 }
3480
3481                 /*
3482                  * Refetching sync_sched_expedited_started allows later
3483                  * callers to piggyback on our grace period.  We retry
3484                  * after they started, so our grace period works for them,
3485                  * and they started after our first try, so their grace
3486                  * period works for us.
3487                  */
3488                 if (!try_get_online_cpus()) {
3489                         /* CPU hotplug operation in flight, use normal GP. */
3490                         wait_rcu_gp(call_rcu_sched);
3491                         atomic_long_inc(&rsp->expedited_normal);
3492                         free_cpumask_var(cm);
3493                         return;
3494                 }
3495                 snap = atomic_long_read(&rsp->expedited_start);
3496                 smp_mb(); /* ensure read is before try_stop_cpus(). */
3497         }
3498         atomic_long_inc(&rsp->expedited_stoppedcpus);
3499
3500 all_cpus_idle:
3501         free_cpumask_var(cm);
3502
3503         /*
3504          * Everyone up to our most recent fetch is covered by our grace
3505          * period.  Update the counter, but only if our work is still
3506          * relevant -- which it won't be if someone who started later
3507          * than we did already did their update.
3508          */
3509         do {
3510                 atomic_long_inc(&rsp->expedited_done_tries);
3511                 s = atomic_long_read(&rsp->expedited_done);
3512                 if (ULONG_CMP_GE((ulong)s, (ulong)snap)) {
3513                         /* ensure test happens before caller kfree */
3514                         smp_mb__before_atomic(); /* ^^^ */
3515                         atomic_long_inc(&rsp->expedited_done_lost);
3516                         break;
3517                 }
3518         } while (atomic_long_cmpxchg(&rsp->expedited_done, s, snap) != s);
3519         atomic_long_inc(&rsp->expedited_done_exit);
3520
3521         put_online_cpus();
3522 }
3523 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
3524
3525 /*
3526  * Check to see if there is any immediate RCU-related work to be done
3527  * by the current CPU, for the specified type of RCU, returning 1 if so.
3528  * The checks are in order of increasing expense: checks that can be
3529  * carried out against CPU-local state are performed first.  However,
3530  * we must check for CPU stalls first, else we might not get a chance.
3531  */
3532 static int __rcu_pending(struct rcu_state *rsp, struct rcu_data *rdp)
3533 {
3534         struct rcu_node *rnp = rdp->mynode;
3535
3536         rdp->n_rcu_pending++;
3537
3538         /* Check for CPU stalls, if enabled. */
3539         check_cpu_stall(rsp, rdp);
3540
3541         /* Is this CPU a NO_HZ_FULL CPU that should ignore RCU? */
3542         if (rcu_nohz_full_cpu(rsp))
3543                 return 0;
3544
3545         /* Is the RCU core waiting for a quiescent state from this CPU? */
3546         if (rcu_scheduler_fully_active &&
3547             rdp->qs_pending && !rdp->passed_quiesce &&
3548             rdp->rcu_qs_ctr_snap == __this_cpu_read(rcu_qs_ctr)) {
3549                 rdp->n_rp_qs_pending++;
3550         } else if (rdp->qs_pending &&
3551                    (rdp->passed_quiesce ||
3552                     rdp->rcu_qs_ctr_snap != __this_cpu_read(rcu_qs_ctr))) {
3553                 rdp->n_rp_report_qs++;
3554                 return 1;
3555         }
3556
3557         /* Does this CPU have callbacks ready to invoke? */
3558         if (cpu_has_callbacks_ready_to_invoke(rdp)) {
3559                 rdp->n_rp_cb_ready++;
3560                 return 1;
3561         }
3562
3563         /* Has RCU gone idle with this CPU needing another grace period? */
3564         if (cpu_needs_another_gp(rsp, rdp)) {
3565                 rdp->n_rp_cpu_needs_gp++;
3566                 return 1;
3567         }
3568
3569         /* Has another RCU grace period completed?  */
3570         if (ACCESS_ONCE(rnp->completed) != rdp->completed) { /* outside lock */
3571                 rdp->n_rp_gp_completed++;
3572                 return 1;
3573         }
3574
3575         /* Has a new RCU grace period started? */
3576         if (ACCESS_ONCE(rnp->gpnum) != rdp->gpnum ||
3577             unlikely(ACCESS_ONCE(rdp->gpwrap))) { /* outside lock */
3578                 rdp->n_rp_gp_started++;
3579                 return 1;
3580         }
3581
3582         /* Does this CPU need a deferred NOCB wakeup? */
3583         if (rcu_nocb_need_deferred_wakeup(rdp)) {
3584                 rdp->n_rp_nocb_defer_wakeup++;
3585                 return 1;
3586         }
3587
3588         /* nothing to do */
3589         rdp->n_rp_need_nothing++;
3590         return 0;
3591 }
3592
3593 /*
3594  * Check to see if there is any immediate RCU-related work to be done
3595  * by the current CPU, returning 1 if so.  This function is part of the
3596  * RCU implementation; it is -not- an exported member of the RCU API.
3597  */
3598 static int rcu_pending(void)
3599 {
3600         struct rcu_state *rsp;
3601
3602         for_each_rcu_flavor(rsp)
3603                 if (__rcu_pending(rsp, this_cpu_ptr(rsp->rda)))
3604                         return 1;
3605         return 0;
3606 }
3607
3608 /*
3609  * Return true if the specified CPU has any callback.  If all_lazy is
3610  * non-NULL, store an indication of whether all callbacks are lazy.
3611  * (If there are no callbacks, all of them are deemed to be lazy.)
3612  */
3613 static int __maybe_unused rcu_cpu_has_callbacks(bool *all_lazy)
3614 {
3615         bool al = true;
3616         bool hc = false;
3617         struct rcu_data *rdp;
3618         struct rcu_state *rsp;
3619
3620         for_each_rcu_flavor(rsp) {
3621                 rdp = this_cpu_ptr(rsp->rda);
3622                 if (!rdp->nxtlist)
3623                         continue;
3624                 hc = true;
3625                 if (rdp->qlen != rdp->qlen_lazy || !all_lazy) {
3626                         al = false;
3627                         break;
3628                 }
3629         }
3630         if (all_lazy)
3631                 *all_lazy = al;
3632         return hc;
3633 }
3634
3635 /*
3636  * Helper function for _rcu_barrier() tracing.  If tracing is disabled,
3637  * the compiler is expected to optimize this away.
3638  */
3639 static void _rcu_barrier_trace(struct rcu_state *rsp, const char *s,
3640                                int cpu, unsigned long done)
3641 {
3642         trace_rcu_barrier(rsp->name, s, cpu,
3643                           atomic_read(&rsp->barrier_cpu_count), done);
3644 }
3645
3646 /*
3647  * RCU callback function for _rcu_barrier().  If we are last, wake
3648  * up the task executing _rcu_barrier().
3649  */
3650 static void rcu_barrier_callback(struct rcu_head *rhp)
3651 {
3652         struct rcu_data *rdp = container_of(rhp, struct rcu_data, barrier_head);
3653         struct rcu_state *rsp = rdp->rsp;
3654
3655         if (atomic_dec_and_test(&rsp->barrier_cpu_count)) {
3656                 _rcu_barrier_trace(rsp, "LastCB", -1, rsp->n_barrier_done);
3657                 complete(&rsp->barrier_completion);
3658         } else {
3659                 _rcu_barrier_trace(rsp, "CB", -1, rsp->n_barrier_done);
3660         }
3661 }
3662
3663 /*
3664  * Called with preemption disabled, and from cross-cpu IRQ context.
3665  */
3666 static void rcu_barrier_func(void *type)
3667 {
3668         struct rcu_state *rsp = type;
3669         struct rcu_data *rdp = raw_cpu_ptr(rsp->rda);
3670
3671         _rcu_barrier_trace(rsp, "IRQ", -1, rsp->n_barrier_done);
3672         atomic_inc(&rsp->barrier_cpu_count);
3673         rsp->call(&rdp->barrier_head, rcu_barrier_callback);
3674 }
3675
3676 /*
3677  * Orchestrate the specified type of RCU barrier, waiting for all
3678  * RCU callbacks of the specified type to complete.
3679  */
3680 static void _rcu_barrier(struct rcu_state *rsp)
3681 {
3682         int cpu;
3683         struct rcu_data *rdp;
3684         unsigned long snap = ACCESS_ONCE(rsp->n_barrier_done);
3685         unsigned long snap_done;
3686
3687         _rcu_barrier_trace(rsp, "Begin", -1, snap);
3688
3689         /* Take mutex to serialize concurrent rcu_barrier() requests. */
3690         mutex_lock(&rsp->barrier_mutex);
3691
3692         /*
3693          * Ensure that all prior references, including to ->n_barrier_done,
3694          * are ordered before the _rcu_barrier() machinery.
3695          */
3696         smp_mb();  /* See above block comment. */
3697
3698         /*
3699          * Recheck ->n_barrier_done to see if others did our work for us.
3700          * This means checking ->n_barrier_done for an even-to-odd-to-even
3701          * transition.  The "if" expression below therefore rounds the old
3702          * value up to the next even number and adds two before comparing.
3703          */
3704         snap_done = rsp->n_barrier_done;
3705         _rcu_barrier_trace(rsp, "Check", -1, snap_done);
3706
3707         /*
3708          * If the value in snap is odd, we needed to wait for the current
3709          * rcu_barrier() to complete, then wait for the next one, in other
3710          * words, we need the value of snap_done to be three larger than
3711          * the value of snap.  On the other hand, if the value in snap is
3712          * even, we only had to wait for the next rcu_barrier() to complete,
3713          * in other words, we need the value of snap_done to be only two
3714          * greater than the value of snap.  The "(snap + 3) & ~0x1" computes
3715          * this for us (thank you, Linus!).
3716          */
3717         if (ULONG_CMP_GE(snap_done, (snap + 3) & ~0x1)) {
3718                 _rcu_barrier_trace(rsp, "EarlyExit", -1, snap_done);
3719                 smp_mb(); /* caller's subsequent code after above check. */
3720                 mutex_unlock(&rsp->barrier_mutex);
3721                 return;
3722         }
3723
3724         /*
3725          * Increment ->n_barrier_done to avoid duplicate work.  Use
3726          * ACCESS_ONCE() to prevent the compiler from speculating
3727          * the increment to precede the early-exit check.
3728          */
3729         ACCESS_ONCE(rsp->n_barrier_done) = rsp->n_barrier_done + 1;
3730         WARN_ON_ONCE((rsp->n_barrier_done & 0x1) != 1);
3731         _rcu_barrier_trace(rsp, "Inc1", -1, rsp->n_barrier_done);
3732         smp_mb(); /* Order ->n_barrier_done increment with below mechanism. */
3733
3734         /*
3735          * Initialize the count to one rather than to zero in order to
3736          * avoid a too-soon return to zero in case of a short grace period
3737          * (or preemption of this task).  Exclude CPU-hotplug operations
3738          * to ensure that no offline CPU has callbacks queued.
3739          */
3740         init_completion(&rsp->barrier_completion);
3741         atomic_set(&rsp->barrier_cpu_count, 1);
3742         get_online_cpus();
3743
3744         /*
3745          * Force each CPU with callbacks to register a new callback.
3746          * When that callback is invoked, we will know that all of the
3747          * corresponding CPU's preceding callbacks have been invoked.
3748          */
3749         for_each_possible_cpu(cpu) {
3750                 if (!cpu_online(cpu) && !rcu_is_nocb_cpu(cpu))
3751                         continue;
3752                 rdp = per_cpu_ptr(rsp->rda, cpu);
3753                 if (rcu_is_nocb_cpu(cpu)) {
3754                         if (!rcu_nocb_cpu_needs_barrier(rsp, cpu)) {
3755                                 _rcu_barrier_trace(rsp, "OfflineNoCB", cpu,
3756                                                    rsp->n_barrier_done);
3757                         } else {
3758                                 _rcu_barrier_trace(rsp, "OnlineNoCB", cpu,
3759                                                    rsp->n_barrier_done);
3760                                 smp_mb__before_atomic();
3761                                 atomic_inc(&rsp->barrier_cpu_count);
3762                                 __call_rcu(&rdp->barrier_head,
3763                                            rcu_barrier_callback, rsp, cpu, 0);
3764                         }
3765                 } else if (ACCESS_ONCE(rdp->qlen)) {
3766                         _rcu_barrier_trace(rsp, "OnlineQ", cpu,
3767                                            rsp->n_barrier_done);
3768                         smp_call_function_single(cpu, rcu_barrier_func, rsp, 1);
3769                 } else {
3770                         _rcu_barrier_trace(rsp, "OnlineNQ", cpu,
3771                                            rsp->n_barrier_done);
3772                 }
3773         }
3774         put_online_cpus();
3775
3776         /*
3777          * Now that we have an rcu_barrier_callback() callback on each
3778          * CPU, and thus each counted, remove the initial count.
3779          */
3780         if (atomic_dec_and_test(&rsp->barrier_cpu_count))
3781                 complete(&rsp->barrier_completion);
3782
3783         /* Increment ->n_barrier_done to prevent duplicate work. */
3784         smp_mb(); /* Keep increment after above mechanism. */
3785         ACCESS_ONCE(rsp->n_barrier_done) = rsp->n_barrier_done + 1;
3786         WARN_ON_ONCE((rsp->n_barrier_done & 0x1) != 0);
3787         _rcu_barrier_trace(rsp, "Inc2", -1, rsp->n_barrier_done);
3788         smp_mb(); /* Keep increment before caller's subsequent code. */
3789
3790         /* Wait for all rcu_barrier_callback() callbacks to be invoked. */
3791         wait_for_completion(&rsp->barrier_completion);
3792
3793         /* Other rcu_barrier() invocations can now safely proceed. */
3794         mutex_unlock(&rsp->barrier_mutex);
3795 }
3796
3797 #ifndef CONFIG_PREEMPT_RT_FULL
3798 /**
3799  * rcu_barrier_bh - Wait until all in-flight call_rcu_bh() callbacks complete.
3800  */
3801 void rcu_barrier_bh(void)
3802 {
3803         _rcu_barrier(&rcu_bh_state);
3804 }
3805 EXPORT_SYMBOL_GPL(rcu_barrier_bh);
3806 #endif
3807
3808 /**
3809  * rcu_barrier_sched - Wait for in-flight call_rcu_sched() callbacks.
3810  */
3811 void rcu_barrier_sched(void)
3812 {
3813         _rcu_barrier(&rcu_sched_state);
3814 }
3815 EXPORT_SYMBOL_GPL(rcu_barrier_sched);
3816
3817 /*
3818  * Propagate ->qsinitmask bits up the rcu_node tree to account for the
3819  * first CPU in a given leaf rcu_node structure coming online.  The caller
3820  * must hold the corresponding leaf rcu_node ->lock with interrrupts
3821  * disabled.
3822  */
3823 static void rcu_init_new_rnp(struct rcu_node *rnp_leaf)
3824 {
3825         long mask;
3826         struct rcu_node *rnp = rnp_leaf;
3827
3828         for (;;) {
3829                 mask = rnp->grpmask;
3830                 rnp = rnp->parent;
3831                 if (rnp == NULL)
3832                         return;
3833                 raw_spin_lock(&rnp->lock); /* Interrupts already disabled. */
3834                 rnp->qsmaskinit |= mask;
3835                 raw_spin_unlock(&rnp->lock); /* Interrupts remain disabled. */
3836         }
3837 }
3838
3839 /*
3840  * Do boot-time initialization of a CPU's per-CPU RCU data.
3841  */
3842 static void __init
3843 rcu_boot_init_percpu_data(int cpu, struct rcu_state *rsp)
3844 {
3845         unsigned long flags;
3846         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
3847         struct rcu_node *rnp = rcu_get_root(rsp);
3848
3849         /* Set up local state, ensuring consistent view of global state. */
3850         raw_spin_lock_irqsave(&rnp->lock, flags);
3851         rdp->grpmask = 1UL << (cpu - rdp->mynode->grplo);
3852         rdp->dynticks = &per_cpu(rcu_dynticks, cpu);
3853         WARN_ON_ONCE(rdp->dynticks->dynticks_nesting != DYNTICK_TASK_EXIT_IDLE);
3854         WARN_ON_ONCE(atomic_read(&rdp->dynticks->dynticks) != 1);
3855         rdp->cpu = cpu;
3856         rdp->rsp = rsp;
3857         rcu_boot_init_nocb_percpu_data(rdp);
3858         raw_spin_unlock_irqrestore(&rnp->lock, flags);
3859 }
3860
3861 /*
3862  * Initialize a CPU's per-CPU RCU data.  Note that only one online or
3863  * offline event can be happening at a given time.  Note also that we
3864  * can accept some slop in the rsp->completed access due to the fact
3865  * that this CPU cannot possibly have any RCU callbacks in flight yet.
3866  */
3867 static void
3868 rcu_init_percpu_data(int cpu, struct rcu_state *rsp)
3869 {
3870         unsigned long flags;
3871         unsigned long mask;
3872         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
3873         struct rcu_node *rnp = rcu_get_root(rsp);
3874
3875         /* Set up local state, ensuring consistent view of global state. */
3876         raw_spin_lock_irqsave(&rnp->lock, flags);
3877         rdp->beenonline = 1;     /* We have now been online. */
3878         rdp->qlen_last_fqs_check = 0;
3879         rdp->n_force_qs_snap = rsp->n_force_qs;
3880         rdp->blimit = blimit;
3881         if (!rdp->nxtlist)
3882                 init_callback_list(rdp);  /* Re-enable callbacks on this CPU. */
3883         rdp->dynticks->dynticks_nesting = DYNTICK_TASK_EXIT_IDLE;
3884         rcu_sysidle_init_percpu_data(rdp->dynticks);
3885         atomic_set(&rdp->dynticks->dynticks,
3886                    (atomic_read(&rdp->dynticks->dynticks) & ~0x1) + 1);
3887         raw_spin_unlock(&rnp->lock);            /* irqs remain disabled. */
3888
3889         /*
3890          * Add CPU to leaf rcu_node pending-online bitmask.  Any needed
3891          * propagation up the rcu_node tree will happen at the beginning
3892          * of the next grace period.
3893          */
3894         rnp = rdp->mynode;
3895         mask = rdp->grpmask;
3896         raw_spin_lock(&rnp->lock);              /* irqs already disabled. */
3897         smp_mb__after_unlock_lock();
3898         rnp->qsmaskinitnext |= mask;
3899         rdp->gpnum = rnp->completed; /* Make CPU later note any new GP. */
3900         rdp->completed = rnp->completed;
3901         rdp->passed_quiesce = false;
3902         rdp->rcu_qs_ctr_snap = __this_cpu_read(rcu_qs_ctr);
3903         rdp->qs_pending = false;
3904         trace_rcu_grace_period(rsp->name, rdp->gpnum, TPS("cpuonl"));
3905         raw_spin_unlock_irqrestore(&rnp->lock, flags);
3906 }
3907
3908 static void rcu_prepare_cpu(int cpu)
3909 {
3910         struct rcu_state *rsp;
3911
3912         for_each_rcu_flavor(rsp)
3913                 rcu_init_percpu_data(cpu, rsp);
3914 }
3915
3916 /*
3917  * Handle CPU online/offline notification events.
3918  */
3919 int rcu_cpu_notify(struct notifier_block *self,
3920                    unsigned long action, void *hcpu)
3921 {
3922         long cpu = (long)hcpu;
3923         struct rcu_data *rdp = per_cpu_ptr(rcu_state_p->rda, cpu);
3924         struct rcu_node *rnp = rdp->mynode;
3925         struct rcu_state *rsp;
3926
3927         switch (action) {
3928         case CPU_UP_PREPARE:
3929         case CPU_UP_PREPARE_FROZEN:
3930                 rcu_prepare_cpu(cpu);
3931                 rcu_prepare_kthreads(cpu);
3932                 rcu_spawn_all_nocb_kthreads(cpu);
3933                 break;
3934         case CPU_ONLINE:
3935         case CPU_DOWN_FAILED:
3936                 rcu_boost_kthread_setaffinity(rnp, -1);
3937                 break;
3938         case CPU_DOWN_PREPARE:
3939                 rcu_boost_kthread_setaffinity(rnp, cpu);
3940                 break;
3941         case CPU_DYING:
3942         case CPU_DYING_FROZEN:
3943                 for_each_rcu_flavor(rsp)
3944                         rcu_cleanup_dying_cpu(rsp);
3945                 break;
3946         case CPU_DYING_IDLE:
3947                 for_each_rcu_flavor(rsp) {
3948                         rcu_cleanup_dying_idle_cpu(cpu, rsp);
3949                 }
3950                 break;
3951         case CPU_DEAD:
3952         case CPU_DEAD_FROZEN:
3953         case CPU_UP_CANCELED:
3954         case CPU_UP_CANCELED_FROZEN:
3955                 for_each_rcu_flavor(rsp) {
3956                         rcu_cleanup_dead_cpu(cpu, rsp);
3957                         do_nocb_deferred_wakeup(per_cpu_ptr(rsp->rda, cpu));
3958                 }
3959                 break;
3960         default:
3961                 break;
3962         }
3963         return NOTIFY_OK;
3964 }
3965
3966 static int rcu_pm_notify(struct notifier_block *self,
3967                          unsigned long action, void *hcpu)
3968 {
3969         switch (action) {
3970         case PM_HIBERNATION_PREPARE:
3971         case PM_SUSPEND_PREPARE:
3972                 if (nr_cpu_ids <= 256) /* Expediting bad for large systems. */
3973                         rcu_expedite_gp();
3974                 break;
3975         case PM_POST_HIBERNATION:
3976         case PM_POST_SUSPEND:
3977                 if (nr_cpu_ids <= 256) /* Expediting bad for large systems. */
3978                         rcu_unexpedite_gp();
3979                 break;
3980         default:
3981                 break;
3982         }
3983         return NOTIFY_OK;
3984 }
3985
3986 /*
3987  * Spawn the kthreads that handle each RCU flavor's grace periods.
3988  */
3989 static int __init rcu_spawn_gp_kthread(void)
3990 {
3991         unsigned long flags;
3992         int kthread_prio_in = kthread_prio;
3993         struct rcu_node *rnp;
3994         struct rcu_state *rsp;
3995         struct sched_param sp;
3996         struct task_struct *t;
3997
3998         /* Force priority into range. */
3999         if (IS_ENABLED(CONFIG_RCU_BOOST) && kthread_prio < 1)
4000                 kthread_prio = 1;
4001         else if (kthread_prio < 0)
4002                 kthread_prio = 0;
4003         else if (kthread_prio > 99)
4004                 kthread_prio = 99;
4005         if (kthread_prio != kthread_prio_in)
4006                 pr_alert("rcu_spawn_gp_kthread(): Limited prio to %d from %d\n",
4007                          kthread_prio, kthread_prio_in);
4008
4009         rcu_scheduler_fully_active = 1;
4010         for_each_rcu_flavor(rsp) {
4011                 t = kthread_create(rcu_gp_kthread, rsp, "%s", rsp->name);
4012                 BUG_ON(IS_ERR(t));
4013                 rnp = rcu_get_root(rsp);
4014                 raw_spin_lock_irqsave(&rnp->lock, flags);
4015                 rsp->gp_kthread = t;
4016                 if (kthread_prio) {
4017                         sp.sched_priority = kthread_prio;
4018                         sched_setscheduler_nocheck(t, SCHED_FIFO, &sp);
4019                 }
4020                 wake_up_process(t);
4021                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
4022         }
4023         rcu_spawn_nocb_kthreads();
4024         rcu_spawn_boost_kthreads();
4025         return 0;
4026 }
4027 early_initcall(rcu_spawn_gp_kthread);
4028
4029 /*
4030  * This function is invoked towards the end of the scheduler's initialization
4031  * process.  Before this is called, the idle task might contain
4032  * RCU read-side critical sections (during which time, this idle
4033  * task is booting the system).  After this function is called, the
4034  * idle tasks are prohibited from containing RCU read-side critical
4035  * sections.  This function also enables RCU lockdep checking.
4036  */
4037 void rcu_scheduler_starting(void)
4038 {
4039         WARN_ON(num_online_cpus() != 1);
4040         WARN_ON(nr_context_switches() > 0);
4041         rcu_scheduler_active = 1;
4042 }
4043
4044 /*
4045  * Compute the per-level fanout, either using the exact fanout specified
4046  * or balancing the tree, depending on CONFIG_RCU_FANOUT_EXACT.
4047  */
4048 static void __init rcu_init_levelspread(struct rcu_state *rsp)
4049 {
4050         int i;
4051
4052         if (IS_ENABLED(CONFIG_RCU_FANOUT_EXACT)) {
4053                 rsp->levelspread[rcu_num_lvls - 1] = rcu_fanout_leaf;
4054                 for (i = rcu_num_lvls - 2; i >= 0; i--)
4055                         rsp->levelspread[i] = CONFIG_RCU_FANOUT;
4056         } else {
4057                 int ccur;
4058                 int cprv;
4059
4060                 cprv = nr_cpu_ids;
4061                 for (i = rcu_num_lvls - 1; i >= 0; i--) {
4062                         ccur = rsp->levelcnt[i];
4063                         rsp->levelspread[i] = (cprv + ccur - 1) / ccur;
4064                         cprv = ccur;
4065                 }
4066         }
4067 }
4068
4069 /*
4070  * Helper function for rcu_init() that initializes one rcu_state structure.
4071  */
4072 static void __init rcu_init_one(struct rcu_state *rsp,
4073                 struct rcu_data __percpu *rda)
4074 {
4075         static const char * const buf[] = {
4076                 "rcu_node_0",
4077                 "rcu_node_1",
4078                 "rcu_node_2",
4079                 "rcu_node_3" };  /* Match MAX_RCU_LVLS */
4080         static const char * const fqs[] = {
4081                 "rcu_node_fqs_0",
4082                 "rcu_node_fqs_1",
4083                 "rcu_node_fqs_2",
4084                 "rcu_node_fqs_3" };  /* Match MAX_RCU_LVLS */
4085         static u8 fl_mask = 0x1;
4086         int cpustride = 1;
4087         int i;
4088         int j;
4089         struct rcu_node *rnp;
4090
4091         BUILD_BUG_ON(MAX_RCU_LVLS > ARRAY_SIZE(buf));  /* Fix buf[] init! */
4092
4093         /* Silence gcc 4.8 warning about array index out of range. */
4094         if (rcu_num_lvls > RCU_NUM_LVLS)
4095                 panic("rcu_init_one: rcu_num_lvls overflow");
4096
4097         /* Initialize the level-tracking arrays. */
4098
4099         for (i = 0; i < rcu_num_lvls; i++)
4100                 rsp->levelcnt[i] = num_rcu_lvl[i];
4101         for (i = 1; i < rcu_num_lvls; i++)
4102                 rsp->level[i] = rsp->level[i - 1] + rsp->levelcnt[i - 1];
4103         rcu_init_levelspread(rsp);
4104         rsp->flavor_mask = fl_mask;
4105         fl_mask <<= 1;
4106
4107         /* Initialize the elements themselves, starting from the leaves. */
4108
4109         for (i = rcu_num_lvls - 1; i >= 0; i--) {
4110                 cpustride *= rsp->levelspread[i];
4111                 rnp = rsp->level[i];
4112                 for (j = 0; j < rsp->levelcnt[i]; j++, rnp++) {
4113                         raw_spin_lock_init(&rnp->lock);
4114                         lockdep_set_class_and_name(&rnp->lock,
4115                                                    &rcu_node_class[i], buf[i]);
4116                         raw_spin_lock_init(&rnp->fqslock);
4117                         lockdep_set_class_and_name(&rnp->fqslock,
4118                                                    &rcu_fqs_class[i], fqs[i]);
4119                         rnp->gpnum = rsp->gpnum;
4120                         rnp->completed = rsp->completed;
4121                         rnp->qsmask = 0;
4122                         rnp->qsmaskinit = 0;
4123                         rnp->grplo = j * cpustride;
4124                         rnp->grphi = (j + 1) * cpustride - 1;
4125                         if (rnp->grphi >= nr_cpu_ids)
4126                                 rnp->grphi = nr_cpu_ids - 1;
4127                         if (i == 0) {
4128                                 rnp->grpnum = 0;
4129                                 rnp->grpmask = 0;
4130                                 rnp->parent = NULL;
4131                         } else {
4132                                 rnp->grpnum = j % rsp->levelspread[i - 1];
4133                                 rnp->grpmask = 1UL << rnp->grpnum;
4134                                 rnp->parent = rsp->level[i - 1] +
4135                                               j / rsp->levelspread[i - 1];
4136                         }
4137                         rnp->level = i;
4138                         INIT_LIST_HEAD(&rnp->blkd_tasks);
4139                         rcu_init_one_nocb(rnp);
4140                 }
4141         }
4142
4143         init_swait_head(&rsp->gp_wq);
4144         rnp = rsp->level[rcu_num_lvls - 1];
4145         for_each_possible_cpu(i) {
4146                 while (i > rnp->grphi)
4147                         rnp++;
4148                 per_cpu_ptr(rsp->rda, i)->mynode = rnp;
4149                 rcu_boot_init_percpu_data(i, rsp);
4150         }
4151         list_add(&rsp->flavors, &rcu_struct_flavors);
4152 }
4153
4154 /*
4155  * Compute the rcu_node tree geometry from kernel parameters.  This cannot
4156  * replace the definitions in tree.h because those are needed to size
4157  * the ->node array in the rcu_state structure.
4158  */
4159 static void __init rcu_init_geometry(void)
4160 {
4161         ulong d;
4162         int i;
4163         int j;
4164         int n = nr_cpu_ids;
4165         int rcu_capacity[MAX_RCU_LVLS + 1];
4166
4167         /*
4168          * Initialize any unspecified boot parameters.
4169          * The default values of jiffies_till_first_fqs and
4170          * jiffies_till_next_fqs are set to the RCU_JIFFIES_TILL_FORCE_QS
4171          * value, which is a function of HZ, then adding one for each
4172          * RCU_JIFFIES_FQS_DIV CPUs that might be on the system.
4173          */
4174         d = RCU_JIFFIES_TILL_FORCE_QS + nr_cpu_ids / RCU_JIFFIES_FQS_DIV;
4175         if (jiffies_till_first_fqs == ULONG_MAX)
4176                 jiffies_till_first_fqs = d;
4177         if (jiffies_till_next_fqs == ULONG_MAX)
4178                 jiffies_till_next_fqs = d;
4179
4180         /* If the compile-time values are accurate, just leave. */
4181         if (rcu_fanout_leaf == CONFIG_RCU_FANOUT_LEAF &&
4182             nr_cpu_ids == NR_CPUS)
4183                 return;
4184         pr_info("RCU: Adjusting geometry for rcu_fanout_leaf=%d, nr_cpu_ids=%d\n",
4185                 rcu_fanout_leaf, nr_cpu_ids);
4186
4187         /*
4188          * Compute number of nodes that can be handled an rcu_node tree
4189          * with the given number of levels.  Setting rcu_capacity[0] makes
4190          * some of the arithmetic easier.
4191          */
4192         rcu_capacity[0] = 1;
4193         rcu_capacity[1] = rcu_fanout_leaf;
4194         for (i = 2; i <= MAX_RCU_LVLS; i++)
4195                 rcu_capacity[i] = rcu_capacity[i - 1] * CONFIG_RCU_FANOUT;
4196
4197         /*
4198          * The boot-time rcu_fanout_leaf parameter is only permitted
4199          * to increase the leaf-level fanout, not decrease it.  Of course,
4200          * the leaf-level fanout cannot exceed the number of bits in
4201          * the rcu_node masks.  Finally, the tree must be able to accommodate
4202          * the configured number of CPUs.  Complain and fall back to the
4203          * compile-time values if these limits are exceeded.
4204          */
4205         if (rcu_fanout_leaf < CONFIG_RCU_FANOUT_LEAF ||
4206             rcu_fanout_leaf > sizeof(unsigned long) * 8 ||
4207             n > rcu_capacity[MAX_RCU_LVLS]) {
4208                 WARN_ON(1);
4209                 return;
4210         }
4211
4212         /* Calculate the number of rcu_nodes at each level of the tree. */
4213         for (i = 1; i <= MAX_RCU_LVLS; i++)
4214                 if (n <= rcu_capacity[i]) {
4215                         for (j = 0; j <= i; j++)
4216                                 num_rcu_lvl[j] =
4217                                         DIV_ROUND_UP(n, rcu_capacity[i - j]);
4218                         rcu_num_lvls = i;
4219                         for (j = i + 1; j <= MAX_RCU_LVLS; j++)
4220                                 num_rcu_lvl[j] = 0;
4221                         break;
4222                 }
4223
4224         /* Calculate the total number of rcu_node structures. */
4225         rcu_num_nodes = 0;
4226         for (i = 0; i <= MAX_RCU_LVLS; i++)
4227                 rcu_num_nodes += num_rcu_lvl[i];
4228         rcu_num_nodes -= n;
4229 }
4230
4231 void __init rcu_init(void)
4232 {
4233         int cpu;
4234
4235         rcu_early_boot_tests();
4236
4237         rcu_bootup_announce();
4238         rcu_init_geometry();
4239         rcu_init_one(&rcu_bh_state, &rcu_bh_data);
4240         rcu_init_one(&rcu_sched_state, &rcu_sched_data);
4241         __rcu_init_preempt();
4242
4243         /*
4244          * We don't need protection against CPU-hotplug here because
4245          * this is called early in boot, before either interrupts
4246          * or the scheduler are operational.
4247          */
4248         cpu_notifier(rcu_cpu_notify, 0);
4249         pm_notifier(rcu_pm_notify, 0);
4250         for_each_online_cpu(cpu)
4251                 rcu_cpu_notify(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
4252 }
4253
4254 #include "tree_plugin.h"