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