Merge remote-tracking branch 'tip/core/rcu' into next.2012.09.25b
[firefly-linux-kernel-4.4.55.git] / kernel / rcutree.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, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
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/percpu.h>
45 #include <linux/notifier.h>
46 #include <linux/cpu.h>
47 #include <linux/mutex.h>
48 #include <linux/time.h>
49 #include <linux/kernel_stat.h>
50 #include <linux/wait.h>
51 #include <linux/kthread.h>
52 #include <linux/prefetch.h>
53 #include <linux/delay.h>
54 #include <linux/stop_machine.h>
55 #include <linux/random.h>
56
57 #include "rcutree.h"
58 #include <trace/events/rcu.h>
59
60 #include "rcu.h"
61
62 /* Data structures. */
63
64 static struct lock_class_key rcu_node_class[RCU_NUM_LVLS];
65 static struct lock_class_key rcu_fqs_class[RCU_NUM_LVLS];
66
67 #define RCU_STATE_INITIALIZER(sname, cr) { \
68         .level = { &sname##_state.node[0] }, \
69         .call = cr, \
70         .fqs_state = RCU_GP_IDLE, \
71         .gpnum = -300, \
72         .completed = -300, \
73         .onofflock = __RAW_SPIN_LOCK_UNLOCKED(&sname##_state.onofflock), \
74         .orphan_nxttail = &sname##_state.orphan_nxtlist, \
75         .orphan_donetail = &sname##_state.orphan_donelist, \
76         .barrier_mutex = __MUTEX_INITIALIZER(sname##_state.barrier_mutex), \
77         .name = #sname, \
78 }
79
80 struct rcu_state rcu_sched_state =
81         RCU_STATE_INITIALIZER(rcu_sched, call_rcu_sched);
82 DEFINE_PER_CPU(struct rcu_data, rcu_sched_data);
83
84 struct rcu_state rcu_bh_state = RCU_STATE_INITIALIZER(rcu_bh, call_rcu_bh);
85 DEFINE_PER_CPU(struct rcu_data, rcu_bh_data);
86
87 static struct rcu_state *rcu_state;
88 LIST_HEAD(rcu_struct_flavors);
89
90 /* Increase (but not decrease) the CONFIG_RCU_FANOUT_LEAF at boot time. */
91 static int rcu_fanout_leaf = CONFIG_RCU_FANOUT_LEAF;
92 module_param(rcu_fanout_leaf, int, 0444);
93 int rcu_num_lvls __read_mostly = RCU_NUM_LVLS;
94 static int num_rcu_lvl[] = {  /* Number of rcu_nodes at specified level. */
95         NUM_RCU_LVL_0,
96         NUM_RCU_LVL_1,
97         NUM_RCU_LVL_2,
98         NUM_RCU_LVL_3,
99         NUM_RCU_LVL_4,
100 };
101 int rcu_num_nodes __read_mostly = NUM_RCU_NODES; /* Total # rcu_nodes in use. */
102
103 /*
104  * The rcu_scheduler_active variable transitions from zero to one just
105  * before the first task is spawned.  So when this variable is zero, RCU
106  * can assume that there is but one task, allowing RCU to (for example)
107  * optimized synchronize_sched() to a simple barrier().  When this variable
108  * is one, RCU must actually do all the hard work required to detect real
109  * grace periods.  This variable is also used to suppress boot-time false
110  * positives from lockdep-RCU error checking.
111  */
112 int rcu_scheduler_active __read_mostly;
113 EXPORT_SYMBOL_GPL(rcu_scheduler_active);
114
115 /*
116  * The rcu_scheduler_fully_active variable transitions from zero to one
117  * during the early_initcall() processing, which is after the scheduler
118  * is capable of creating new tasks.  So RCU processing (for example,
119  * creating tasks for RCU priority boosting) must be delayed until after
120  * rcu_scheduler_fully_active transitions from zero to one.  We also
121  * currently delay invocation of any RCU callbacks until after this point.
122  *
123  * It might later prove better for people registering RCU callbacks during
124  * early boot to take responsibility for these callbacks, but one step at
125  * a time.
126  */
127 static int rcu_scheduler_fully_active __read_mostly;
128
129 #ifdef CONFIG_RCU_BOOST
130
131 /*
132  * Control variables for per-CPU and per-rcu_node kthreads.  These
133  * handle all flavors of RCU.
134  */
135 static DEFINE_PER_CPU(struct task_struct *, rcu_cpu_kthread_task);
136 DEFINE_PER_CPU(unsigned int, rcu_cpu_kthread_status);
137 DEFINE_PER_CPU(unsigned int, rcu_cpu_kthread_loops);
138 DEFINE_PER_CPU(char, rcu_cpu_has_work);
139
140 #endif /* #ifdef CONFIG_RCU_BOOST */
141
142 static void rcu_boost_kthread_setaffinity(struct rcu_node *rnp, int outgoingcpu);
143 static void invoke_rcu_core(void);
144 static void invoke_rcu_callbacks(struct rcu_state *rsp, struct rcu_data *rdp);
145
146 /*
147  * Track the rcutorture test sequence number and the update version
148  * number within a given test.  The rcutorture_testseq is incremented
149  * on every rcutorture module load and unload, so has an odd value
150  * when a test is running.  The rcutorture_vernum is set to zero
151  * when rcutorture starts and is incremented on each rcutorture update.
152  * These variables enable correlating rcutorture output with the
153  * RCU tracing information.
154  */
155 unsigned long rcutorture_testseq;
156 unsigned long rcutorture_vernum;
157
158 /*
159  * Return true if an RCU grace period is in progress.  The ACCESS_ONCE()s
160  * permit this function to be invoked without holding the root rcu_node
161  * structure's ->lock, but of course results can be subject to change.
162  */
163 static int rcu_gp_in_progress(struct rcu_state *rsp)
164 {
165         return ACCESS_ONCE(rsp->completed) != ACCESS_ONCE(rsp->gpnum);
166 }
167
168 /*
169  * Note a quiescent state.  Because we do not need to know
170  * how many quiescent states passed, just if there was at least
171  * one since the start of the grace period, this just sets a flag.
172  * The caller must have disabled preemption.
173  */
174 void rcu_sched_qs(int cpu)
175 {
176         struct rcu_data *rdp = &per_cpu(rcu_sched_data, cpu);
177
178         if (rdp->passed_quiesce == 0)
179                 trace_rcu_grace_period("rcu_sched", rdp->gpnum, "cpuqs");
180         rdp->passed_quiesce = 1;
181 }
182
183 void rcu_bh_qs(int cpu)
184 {
185         struct rcu_data *rdp = &per_cpu(rcu_bh_data, cpu);
186
187         if (rdp->passed_quiesce == 0)
188                 trace_rcu_grace_period("rcu_bh", rdp->gpnum, "cpuqs");
189         rdp->passed_quiesce = 1;
190 }
191
192 /*
193  * Note a context switch.  This is a quiescent state for RCU-sched,
194  * and requires special handling for preemptible RCU.
195  * The caller must have disabled preemption.
196  */
197 void rcu_note_context_switch(int cpu)
198 {
199         trace_rcu_utilization("Start context switch");
200         rcu_sched_qs(cpu);
201         rcu_preempt_note_context_switch(cpu);
202         trace_rcu_utilization("End context switch");
203 }
204 EXPORT_SYMBOL_GPL(rcu_note_context_switch);
205
206 DEFINE_PER_CPU(struct rcu_dynticks, rcu_dynticks) = {
207         .dynticks_nesting = DYNTICK_TASK_EXIT_IDLE,
208         .dynticks = ATOMIC_INIT(1),
209 };
210
211 static int blimit = 10;         /* Maximum callbacks per rcu_do_batch. */
212 static int qhimark = 10000;     /* If this many pending, ignore blimit. */
213 static int qlowmark = 100;      /* Once only this many pending, use blimit. */
214
215 module_param(blimit, int, 0444);
216 module_param(qhimark, int, 0444);
217 module_param(qlowmark, int, 0444);
218
219 int rcu_cpu_stall_suppress __read_mostly; /* 1 = suppress stall warnings. */
220 int rcu_cpu_stall_timeout __read_mostly = CONFIG_RCU_CPU_STALL_TIMEOUT;
221
222 module_param(rcu_cpu_stall_suppress, int, 0644);
223 module_param(rcu_cpu_stall_timeout, int, 0644);
224
225 static ulong jiffies_till_first_fqs = RCU_JIFFIES_TILL_FORCE_QS;
226 static ulong jiffies_till_next_fqs = RCU_JIFFIES_TILL_FORCE_QS;
227
228 module_param(jiffies_till_first_fqs, ulong, 0644);
229 module_param(jiffies_till_next_fqs, ulong, 0644);
230
231 static void force_qs_rnp(struct rcu_state *rsp, int (*f)(struct rcu_data *));
232 static void force_quiescent_state(struct rcu_state *rsp);
233 static int rcu_pending(int cpu);
234
235 /*
236  * Return the number of RCU-sched batches processed thus far for debug & stats.
237  */
238 long rcu_batches_completed_sched(void)
239 {
240         return rcu_sched_state.completed;
241 }
242 EXPORT_SYMBOL_GPL(rcu_batches_completed_sched);
243
244 /*
245  * Return the number of RCU BH batches processed thus far for debug & stats.
246  */
247 long rcu_batches_completed_bh(void)
248 {
249         return rcu_bh_state.completed;
250 }
251 EXPORT_SYMBOL_GPL(rcu_batches_completed_bh);
252
253 /*
254  * Force a quiescent state for RCU BH.
255  */
256 void rcu_bh_force_quiescent_state(void)
257 {
258         force_quiescent_state(&rcu_bh_state);
259 }
260 EXPORT_SYMBOL_GPL(rcu_bh_force_quiescent_state);
261
262 /*
263  * Record the number of times rcutorture tests have been initiated and
264  * terminated.  This information allows the debugfs tracing stats to be
265  * correlated to the rcutorture messages, even when the rcutorture module
266  * is being repeatedly loaded and unloaded.  In other words, we cannot
267  * store this state in rcutorture itself.
268  */
269 void rcutorture_record_test_transition(void)
270 {
271         rcutorture_testseq++;
272         rcutorture_vernum = 0;
273 }
274 EXPORT_SYMBOL_GPL(rcutorture_record_test_transition);
275
276 /*
277  * Record the number of writer passes through the current rcutorture test.
278  * This is also used to correlate debugfs tracing stats with the rcutorture
279  * messages.
280  */
281 void rcutorture_record_progress(unsigned long vernum)
282 {
283         rcutorture_vernum++;
284 }
285 EXPORT_SYMBOL_GPL(rcutorture_record_progress);
286
287 /*
288  * Force a quiescent state for RCU-sched.
289  */
290 void rcu_sched_force_quiescent_state(void)
291 {
292         force_quiescent_state(&rcu_sched_state);
293 }
294 EXPORT_SYMBOL_GPL(rcu_sched_force_quiescent_state);
295
296 /*
297  * Does the CPU have callbacks ready to be invoked?
298  */
299 static int
300 cpu_has_callbacks_ready_to_invoke(struct rcu_data *rdp)
301 {
302         return &rdp->nxtlist != rdp->nxttail[RCU_DONE_TAIL];
303 }
304
305 /*
306  * Does the current CPU require a yet-as-unscheduled grace period?
307  */
308 static int
309 cpu_needs_another_gp(struct rcu_state *rsp, struct rcu_data *rdp)
310 {
311         return *rdp->nxttail[RCU_DONE_TAIL +
312                              ACCESS_ONCE(rsp->completed) != rdp->completed] &&
313                !rcu_gp_in_progress(rsp);
314 }
315
316 /*
317  * Return the root node of the specified rcu_state structure.
318  */
319 static struct rcu_node *rcu_get_root(struct rcu_state *rsp)
320 {
321         return &rsp->node[0];
322 }
323
324 /*
325  * rcu_idle_enter_common - inform RCU that current CPU is moving towards idle
326  *
327  * If the new value of the ->dynticks_nesting counter now is zero,
328  * we really have entered idle, and must do the appropriate accounting.
329  * The caller must have disabled interrupts.
330  */
331 static void rcu_idle_enter_common(struct rcu_dynticks *rdtp, long long oldval)
332 {
333         trace_rcu_dyntick("Start", oldval, 0);
334         if (!is_idle_task(current)) {
335                 struct task_struct *idle = idle_task(smp_processor_id());
336
337                 trace_rcu_dyntick("Error on entry: not idle task", oldval, 0);
338                 ftrace_dump(DUMP_ORIG);
339                 WARN_ONCE(1, "Current pid: %d comm: %s / Idle pid: %d comm: %s",
340                           current->pid, current->comm,
341                           idle->pid, idle->comm); /* must be idle task! */
342         }
343         rcu_prepare_for_idle(smp_processor_id());
344         /* CPUs seeing atomic_inc() must see prior RCU read-side crit sects */
345         smp_mb__before_atomic_inc();  /* See above. */
346         atomic_inc(&rdtp->dynticks);
347         smp_mb__after_atomic_inc();  /* Force ordering with next sojourn. */
348         WARN_ON_ONCE(atomic_read(&rdtp->dynticks) & 0x1);
349
350         /*
351          * The idle task is not permitted to enter the idle loop while
352          * in an RCU read-side critical section.
353          */
354         rcu_lockdep_assert(!lock_is_held(&rcu_lock_map),
355                            "Illegal idle entry in RCU read-side critical section.");
356         rcu_lockdep_assert(!lock_is_held(&rcu_bh_lock_map),
357                            "Illegal idle entry in RCU-bh read-side critical section.");
358         rcu_lockdep_assert(!lock_is_held(&rcu_sched_lock_map),
359                            "Illegal idle entry in RCU-sched read-side critical section.");
360 }
361
362 /**
363  * rcu_idle_enter - inform RCU that current CPU is entering idle
364  *
365  * Enter idle mode, in other words, -leave- the mode in which RCU
366  * read-side critical sections can occur.  (Though RCU read-side
367  * critical sections can occur in irq handlers in idle, a possibility
368  * handled by irq_enter() and irq_exit().)
369  *
370  * We crowbar the ->dynticks_nesting field to zero to allow for
371  * the possibility of usermode upcalls having messed up our count
372  * of interrupt nesting level during the prior busy period.
373  */
374 void rcu_idle_enter(void)
375 {
376         unsigned long flags;
377         long long oldval;
378         struct rcu_dynticks *rdtp;
379
380         local_irq_save(flags);
381         rdtp = &__get_cpu_var(rcu_dynticks);
382         oldval = rdtp->dynticks_nesting;
383         WARN_ON_ONCE((oldval & DYNTICK_TASK_NEST_MASK) == 0);
384         if ((oldval & DYNTICK_TASK_NEST_MASK) == DYNTICK_TASK_NEST_VALUE)
385                 rdtp->dynticks_nesting = 0;
386         else
387                 rdtp->dynticks_nesting -= DYNTICK_TASK_NEST_VALUE;
388         rcu_idle_enter_common(rdtp, oldval);
389         local_irq_restore(flags);
390 }
391 EXPORT_SYMBOL_GPL(rcu_idle_enter);
392
393 /**
394  * rcu_irq_exit - inform RCU that current CPU is exiting irq towards idle
395  *
396  * Exit from an interrupt handler, which might possibly result in entering
397  * idle mode, in other words, leaving the mode in which read-side critical
398  * sections can occur.
399  *
400  * This code assumes that the idle loop never does anything that might
401  * result in unbalanced calls to irq_enter() and irq_exit().  If your
402  * architecture violates this assumption, RCU will give you what you
403  * deserve, good and hard.  But very infrequently and irreproducibly.
404  *
405  * Use things like work queues to work around this limitation.
406  *
407  * You have been warned.
408  */
409 void rcu_irq_exit(void)
410 {
411         unsigned long flags;
412         long long oldval;
413         struct rcu_dynticks *rdtp;
414
415         local_irq_save(flags);
416         rdtp = &__get_cpu_var(rcu_dynticks);
417         oldval = rdtp->dynticks_nesting;
418         rdtp->dynticks_nesting--;
419         WARN_ON_ONCE(rdtp->dynticks_nesting < 0);
420         if (rdtp->dynticks_nesting)
421                 trace_rcu_dyntick("--=", oldval, rdtp->dynticks_nesting);
422         else
423                 rcu_idle_enter_common(rdtp, oldval);
424         local_irq_restore(flags);
425 }
426
427 /*
428  * rcu_idle_exit_common - inform RCU that current CPU is moving away from idle
429  *
430  * If the new value of the ->dynticks_nesting counter was previously zero,
431  * we really have exited idle, and must do the appropriate accounting.
432  * The caller must have disabled interrupts.
433  */
434 static void rcu_idle_exit_common(struct rcu_dynticks *rdtp, long long oldval)
435 {
436         smp_mb__before_atomic_inc();  /* Force ordering w/previous sojourn. */
437         atomic_inc(&rdtp->dynticks);
438         /* CPUs seeing atomic_inc() must see later RCU read-side crit sects */
439         smp_mb__after_atomic_inc();  /* See above. */
440         WARN_ON_ONCE(!(atomic_read(&rdtp->dynticks) & 0x1));
441         rcu_cleanup_after_idle(smp_processor_id());
442         trace_rcu_dyntick("End", oldval, rdtp->dynticks_nesting);
443         if (!is_idle_task(current)) {
444                 struct task_struct *idle = idle_task(smp_processor_id());
445
446                 trace_rcu_dyntick("Error on exit: not idle task",
447                                   oldval, rdtp->dynticks_nesting);
448                 ftrace_dump(DUMP_ORIG);
449                 WARN_ONCE(1, "Current pid: %d comm: %s / Idle pid: %d comm: %s",
450                           current->pid, current->comm,
451                           idle->pid, idle->comm); /* must be idle task! */
452         }
453 }
454
455 /**
456  * rcu_idle_exit - inform RCU that current CPU is leaving idle
457  *
458  * Exit idle mode, in other words, -enter- the mode in which RCU
459  * read-side critical sections can occur.
460  *
461  * We crowbar the ->dynticks_nesting field to DYNTICK_TASK_NEST to
462  * allow for the possibility of usermode upcalls messing up our count
463  * of interrupt nesting level during the busy period that is just
464  * now starting.
465  */
466 void rcu_idle_exit(void)
467 {
468         unsigned long flags;
469         struct rcu_dynticks *rdtp;
470         long long oldval;
471
472         local_irq_save(flags);
473         rdtp = &__get_cpu_var(rcu_dynticks);
474         oldval = rdtp->dynticks_nesting;
475         WARN_ON_ONCE(oldval < 0);
476         if (oldval & DYNTICK_TASK_NEST_MASK)
477                 rdtp->dynticks_nesting += DYNTICK_TASK_NEST_VALUE;
478         else
479                 rdtp->dynticks_nesting = DYNTICK_TASK_EXIT_IDLE;
480         rcu_idle_exit_common(rdtp, oldval);
481         local_irq_restore(flags);
482 }
483 EXPORT_SYMBOL_GPL(rcu_idle_exit);
484
485 /**
486  * rcu_irq_enter - inform RCU that current CPU is entering irq away from idle
487  *
488  * Enter an interrupt handler, which might possibly result in exiting
489  * idle mode, in other words, entering the mode in which read-side critical
490  * sections can occur.
491  *
492  * Note that the Linux kernel is fully capable of entering an interrupt
493  * handler that it never exits, for example when doing upcalls to
494  * user mode!  This code assumes that the idle loop never does upcalls to
495  * user mode.  If your architecture does do upcalls from the idle loop (or
496  * does anything else that results in unbalanced calls to the irq_enter()
497  * and irq_exit() functions), RCU will give you what you deserve, good
498  * and hard.  But very infrequently and irreproducibly.
499  *
500  * Use things like work queues to work around this limitation.
501  *
502  * You have been warned.
503  */
504 void rcu_irq_enter(void)
505 {
506         unsigned long flags;
507         struct rcu_dynticks *rdtp;
508         long long oldval;
509
510         local_irq_save(flags);
511         rdtp = &__get_cpu_var(rcu_dynticks);
512         oldval = rdtp->dynticks_nesting;
513         rdtp->dynticks_nesting++;
514         WARN_ON_ONCE(rdtp->dynticks_nesting == 0);
515         if (oldval)
516                 trace_rcu_dyntick("++=", oldval, rdtp->dynticks_nesting);
517         else
518                 rcu_idle_exit_common(rdtp, oldval);
519         local_irq_restore(flags);
520 }
521
522 /**
523  * rcu_nmi_enter - inform RCU of entry to NMI context
524  *
525  * If the CPU was idle with dynamic ticks active, and there is no
526  * irq handler running, this updates rdtp->dynticks_nmi to let the
527  * RCU grace-period handling know that the CPU is active.
528  */
529 void rcu_nmi_enter(void)
530 {
531         struct rcu_dynticks *rdtp = &__get_cpu_var(rcu_dynticks);
532
533         if (rdtp->dynticks_nmi_nesting == 0 &&
534             (atomic_read(&rdtp->dynticks) & 0x1))
535                 return;
536         rdtp->dynticks_nmi_nesting++;
537         smp_mb__before_atomic_inc();  /* Force delay from prior write. */
538         atomic_inc(&rdtp->dynticks);
539         /* CPUs seeing atomic_inc() must see later RCU read-side crit sects */
540         smp_mb__after_atomic_inc();  /* See above. */
541         WARN_ON_ONCE(!(atomic_read(&rdtp->dynticks) & 0x1));
542 }
543
544 /**
545  * rcu_nmi_exit - inform RCU of exit from NMI context
546  *
547  * If the CPU was idle with dynamic ticks active, and there is no
548  * irq handler running, this updates rdtp->dynticks_nmi to let the
549  * RCU grace-period handling know that the CPU is no longer active.
550  */
551 void rcu_nmi_exit(void)
552 {
553         struct rcu_dynticks *rdtp = &__get_cpu_var(rcu_dynticks);
554
555         if (rdtp->dynticks_nmi_nesting == 0 ||
556             --rdtp->dynticks_nmi_nesting != 0)
557                 return;
558         /* CPUs seeing atomic_inc() must see prior RCU read-side crit sects */
559         smp_mb__before_atomic_inc();  /* See above. */
560         atomic_inc(&rdtp->dynticks);
561         smp_mb__after_atomic_inc();  /* Force delay to next write. */
562         WARN_ON_ONCE(atomic_read(&rdtp->dynticks) & 0x1);
563 }
564
565 /**
566  * rcu_is_cpu_idle - see if RCU thinks that the current CPU is idle
567  *
568  * If the current CPU is in its idle loop and is neither in an interrupt
569  * or NMI handler, return true.
570  */
571 int rcu_is_cpu_idle(void)
572 {
573         int ret;
574
575         preempt_disable();
576         ret = (atomic_read(&__get_cpu_var(rcu_dynticks).dynticks) & 0x1) == 0;
577         preempt_enable();
578         return ret;
579 }
580 EXPORT_SYMBOL(rcu_is_cpu_idle);
581
582 #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU)
583
584 /*
585  * Is the current CPU online?  Disable preemption to avoid false positives
586  * that could otherwise happen due to the current CPU number being sampled,
587  * this task being preempted, its old CPU being taken offline, resuming
588  * on some other CPU, then determining that its old CPU is now offline.
589  * It is OK to use RCU on an offline processor during initial boot, hence
590  * the check for rcu_scheduler_fully_active.  Note also that it is OK
591  * for a CPU coming online to use RCU for one jiffy prior to marking itself
592  * online in the cpu_online_mask.  Similarly, it is OK for a CPU going
593  * offline to continue to use RCU for one jiffy after marking itself
594  * offline in the cpu_online_mask.  This leniency is necessary given the
595  * non-atomic nature of the online and offline processing, for example,
596  * the fact that a CPU enters the scheduler after completing the CPU_DYING
597  * notifiers.
598  *
599  * This is also why RCU internally marks CPUs online during the
600  * CPU_UP_PREPARE phase and offline during the CPU_DEAD phase.
601  *
602  * Disable checking if in an NMI handler because we cannot safely report
603  * errors from NMI handlers anyway.
604  */
605 bool rcu_lockdep_current_cpu_online(void)
606 {
607         struct rcu_data *rdp;
608         struct rcu_node *rnp;
609         bool ret;
610
611         if (in_nmi())
612                 return 1;
613         preempt_disable();
614         rdp = &__get_cpu_var(rcu_sched_data);
615         rnp = rdp->mynode;
616         ret = (rdp->grpmask & rnp->qsmaskinit) ||
617               !rcu_scheduler_fully_active;
618         preempt_enable();
619         return ret;
620 }
621 EXPORT_SYMBOL_GPL(rcu_lockdep_current_cpu_online);
622
623 #endif /* #if defined(CONFIG_PROVE_RCU) && defined(CONFIG_HOTPLUG_CPU) */
624
625 /**
626  * rcu_is_cpu_rrupt_from_idle - see if idle or immediately interrupted from idle
627  *
628  * If the current CPU is idle or running at a first-level (not nested)
629  * interrupt from idle, return true.  The caller must have at least
630  * disabled preemption.
631  */
632 int rcu_is_cpu_rrupt_from_idle(void)
633 {
634         return __get_cpu_var(rcu_dynticks).dynticks_nesting <= 1;
635 }
636
637 /*
638  * Snapshot the specified CPU's dynticks counter so that we can later
639  * credit them with an implicit quiescent state.  Return 1 if this CPU
640  * is in dynticks idle mode, which is an extended quiescent state.
641  */
642 static int dyntick_save_progress_counter(struct rcu_data *rdp)
643 {
644         rdp->dynticks_snap = atomic_add_return(0, &rdp->dynticks->dynticks);
645         return (rdp->dynticks_snap & 0x1) == 0;
646 }
647
648 /*
649  * Return true if the specified CPU has passed through a quiescent
650  * state by virtue of being in or having passed through an dynticks
651  * idle state since the last call to dyntick_save_progress_counter()
652  * for this same CPU, or by virtue of having been offline.
653  */
654 static int rcu_implicit_dynticks_qs(struct rcu_data *rdp)
655 {
656         unsigned int curr;
657         unsigned int snap;
658
659         curr = (unsigned int)atomic_add_return(0, &rdp->dynticks->dynticks);
660         snap = (unsigned int)rdp->dynticks_snap;
661
662         /*
663          * If the CPU passed through or entered a dynticks idle phase with
664          * no active irq/NMI handlers, then we can safely pretend that the CPU
665          * already acknowledged the request to pass through a quiescent
666          * state.  Either way, that CPU cannot possibly be in an RCU
667          * read-side critical section that started before the beginning
668          * of the current RCU grace period.
669          */
670         if ((curr & 0x1) == 0 || UINT_CMP_GE(curr, snap + 2)) {
671                 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, "dti");
672                 rdp->dynticks_fqs++;
673                 return 1;
674         }
675
676         /*
677          * Check for the CPU being offline, but only if the grace period
678          * is old enough.  We don't need to worry about the CPU changing
679          * state: If we see it offline even once, it has been through a
680          * quiescent state.
681          *
682          * The reason for insisting that the grace period be at least
683          * one jiffy old is that CPUs that are not quite online and that
684          * have just gone offline can still execute RCU read-side critical
685          * sections.
686          */
687         if (ULONG_CMP_GE(rdp->rsp->gp_start + 2, jiffies))
688                 return 0;  /* Grace period is not old enough. */
689         barrier();
690         if (cpu_is_offline(rdp->cpu)) {
691                 trace_rcu_fqs(rdp->rsp->name, rdp->gpnum, rdp->cpu, "ofl");
692                 rdp->offline_fqs++;
693                 return 1;
694         }
695         return 0;
696 }
697
698 static int jiffies_till_stall_check(void)
699 {
700         int till_stall_check = ACCESS_ONCE(rcu_cpu_stall_timeout);
701
702         /*
703          * Limit check must be consistent with the Kconfig limits
704          * for CONFIG_RCU_CPU_STALL_TIMEOUT.
705          */
706         if (till_stall_check < 3) {
707                 ACCESS_ONCE(rcu_cpu_stall_timeout) = 3;
708                 till_stall_check = 3;
709         } else if (till_stall_check > 300) {
710                 ACCESS_ONCE(rcu_cpu_stall_timeout) = 300;
711                 till_stall_check = 300;
712         }
713         return till_stall_check * HZ + RCU_STALL_DELAY_DELTA;
714 }
715
716 static void record_gp_stall_check_time(struct rcu_state *rsp)
717 {
718         rsp->gp_start = jiffies;
719         rsp->jiffies_stall = jiffies + jiffies_till_stall_check();
720 }
721
722 static void print_other_cpu_stall(struct rcu_state *rsp)
723 {
724         int cpu;
725         long delta;
726         unsigned long flags;
727         int ndetected = 0;
728         struct rcu_node *rnp = rcu_get_root(rsp);
729
730         /* Only let one CPU complain about others per time interval. */
731
732         raw_spin_lock_irqsave(&rnp->lock, flags);
733         delta = jiffies - rsp->jiffies_stall;
734         if (delta < RCU_STALL_RAT_DELAY || !rcu_gp_in_progress(rsp)) {
735                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
736                 return;
737         }
738         rsp->jiffies_stall = jiffies + 3 * jiffies_till_stall_check() + 3;
739         raw_spin_unlock_irqrestore(&rnp->lock, flags);
740
741         /*
742          * OK, time to rat on our buddy...
743          * See Documentation/RCU/stallwarn.txt for info on how to debug
744          * RCU CPU stall warnings.
745          */
746         printk(KERN_ERR "INFO: %s detected stalls on CPUs/tasks:",
747                rsp->name);
748         print_cpu_stall_info_begin();
749         rcu_for_each_leaf_node(rsp, rnp) {
750                 raw_spin_lock_irqsave(&rnp->lock, flags);
751                 ndetected += rcu_print_task_stall(rnp);
752                 if (rnp->qsmask != 0) {
753                         for (cpu = 0; cpu <= rnp->grphi - rnp->grplo; cpu++)
754                                 if (rnp->qsmask & (1UL << cpu)) {
755                                         print_cpu_stall_info(rsp,
756                                                              rnp->grplo + cpu);
757                                         ndetected++;
758                                 }
759                 }
760                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
761         }
762
763         /*
764          * Now rat on any tasks that got kicked up to the root rcu_node
765          * due to CPU offlining.
766          */
767         rnp = rcu_get_root(rsp);
768         raw_spin_lock_irqsave(&rnp->lock, flags);
769         ndetected += rcu_print_task_stall(rnp);
770         raw_spin_unlock_irqrestore(&rnp->lock, flags);
771
772         print_cpu_stall_info_end();
773         printk(KERN_CONT "(detected by %d, t=%ld jiffies)\n",
774                smp_processor_id(), (long)(jiffies - rsp->gp_start));
775         if (ndetected == 0)
776                 printk(KERN_ERR "INFO: Stall ended before state dump start\n");
777         else if (!trigger_all_cpu_backtrace())
778                 dump_stack();
779
780         /* Complain about tasks blocking the grace period. */
781
782         rcu_print_detail_task_stall(rsp);
783
784         force_quiescent_state(rsp);  /* Kick them all. */
785 }
786
787 static void print_cpu_stall(struct rcu_state *rsp)
788 {
789         unsigned long flags;
790         struct rcu_node *rnp = rcu_get_root(rsp);
791
792         /*
793          * OK, time to rat on ourselves...
794          * See Documentation/RCU/stallwarn.txt for info on how to debug
795          * RCU CPU stall warnings.
796          */
797         printk(KERN_ERR "INFO: %s self-detected stall on CPU", rsp->name);
798         print_cpu_stall_info_begin();
799         print_cpu_stall_info(rsp, smp_processor_id());
800         print_cpu_stall_info_end();
801         printk(KERN_CONT " (t=%lu jiffies)\n", jiffies - rsp->gp_start);
802         if (!trigger_all_cpu_backtrace())
803                 dump_stack();
804
805         raw_spin_lock_irqsave(&rnp->lock, flags);
806         if (ULONG_CMP_GE(jiffies, rsp->jiffies_stall))
807                 rsp->jiffies_stall = jiffies +
808                                      3 * jiffies_till_stall_check() + 3;
809         raw_spin_unlock_irqrestore(&rnp->lock, flags);
810
811         set_need_resched();  /* kick ourselves to get things going. */
812 }
813
814 static void check_cpu_stall(struct rcu_state *rsp, struct rcu_data *rdp)
815 {
816         unsigned long j;
817         unsigned long js;
818         struct rcu_node *rnp;
819
820         if (rcu_cpu_stall_suppress)
821                 return;
822         j = ACCESS_ONCE(jiffies);
823         js = ACCESS_ONCE(rsp->jiffies_stall);
824         rnp = rdp->mynode;
825         if (rcu_gp_in_progress(rsp) &&
826             (ACCESS_ONCE(rnp->qsmask) & rdp->grpmask) && ULONG_CMP_GE(j, js)) {
827
828                 /* We haven't checked in, so go dump stack. */
829                 print_cpu_stall(rsp);
830
831         } else if (rcu_gp_in_progress(rsp) &&
832                    ULONG_CMP_GE(j, js + RCU_STALL_RAT_DELAY)) {
833
834                 /* They had a few time units to dump stack, so complain. */
835                 print_other_cpu_stall(rsp);
836         }
837 }
838
839 static int rcu_panic(struct notifier_block *this, unsigned long ev, void *ptr)
840 {
841         rcu_cpu_stall_suppress = 1;
842         return NOTIFY_DONE;
843 }
844
845 /**
846  * rcu_cpu_stall_reset - prevent further stall warnings in current grace period
847  *
848  * Set the stall-warning timeout way off into the future, thus preventing
849  * any RCU CPU stall-warning messages from appearing in the current set of
850  * RCU grace periods.
851  *
852  * The caller must disable hard irqs.
853  */
854 void rcu_cpu_stall_reset(void)
855 {
856         struct rcu_state *rsp;
857
858         for_each_rcu_flavor(rsp)
859                 rsp->jiffies_stall = jiffies + ULONG_MAX / 2;
860 }
861
862 static struct notifier_block rcu_panic_block = {
863         .notifier_call = rcu_panic,
864 };
865
866 static void __init check_cpu_stall_init(void)
867 {
868         atomic_notifier_chain_register(&panic_notifier_list, &rcu_panic_block);
869 }
870
871 /*
872  * Update CPU-local rcu_data state to record the newly noticed grace period.
873  * This is used both when we started the grace period and when we notice
874  * that someone else started the grace period.  The caller must hold the
875  * ->lock of the leaf rcu_node structure corresponding to the current CPU,
876  *  and must have irqs disabled.
877  */
878 static void __note_new_gpnum(struct rcu_state *rsp, struct rcu_node *rnp, struct rcu_data *rdp)
879 {
880         if (rdp->gpnum != rnp->gpnum) {
881                 /*
882                  * If the current grace period is waiting for this CPU,
883                  * set up to detect a quiescent state, otherwise don't
884                  * go looking for one.
885                  */
886                 rdp->gpnum = rnp->gpnum;
887                 trace_rcu_grace_period(rsp->name, rdp->gpnum, "cpustart");
888                 rdp->passed_quiesce = 0;
889                 rdp->qs_pending = !!(rnp->qsmask & rdp->grpmask);
890                 zero_cpu_stall_ticks(rdp);
891         }
892 }
893
894 static void note_new_gpnum(struct rcu_state *rsp, struct rcu_data *rdp)
895 {
896         unsigned long flags;
897         struct rcu_node *rnp;
898
899         local_irq_save(flags);
900         rnp = rdp->mynode;
901         if (rdp->gpnum == ACCESS_ONCE(rnp->gpnum) || /* outside lock. */
902             !raw_spin_trylock(&rnp->lock)) { /* irqs already off, so later. */
903                 local_irq_restore(flags);
904                 return;
905         }
906         __note_new_gpnum(rsp, rnp, rdp);
907         raw_spin_unlock_irqrestore(&rnp->lock, flags);
908 }
909
910 /*
911  * Did someone else start a new RCU grace period start since we last
912  * checked?  Update local state appropriately if so.  Must be called
913  * on the CPU corresponding to rdp.
914  */
915 static int
916 check_for_new_grace_period(struct rcu_state *rsp, struct rcu_data *rdp)
917 {
918         unsigned long flags;
919         int ret = 0;
920
921         local_irq_save(flags);
922         if (rdp->gpnum != rsp->gpnum) {
923                 note_new_gpnum(rsp, rdp);
924                 ret = 1;
925         }
926         local_irq_restore(flags);
927         return ret;
928 }
929
930 /*
931  * Initialize the specified rcu_data structure's callback list to empty.
932  */
933 static void init_callback_list(struct rcu_data *rdp)
934 {
935         int i;
936
937         rdp->nxtlist = NULL;
938         for (i = 0; i < RCU_NEXT_SIZE; i++)
939                 rdp->nxttail[i] = &rdp->nxtlist;
940 }
941
942 /*
943  * Advance this CPU's callbacks, but only if the current grace period
944  * has ended.  This may be called only from the CPU to whom the rdp
945  * belongs.  In addition, the corresponding leaf rcu_node structure's
946  * ->lock must be held by the caller, with irqs disabled.
947  */
948 static void
949 __rcu_process_gp_end(struct rcu_state *rsp, struct rcu_node *rnp, struct rcu_data *rdp)
950 {
951         /* Did another grace period end? */
952         if (rdp->completed != rnp->completed) {
953
954                 /* Advance callbacks.  No harm if list empty. */
955                 rdp->nxttail[RCU_DONE_TAIL] = rdp->nxttail[RCU_WAIT_TAIL];
956                 rdp->nxttail[RCU_WAIT_TAIL] = rdp->nxttail[RCU_NEXT_READY_TAIL];
957                 rdp->nxttail[RCU_NEXT_READY_TAIL] = rdp->nxttail[RCU_NEXT_TAIL];
958
959                 /* Remember that we saw this grace-period completion. */
960                 rdp->completed = rnp->completed;
961                 trace_rcu_grace_period(rsp->name, rdp->gpnum, "cpuend");
962
963                 /*
964                  * If we were in an extended quiescent state, we may have
965                  * missed some grace periods that others CPUs handled on
966                  * our behalf. Catch up with this state to avoid noting
967                  * spurious new grace periods.  If another grace period
968                  * has started, then rnp->gpnum will have advanced, so
969                  * we will detect this later on.  Of course, any quiescent
970                  * states we found for the old GP are now invalid.
971                  */
972                 if (ULONG_CMP_LT(rdp->gpnum, rdp->completed)) {
973                         rdp->gpnum = rdp->completed;
974                         rdp->passed_quiesce = 0;
975                 }
976
977                 /*
978                  * If RCU does not need a quiescent state from this CPU,
979                  * then make sure that this CPU doesn't go looking for one.
980                  */
981                 if ((rnp->qsmask & rdp->grpmask) == 0)
982                         rdp->qs_pending = 0;
983         }
984 }
985
986 /*
987  * Advance this CPU's callbacks, but only if the current grace period
988  * has ended.  This may be called only from the CPU to whom the rdp
989  * belongs.
990  */
991 static void
992 rcu_process_gp_end(struct rcu_state *rsp, struct rcu_data *rdp)
993 {
994         unsigned long flags;
995         struct rcu_node *rnp;
996
997         local_irq_save(flags);
998         rnp = rdp->mynode;
999         if (rdp->completed == ACCESS_ONCE(rnp->completed) || /* outside lock. */
1000             !raw_spin_trylock(&rnp->lock)) { /* irqs already off, so later. */
1001                 local_irq_restore(flags);
1002                 return;
1003         }
1004         __rcu_process_gp_end(rsp, rnp, rdp);
1005         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1006 }
1007
1008 /*
1009  * Do per-CPU grace-period initialization for running CPU.  The caller
1010  * must hold the lock of the leaf rcu_node structure corresponding to
1011  * this CPU.
1012  */
1013 static void
1014 rcu_start_gp_per_cpu(struct rcu_state *rsp, struct rcu_node *rnp, struct rcu_data *rdp)
1015 {
1016         /* Prior grace period ended, so advance callbacks for current CPU. */
1017         __rcu_process_gp_end(rsp, rnp, rdp);
1018
1019         /* Set state so that this CPU will detect the next quiescent state. */
1020         __note_new_gpnum(rsp, rnp, rdp);
1021 }
1022
1023 /*
1024  * Initialize a new grace period.
1025  */
1026 static int rcu_gp_init(struct rcu_state *rsp)
1027 {
1028         struct rcu_data *rdp;
1029         struct rcu_node *rnp = rcu_get_root(rsp);
1030
1031         raw_spin_lock_irq(&rnp->lock);
1032         rsp->gp_flags = 0; /* Clear all flags: New grace period. */
1033
1034         if (rcu_gp_in_progress(rsp)) {
1035                 /* Grace period already in progress, don't start another.  */
1036                 raw_spin_unlock_irq(&rnp->lock);
1037                 return 0;
1038         }
1039
1040         /* Advance to a new grace period and initialize state. */
1041         rsp->gpnum++;
1042         trace_rcu_grace_period(rsp->name, rsp->gpnum, "start");
1043         record_gp_stall_check_time(rsp);
1044         raw_spin_unlock_irq(&rnp->lock);
1045
1046         /* Exclude any concurrent CPU-hotplug operations. */
1047         get_online_cpus();
1048
1049         /*
1050          * Set the quiescent-state-needed bits in all the rcu_node
1051          * structures for all currently online CPUs in breadth-first order,
1052          * starting from the root rcu_node structure, relying on the layout
1053          * of the tree within the rsp->node[] array.  Note that other CPUs
1054          * will access only the leaves of the hierarchy, thus seeing that no
1055          * grace period is in progress, at least until the corresponding
1056          * leaf node has been initialized.  In addition, we have excluded
1057          * CPU-hotplug operations.
1058          *
1059          * The grace period cannot complete until the initialization
1060          * process finishes, because this kthread handles both.
1061          */
1062         rcu_for_each_node_breadth_first(rsp, rnp) {
1063                 raw_spin_lock_irq(&rnp->lock);
1064                 rdp = this_cpu_ptr(rsp->rda);
1065                 rcu_preempt_check_blocked_tasks(rnp);
1066                 rnp->qsmask = rnp->qsmaskinit;
1067                 rnp->gpnum = rsp->gpnum;
1068                 WARN_ON_ONCE(rnp->completed != rsp->completed);
1069                 rnp->completed = rsp->completed;
1070                 if (rnp == rdp->mynode)
1071                         rcu_start_gp_per_cpu(rsp, rnp, rdp);
1072                 rcu_preempt_boost_start_gp(rnp);
1073                 trace_rcu_grace_period_init(rsp->name, rnp->gpnum,
1074                                             rnp->level, rnp->grplo,
1075                                             rnp->grphi, rnp->qsmask);
1076                 raw_spin_unlock_irq(&rnp->lock);
1077 #ifdef CONFIG_PROVE_RCU_DELAY
1078                 if ((random32() % (rcu_num_nodes * 8)) == 0)
1079                         schedule_timeout_uninterruptible(2);
1080 #endif /* #ifdef CONFIG_PROVE_RCU_DELAY */
1081                 cond_resched();
1082         }
1083
1084         put_online_cpus();
1085         return 1;
1086 }
1087
1088 /*
1089  * Do one round of quiescent-state forcing.
1090  */
1091 int rcu_gp_fqs(struct rcu_state *rsp, int fqs_state_in)
1092 {
1093         int fqs_state = fqs_state_in;
1094         struct rcu_node *rnp = rcu_get_root(rsp);
1095
1096         rsp->n_force_qs++;
1097         if (fqs_state == RCU_SAVE_DYNTICK) {
1098                 /* Collect dyntick-idle snapshots. */
1099                 force_qs_rnp(rsp, dyntick_save_progress_counter);
1100                 fqs_state = RCU_FORCE_QS;
1101         } else {
1102                 /* Handle dyntick-idle and offline CPUs. */
1103                 force_qs_rnp(rsp, rcu_implicit_dynticks_qs);
1104         }
1105         /* Clear flag to prevent immediate re-entry. */
1106         if (ACCESS_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) {
1107                 raw_spin_lock_irq(&rnp->lock);
1108                 rsp->gp_flags &= ~RCU_GP_FLAG_FQS;
1109                 raw_spin_unlock_irq(&rnp->lock);
1110         }
1111         return fqs_state;
1112 }
1113
1114 /*
1115  * Clean up after the old grace period.
1116  */
1117 static void rcu_gp_cleanup(struct rcu_state *rsp)
1118 {
1119         unsigned long gp_duration;
1120         struct rcu_data *rdp;
1121         struct rcu_node *rnp = rcu_get_root(rsp);
1122
1123         raw_spin_lock_irq(&rnp->lock);
1124         gp_duration = jiffies - rsp->gp_start;
1125         if (gp_duration > rsp->gp_max)
1126                 rsp->gp_max = gp_duration;
1127
1128         /*
1129          * We know the grace period is complete, but to everyone else
1130          * it appears to still be ongoing.  But it is also the case
1131          * that to everyone else it looks like there is nothing that
1132          * they can do to advance the grace period.  It is therefore
1133          * safe for us to drop the lock in order to mark the grace
1134          * period as completed in all of the rcu_node structures.
1135          */
1136         raw_spin_unlock_irq(&rnp->lock);
1137
1138         /*
1139          * Propagate new ->completed value to rcu_node structures so
1140          * that other CPUs don't have to wait until the start of the next
1141          * grace period to process their callbacks.  This also avoids
1142          * some nasty RCU grace-period initialization races by forcing
1143          * the end of the current grace period to be completely recorded in
1144          * all of the rcu_node structures before the beginning of the next
1145          * grace period is recorded in any of the rcu_node structures.
1146          */
1147         rcu_for_each_node_breadth_first(rsp, rnp) {
1148                 raw_spin_lock_irq(&rnp->lock);
1149                 rnp->completed = rsp->gpnum;
1150                 raw_spin_unlock_irq(&rnp->lock);
1151                 cond_resched();
1152         }
1153         rnp = rcu_get_root(rsp);
1154         raw_spin_lock_irq(&rnp->lock);
1155
1156         rsp->completed = rsp->gpnum; /* Declare grace period done. */
1157         trace_rcu_grace_period(rsp->name, rsp->completed, "end");
1158         rsp->fqs_state = RCU_GP_IDLE;
1159         rdp = this_cpu_ptr(rsp->rda);
1160         if (cpu_needs_another_gp(rsp, rdp))
1161                 rsp->gp_flags = 1;
1162         raw_spin_unlock_irq(&rnp->lock);
1163 }
1164
1165 /*
1166  * Body of kthread that handles grace periods.
1167  */
1168 static int __noreturn rcu_gp_kthread(void *arg)
1169 {
1170         int fqs_state;
1171         unsigned long j;
1172         int ret;
1173         struct rcu_state *rsp = arg;
1174         struct rcu_node *rnp = rcu_get_root(rsp);
1175
1176         for (;;) {
1177
1178                 /* Handle grace-period start. */
1179                 for (;;) {
1180                         wait_event_interruptible(rsp->gp_wq,
1181                                                  rsp->gp_flags &
1182                                                  RCU_GP_FLAG_INIT);
1183                         if ((rsp->gp_flags & RCU_GP_FLAG_INIT) &&
1184                             rcu_gp_init(rsp))
1185                                 break;
1186                         cond_resched();
1187                         flush_signals(current);
1188                 }
1189
1190                 /* Handle quiescent-state forcing. */
1191                 fqs_state = RCU_SAVE_DYNTICK;
1192                 j = jiffies_till_first_fqs;
1193                 if (j > HZ) {
1194                         j = HZ;
1195                         jiffies_till_first_fqs = HZ;
1196                 }
1197                 for (;;) {
1198                         rsp->jiffies_force_qs = jiffies + j;
1199                         ret = wait_event_interruptible_timeout(rsp->gp_wq,
1200                                         (rsp->gp_flags & RCU_GP_FLAG_FQS) ||
1201                                         (!ACCESS_ONCE(rnp->qsmask) &&
1202                                          !rcu_preempt_blocked_readers_cgp(rnp)),
1203                                         j);
1204                         /* If grace period done, leave loop. */
1205                         if (!ACCESS_ONCE(rnp->qsmask) &&
1206                             !rcu_preempt_blocked_readers_cgp(rnp))
1207                                 break;
1208                         /* If time for quiescent-state forcing, do it. */
1209                         if (ret == 0 || (rsp->gp_flags & RCU_GP_FLAG_FQS)) {
1210                                 fqs_state = rcu_gp_fqs(rsp, fqs_state);
1211                                 cond_resched();
1212                         } else {
1213                                 /* Deal with stray signal. */
1214                                 cond_resched();
1215                                 flush_signals(current);
1216                         }
1217                         j = jiffies_till_next_fqs;
1218                         if (j > HZ) {
1219                                 j = HZ;
1220                                 jiffies_till_next_fqs = HZ;
1221                         } else if (j < 1) {
1222                                 j = 1;
1223                                 jiffies_till_next_fqs = 1;
1224                         }
1225                 }
1226
1227                 /* Handle grace-period end. */
1228                 rcu_gp_cleanup(rsp);
1229         }
1230 }
1231
1232 /*
1233  * Start a new RCU grace period if warranted, re-initializing the hierarchy
1234  * in preparation for detecting the next grace period.  The caller must hold
1235  * the root node's ->lock, which is released before return.  Hard irqs must
1236  * be disabled.
1237  *
1238  * Note that it is legal for a dying CPU (which is marked as offline) to
1239  * invoke this function.  This can happen when the dying CPU reports its
1240  * quiescent state.
1241  */
1242 static void
1243 rcu_start_gp(struct rcu_state *rsp, unsigned long flags)
1244         __releases(rcu_get_root(rsp)->lock)
1245 {
1246         struct rcu_data *rdp = this_cpu_ptr(rsp->rda);
1247         struct rcu_node *rnp = rcu_get_root(rsp);
1248
1249         if (!rsp->gp_kthread ||
1250             !cpu_needs_another_gp(rsp, rdp)) {
1251                 /*
1252                  * Either we have not yet spawned the grace-period
1253                  * task or this CPU does not need another grace period.
1254                  * Either way, don't start a new grace period.
1255                  */
1256                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1257                 return;
1258         }
1259
1260         rsp->gp_flags = RCU_GP_FLAG_INIT;
1261         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1262         wake_up(&rsp->gp_wq);
1263 }
1264
1265 /*
1266  * Report a full set of quiescent states to the specified rcu_state
1267  * data structure.  This involves cleaning up after the prior grace
1268  * period and letting rcu_start_gp() start up the next grace period
1269  * if one is needed.  Note that the caller must hold rnp->lock, as
1270  * required by rcu_start_gp(), which will release it.
1271  */
1272 static void rcu_report_qs_rsp(struct rcu_state *rsp, unsigned long flags)
1273         __releases(rcu_get_root(rsp)->lock)
1274 {
1275         WARN_ON_ONCE(!rcu_gp_in_progress(rsp));
1276         raw_spin_unlock_irqrestore(&rcu_get_root(rsp)->lock, flags);
1277         wake_up(&rsp->gp_wq);  /* Memory barrier implied by wake_up() path. */
1278 }
1279
1280 /*
1281  * Similar to rcu_report_qs_rdp(), for which it is a helper function.
1282  * Allows quiescent states for a group of CPUs to be reported at one go
1283  * to the specified rcu_node structure, though all the CPUs in the group
1284  * must be represented by the same rcu_node structure (which need not be
1285  * a leaf rcu_node structure, though it often will be).  That structure's
1286  * lock must be held upon entry, and it is released before return.
1287  */
1288 static void
1289 rcu_report_qs_rnp(unsigned long mask, struct rcu_state *rsp,
1290                   struct rcu_node *rnp, unsigned long flags)
1291         __releases(rnp->lock)
1292 {
1293         struct rcu_node *rnp_c;
1294
1295         /* Walk up the rcu_node hierarchy. */
1296         for (;;) {
1297                 if (!(rnp->qsmask & mask)) {
1298
1299                         /* Our bit has already been cleared, so done. */
1300                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1301                         return;
1302                 }
1303                 rnp->qsmask &= ~mask;
1304                 trace_rcu_quiescent_state_report(rsp->name, rnp->gpnum,
1305                                                  mask, rnp->qsmask, rnp->level,
1306                                                  rnp->grplo, rnp->grphi,
1307                                                  !!rnp->gp_tasks);
1308                 if (rnp->qsmask != 0 || rcu_preempt_blocked_readers_cgp(rnp)) {
1309
1310                         /* Other bits still set at this level, so done. */
1311                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1312                         return;
1313                 }
1314                 mask = rnp->grpmask;
1315                 if (rnp->parent == NULL) {
1316
1317                         /* No more levels.  Exit loop holding root lock. */
1318
1319                         break;
1320                 }
1321                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1322                 rnp_c = rnp;
1323                 rnp = rnp->parent;
1324                 raw_spin_lock_irqsave(&rnp->lock, flags);
1325                 WARN_ON_ONCE(rnp_c->qsmask);
1326         }
1327
1328         /*
1329          * Get here if we are the last CPU to pass through a quiescent
1330          * state for this grace period.  Invoke rcu_report_qs_rsp()
1331          * to clean up and start the next grace period if one is needed.
1332          */
1333         rcu_report_qs_rsp(rsp, flags); /* releases rnp->lock. */
1334 }
1335
1336 /*
1337  * Record a quiescent state for the specified CPU to that CPU's rcu_data
1338  * structure.  This must be either called from the specified CPU, or
1339  * called when the specified CPU is known to be offline (and when it is
1340  * also known that no other CPU is concurrently trying to help the offline
1341  * CPU).  The lastcomp argument is used to make sure we are still in the
1342  * grace period of interest.  We don't want to end the current grace period
1343  * based on quiescent states detected in an earlier grace period!
1344  */
1345 static void
1346 rcu_report_qs_rdp(int cpu, struct rcu_state *rsp, struct rcu_data *rdp)
1347 {
1348         unsigned long flags;
1349         unsigned long mask;
1350         struct rcu_node *rnp;
1351
1352         rnp = rdp->mynode;
1353         raw_spin_lock_irqsave(&rnp->lock, flags);
1354         if (rdp->passed_quiesce == 0 || rdp->gpnum != rnp->gpnum ||
1355             rnp->completed == rnp->gpnum) {
1356
1357                 /*
1358                  * The grace period in which this quiescent state was
1359                  * recorded has ended, so don't report it upwards.
1360                  * We will instead need a new quiescent state that lies
1361                  * within the current grace period.
1362                  */
1363                 rdp->passed_quiesce = 0;        /* need qs for new gp. */
1364                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1365                 return;
1366         }
1367         mask = rdp->grpmask;
1368         if ((rnp->qsmask & mask) == 0) {
1369                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1370         } else {
1371                 rdp->qs_pending = 0;
1372
1373                 /*
1374                  * This GP can't end until cpu checks in, so all of our
1375                  * callbacks can be processed during the next GP.
1376                  */
1377                 rdp->nxttail[RCU_NEXT_READY_TAIL] = rdp->nxttail[RCU_NEXT_TAIL];
1378
1379                 rcu_report_qs_rnp(mask, rsp, rnp, flags); /* rlses rnp->lock */
1380         }
1381 }
1382
1383 /*
1384  * Check to see if there is a new grace period of which this CPU
1385  * is not yet aware, and if so, set up local rcu_data state for it.
1386  * Otherwise, see if this CPU has just passed through its first
1387  * quiescent state for this grace period, and record that fact if so.
1388  */
1389 static void
1390 rcu_check_quiescent_state(struct rcu_state *rsp, struct rcu_data *rdp)
1391 {
1392         /* If there is now a new grace period, record and return. */
1393         if (check_for_new_grace_period(rsp, rdp))
1394                 return;
1395
1396         /*
1397          * Does this CPU still need to do its part for current grace period?
1398          * If no, return and let the other CPUs do their part as well.
1399          */
1400         if (!rdp->qs_pending)
1401                 return;
1402
1403         /*
1404          * Was there a quiescent state since the beginning of the grace
1405          * period? If no, then exit and wait for the next call.
1406          */
1407         if (!rdp->passed_quiesce)
1408                 return;
1409
1410         /*
1411          * Tell RCU we are done (but rcu_report_qs_rdp() will be the
1412          * judge of that).
1413          */
1414         rcu_report_qs_rdp(rdp->cpu, rsp, rdp);
1415 }
1416
1417 #ifdef CONFIG_HOTPLUG_CPU
1418
1419 /*
1420  * Send the specified CPU's RCU callbacks to the orphanage.  The
1421  * specified CPU must be offline, and the caller must hold the
1422  * ->onofflock.
1423  */
1424 static void
1425 rcu_send_cbs_to_orphanage(int cpu, struct rcu_state *rsp,
1426                           struct rcu_node *rnp, struct rcu_data *rdp)
1427 {
1428         /*
1429          * Orphan the callbacks.  First adjust the counts.  This is safe
1430          * because ->onofflock excludes _rcu_barrier()'s adoption of
1431          * the callbacks, thus no memory barrier is required.
1432          */
1433         if (rdp->nxtlist != NULL) {
1434                 rsp->qlen_lazy += rdp->qlen_lazy;
1435                 rsp->qlen += rdp->qlen;
1436                 rdp->n_cbs_orphaned += rdp->qlen;
1437                 rdp->qlen_lazy = 0;
1438                 ACCESS_ONCE(rdp->qlen) = 0;
1439         }
1440
1441         /*
1442          * Next, move those callbacks still needing a grace period to
1443          * the orphanage, where some other CPU will pick them up.
1444          * Some of the callbacks might have gone partway through a grace
1445          * period, but that is too bad.  They get to start over because we
1446          * cannot assume that grace periods are synchronized across CPUs.
1447          * We don't bother updating the ->nxttail[] array yet, instead
1448          * we just reset the whole thing later on.
1449          */
1450         if (*rdp->nxttail[RCU_DONE_TAIL] != NULL) {
1451                 *rsp->orphan_nxttail = *rdp->nxttail[RCU_DONE_TAIL];
1452                 rsp->orphan_nxttail = rdp->nxttail[RCU_NEXT_TAIL];
1453                 *rdp->nxttail[RCU_DONE_TAIL] = NULL;
1454         }
1455
1456         /*
1457          * Then move the ready-to-invoke callbacks to the orphanage,
1458          * where some other CPU will pick them up.  These will not be
1459          * required to pass though another grace period: They are done.
1460          */
1461         if (rdp->nxtlist != NULL) {
1462                 *rsp->orphan_donetail = rdp->nxtlist;
1463                 rsp->orphan_donetail = rdp->nxttail[RCU_DONE_TAIL];
1464         }
1465
1466         /* Finally, initialize the rcu_data structure's list to empty.  */
1467         init_callback_list(rdp);
1468 }
1469
1470 /*
1471  * Adopt the RCU callbacks from the specified rcu_state structure's
1472  * orphanage.  The caller must hold the ->onofflock.
1473  */
1474 static void rcu_adopt_orphan_cbs(struct rcu_state *rsp)
1475 {
1476         int i;
1477         struct rcu_data *rdp = __this_cpu_ptr(rsp->rda);
1478
1479         /* Do the accounting first. */
1480         rdp->qlen_lazy += rsp->qlen_lazy;
1481         rdp->qlen += rsp->qlen;
1482         rdp->n_cbs_adopted += rsp->qlen;
1483         if (rsp->qlen_lazy != rsp->qlen)
1484                 rcu_idle_count_callbacks_posted();
1485         rsp->qlen_lazy = 0;
1486         rsp->qlen = 0;
1487
1488         /*
1489          * We do not need a memory barrier here because the only way we
1490          * can get here if there is an rcu_barrier() in flight is if
1491          * we are the task doing the rcu_barrier().
1492          */
1493
1494         /* First adopt the ready-to-invoke callbacks. */
1495         if (rsp->orphan_donelist != NULL) {
1496                 *rsp->orphan_donetail = *rdp->nxttail[RCU_DONE_TAIL];
1497                 *rdp->nxttail[RCU_DONE_TAIL] = rsp->orphan_donelist;
1498                 for (i = RCU_NEXT_SIZE - 1; i >= RCU_DONE_TAIL; i--)
1499                         if (rdp->nxttail[i] == rdp->nxttail[RCU_DONE_TAIL])
1500                                 rdp->nxttail[i] = rsp->orphan_donetail;
1501                 rsp->orphan_donelist = NULL;
1502                 rsp->orphan_donetail = &rsp->orphan_donelist;
1503         }
1504
1505         /* And then adopt the callbacks that still need a grace period. */
1506         if (rsp->orphan_nxtlist != NULL) {
1507                 *rdp->nxttail[RCU_NEXT_TAIL] = rsp->orphan_nxtlist;
1508                 rdp->nxttail[RCU_NEXT_TAIL] = rsp->orphan_nxttail;
1509                 rsp->orphan_nxtlist = NULL;
1510                 rsp->orphan_nxttail = &rsp->orphan_nxtlist;
1511         }
1512 }
1513
1514 /*
1515  * Trace the fact that this CPU is going offline.
1516  */
1517 static void rcu_cleanup_dying_cpu(struct rcu_state *rsp)
1518 {
1519         RCU_TRACE(unsigned long mask);
1520         RCU_TRACE(struct rcu_data *rdp = this_cpu_ptr(rsp->rda));
1521         RCU_TRACE(struct rcu_node *rnp = rdp->mynode);
1522
1523         RCU_TRACE(mask = rdp->grpmask);
1524         trace_rcu_grace_period(rsp->name,
1525                                rnp->gpnum + 1 - !!(rnp->qsmask & mask),
1526                                "cpuofl");
1527 }
1528
1529 /*
1530  * The CPU has been completely removed, and some other CPU is reporting
1531  * this fact from process context.  Do the remainder of the cleanup,
1532  * including orphaning the outgoing CPU's RCU callbacks, and also
1533  * adopting them.  There can only be one CPU hotplug operation at a time,
1534  * so no other CPU can be attempting to update rcu_cpu_kthread_task.
1535  */
1536 static void rcu_cleanup_dead_cpu(int cpu, struct rcu_state *rsp)
1537 {
1538         unsigned long flags;
1539         unsigned long mask;
1540         int need_report = 0;
1541         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
1542         struct rcu_node *rnp = rdp->mynode;  /* Outgoing CPU's rdp & rnp. */
1543
1544         /* Adjust any no-longer-needed kthreads. */
1545         rcu_boost_kthread_setaffinity(rnp, -1);
1546
1547         /* Remove the dead CPU from the bitmasks in the rcu_node hierarchy. */
1548
1549         /* Exclude any attempts to start a new grace period. */
1550         raw_spin_lock_irqsave(&rsp->onofflock, flags);
1551
1552         /* Orphan the dead CPU's callbacks, and adopt them if appropriate. */
1553         rcu_send_cbs_to_orphanage(cpu, rsp, rnp, rdp);
1554         rcu_adopt_orphan_cbs(rsp);
1555
1556         /* Remove the outgoing CPU from the masks in the rcu_node hierarchy. */
1557         mask = rdp->grpmask;    /* rnp->grplo is constant. */
1558         do {
1559                 raw_spin_lock(&rnp->lock);      /* irqs already disabled. */
1560                 rnp->qsmaskinit &= ~mask;
1561                 if (rnp->qsmaskinit != 0) {
1562                         if (rnp != rdp->mynode)
1563                                 raw_spin_unlock(&rnp->lock); /* irqs remain disabled. */
1564                         break;
1565                 }
1566                 if (rnp == rdp->mynode)
1567                         need_report = rcu_preempt_offline_tasks(rsp, rnp, rdp);
1568                 else
1569                         raw_spin_unlock(&rnp->lock); /* irqs remain disabled. */
1570                 mask = rnp->grpmask;
1571                 rnp = rnp->parent;
1572         } while (rnp != NULL);
1573
1574         /*
1575          * We still hold the leaf rcu_node structure lock here, and
1576          * irqs are still disabled.  The reason for this subterfuge is
1577          * because invoking rcu_report_unblock_qs_rnp() with ->onofflock
1578          * held leads to deadlock.
1579          */
1580         raw_spin_unlock(&rsp->onofflock); /* irqs remain disabled. */
1581         rnp = rdp->mynode;
1582         if (need_report & RCU_OFL_TASKS_NORM_GP)
1583                 rcu_report_unblock_qs_rnp(rnp, flags);
1584         else
1585                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1586         if (need_report & RCU_OFL_TASKS_EXP_GP)
1587                 rcu_report_exp_rnp(rsp, rnp, true);
1588         WARN_ONCE(rdp->qlen != 0 || rdp->nxtlist != NULL,
1589                   "rcu_cleanup_dead_cpu: Callbacks on offline CPU %d: qlen=%lu, nxtlist=%p\n",
1590                   cpu, rdp->qlen, rdp->nxtlist);
1591         init_callback_list(rdp);
1592         /* Disallow further callbacks on this CPU. */
1593         rdp->nxttail[RCU_NEXT_TAIL] = NULL;
1594 }
1595
1596 #else /* #ifdef CONFIG_HOTPLUG_CPU */
1597
1598 static void rcu_cleanup_dying_cpu(struct rcu_state *rsp)
1599 {
1600 }
1601
1602 static void rcu_cleanup_dead_cpu(int cpu, struct rcu_state *rsp)
1603 {
1604 }
1605
1606 #endif /* #else #ifdef CONFIG_HOTPLUG_CPU */
1607
1608 /*
1609  * Invoke any RCU callbacks that have made it to the end of their grace
1610  * period.  Thottle as specified by rdp->blimit.
1611  */
1612 static void rcu_do_batch(struct rcu_state *rsp, struct rcu_data *rdp)
1613 {
1614         unsigned long flags;
1615         struct rcu_head *next, *list, **tail;
1616         int bl, count, count_lazy, i;
1617
1618         /* If no callbacks are ready, just return.*/
1619         if (!cpu_has_callbacks_ready_to_invoke(rdp)) {
1620                 trace_rcu_batch_start(rsp->name, rdp->qlen_lazy, rdp->qlen, 0);
1621                 trace_rcu_batch_end(rsp->name, 0, !!ACCESS_ONCE(rdp->nxtlist),
1622                                     need_resched(), is_idle_task(current),
1623                                     rcu_is_callbacks_kthread());
1624                 return;
1625         }
1626
1627         /*
1628          * Extract the list of ready callbacks, disabling to prevent
1629          * races with call_rcu() from interrupt handlers.
1630          */
1631         local_irq_save(flags);
1632         WARN_ON_ONCE(cpu_is_offline(smp_processor_id()));
1633         bl = rdp->blimit;
1634         trace_rcu_batch_start(rsp->name, rdp->qlen_lazy, rdp->qlen, bl);
1635         list = rdp->nxtlist;
1636         rdp->nxtlist = *rdp->nxttail[RCU_DONE_TAIL];
1637         *rdp->nxttail[RCU_DONE_TAIL] = NULL;
1638         tail = rdp->nxttail[RCU_DONE_TAIL];
1639         for (i = RCU_NEXT_SIZE - 1; i >= 0; i--)
1640                 if (rdp->nxttail[i] == rdp->nxttail[RCU_DONE_TAIL])
1641                         rdp->nxttail[i] = &rdp->nxtlist;
1642         local_irq_restore(flags);
1643
1644         /* Invoke callbacks. */
1645         count = count_lazy = 0;
1646         while (list) {
1647                 next = list->next;
1648                 prefetch(next);
1649                 debug_rcu_head_unqueue(list);
1650                 if (__rcu_reclaim(rsp->name, list))
1651                         count_lazy++;
1652                 list = next;
1653                 /* Stop only if limit reached and CPU has something to do. */
1654                 if (++count >= bl &&
1655                     (need_resched() ||
1656                      (!is_idle_task(current) && !rcu_is_callbacks_kthread())))
1657                         break;
1658         }
1659
1660         local_irq_save(flags);
1661         trace_rcu_batch_end(rsp->name, count, !!list, need_resched(),
1662                             is_idle_task(current),
1663                             rcu_is_callbacks_kthread());
1664
1665         /* Update count, and requeue any remaining callbacks. */
1666         if (list != NULL) {
1667                 *tail = rdp->nxtlist;
1668                 rdp->nxtlist = list;
1669                 for (i = 0; i < RCU_NEXT_SIZE; i++)
1670                         if (&rdp->nxtlist == rdp->nxttail[i])
1671                                 rdp->nxttail[i] = tail;
1672                         else
1673                                 break;
1674         }
1675         smp_mb(); /* List handling before counting for rcu_barrier(). */
1676         rdp->qlen_lazy -= count_lazy;
1677         ACCESS_ONCE(rdp->qlen) -= count;
1678         rdp->n_cbs_invoked += count;
1679
1680         /* Reinstate batch limit if we have worked down the excess. */
1681         if (rdp->blimit == LONG_MAX && rdp->qlen <= qlowmark)
1682                 rdp->blimit = blimit;
1683
1684         /* Reset ->qlen_last_fqs_check trigger if enough CBs have drained. */
1685         if (rdp->qlen == 0 && rdp->qlen_last_fqs_check != 0) {
1686                 rdp->qlen_last_fqs_check = 0;
1687                 rdp->n_force_qs_snap = rsp->n_force_qs;
1688         } else if (rdp->qlen < rdp->qlen_last_fqs_check - qhimark)
1689                 rdp->qlen_last_fqs_check = rdp->qlen;
1690         WARN_ON_ONCE((rdp->nxtlist == NULL) != (rdp->qlen == 0));
1691
1692         local_irq_restore(flags);
1693
1694         /* Re-invoke RCU core processing if there are callbacks remaining. */
1695         if (cpu_has_callbacks_ready_to_invoke(rdp))
1696                 invoke_rcu_core();
1697 }
1698
1699 /*
1700  * Check to see if this CPU is in a non-context-switch quiescent state
1701  * (user mode or idle loop for rcu, non-softirq execution for rcu_bh).
1702  * Also schedule RCU core processing.
1703  *
1704  * This function must be called from hardirq context.  It is normally
1705  * invoked from the scheduling-clock interrupt.  If rcu_pending returns
1706  * false, there is no point in invoking rcu_check_callbacks().
1707  */
1708 void rcu_check_callbacks(int cpu, int user)
1709 {
1710         trace_rcu_utilization("Start scheduler-tick");
1711         increment_cpu_stall_ticks();
1712         if (user || rcu_is_cpu_rrupt_from_idle()) {
1713
1714                 /*
1715                  * Get here if this CPU took its interrupt from user
1716                  * mode or from the idle loop, and if this is not a
1717                  * nested interrupt.  In this case, the CPU is in
1718                  * a quiescent state, so note it.
1719                  *
1720                  * No memory barrier is required here because both
1721                  * rcu_sched_qs() and rcu_bh_qs() reference only CPU-local
1722                  * variables that other CPUs neither access nor modify,
1723                  * at least not while the corresponding CPU is online.
1724                  */
1725
1726                 rcu_sched_qs(cpu);
1727                 rcu_bh_qs(cpu);
1728
1729         } else if (!in_softirq()) {
1730
1731                 /*
1732                  * Get here if this CPU did not take its interrupt from
1733                  * softirq, in other words, if it is not interrupting
1734                  * a rcu_bh read-side critical section.  This is an _bh
1735                  * critical section, so note it.
1736                  */
1737
1738                 rcu_bh_qs(cpu);
1739         }
1740         rcu_preempt_check_callbacks(cpu);
1741         if (rcu_pending(cpu))
1742                 invoke_rcu_core();
1743         trace_rcu_utilization("End scheduler-tick");
1744 }
1745
1746 /*
1747  * Scan the leaf rcu_node structures, processing dyntick state for any that
1748  * have not yet encountered a quiescent state, using the function specified.
1749  * Also initiate boosting for any threads blocked on the root rcu_node.
1750  *
1751  * The caller must have suppressed start of new grace periods.
1752  */
1753 static void force_qs_rnp(struct rcu_state *rsp, int (*f)(struct rcu_data *))
1754 {
1755         unsigned long bit;
1756         int cpu;
1757         unsigned long flags;
1758         unsigned long mask;
1759         struct rcu_node *rnp;
1760
1761         rcu_for_each_leaf_node(rsp, rnp) {
1762                 cond_resched();
1763                 mask = 0;
1764                 raw_spin_lock_irqsave(&rnp->lock, flags);
1765                 if (!rcu_gp_in_progress(rsp)) {
1766                         raw_spin_unlock_irqrestore(&rnp->lock, flags);
1767                         return;
1768                 }
1769                 if (rnp->qsmask == 0) {
1770                         rcu_initiate_boost(rnp, flags); /* releases rnp->lock */
1771                         continue;
1772                 }
1773                 cpu = rnp->grplo;
1774                 bit = 1;
1775                 for (; cpu <= rnp->grphi; cpu++, bit <<= 1) {
1776                         if ((rnp->qsmask & bit) != 0 &&
1777                             f(per_cpu_ptr(rsp->rda, cpu)))
1778                                 mask |= bit;
1779                 }
1780                 if (mask != 0) {
1781
1782                         /* rcu_report_qs_rnp() releases rnp->lock. */
1783                         rcu_report_qs_rnp(mask, rsp, rnp, flags);
1784                         continue;
1785                 }
1786                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
1787         }
1788         rnp = rcu_get_root(rsp);
1789         if (rnp->qsmask == 0) {
1790                 raw_spin_lock_irqsave(&rnp->lock, flags);
1791                 rcu_initiate_boost(rnp, flags); /* releases rnp->lock. */
1792         }
1793 }
1794
1795 /*
1796  * Force quiescent states on reluctant CPUs, and also detect which
1797  * CPUs are in dyntick-idle mode.
1798  */
1799 static void force_quiescent_state(struct rcu_state *rsp)
1800 {
1801         unsigned long flags;
1802         bool ret;
1803         struct rcu_node *rnp;
1804         struct rcu_node *rnp_old = NULL;
1805
1806         /* Funnel through hierarchy to reduce memory contention. */
1807         rnp = per_cpu_ptr(rsp->rda, raw_smp_processor_id())->mynode;
1808         for (; rnp != NULL; rnp = rnp->parent) {
1809                 ret = (ACCESS_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) ||
1810                       !raw_spin_trylock(&rnp->fqslock);
1811                 if (rnp_old != NULL)
1812                         raw_spin_unlock(&rnp_old->fqslock);
1813                 if (ret) {
1814                         rsp->n_force_qs_lh++;
1815                         return;
1816                 }
1817                 rnp_old = rnp;
1818         }
1819         /* rnp_old == rcu_get_root(rsp), rnp == NULL. */
1820
1821         /* Reached the root of the rcu_node tree, acquire lock. */
1822         raw_spin_lock_irqsave(&rnp_old->lock, flags);
1823         raw_spin_unlock(&rnp_old->fqslock);
1824         if (ACCESS_ONCE(rsp->gp_flags) & RCU_GP_FLAG_FQS) {
1825                 rsp->n_force_qs_lh++;
1826                 raw_spin_unlock_irqrestore(&rnp_old->lock, flags);
1827                 return;  /* Someone beat us to it. */
1828         }
1829         rsp->gp_flags |= RCU_GP_FLAG_FQS;
1830         raw_spin_unlock_irqrestore(&rnp_old->lock, flags);
1831         wake_up(&rsp->gp_wq);  /* Memory barrier implied by wake_up() path. */
1832 }
1833
1834 /*
1835  * This does the RCU core processing work for the specified rcu_state
1836  * and rcu_data structures.  This may be called only from the CPU to
1837  * whom the rdp belongs.
1838  */
1839 static void
1840 __rcu_process_callbacks(struct rcu_state *rsp)
1841 {
1842         unsigned long flags;
1843         struct rcu_data *rdp = __this_cpu_ptr(rsp->rda);
1844
1845         WARN_ON_ONCE(rdp->beenonline == 0);
1846
1847         /*
1848          * Advance callbacks in response to end of earlier grace
1849          * period that some other CPU ended.
1850          */
1851         rcu_process_gp_end(rsp, rdp);
1852
1853         /* Update RCU state based on any recent quiescent states. */
1854         rcu_check_quiescent_state(rsp, rdp);
1855
1856         /* Does this CPU require a not-yet-started grace period? */
1857         if (cpu_needs_another_gp(rsp, rdp)) {
1858                 raw_spin_lock_irqsave(&rcu_get_root(rsp)->lock, flags);
1859                 rcu_start_gp(rsp, flags);  /* releases above lock */
1860         }
1861
1862         /* If there are callbacks ready, invoke them. */
1863         if (cpu_has_callbacks_ready_to_invoke(rdp))
1864                 invoke_rcu_callbacks(rsp, rdp);
1865 }
1866
1867 /*
1868  * Do RCU core processing for the current CPU.
1869  */
1870 static void rcu_process_callbacks(struct softirq_action *unused)
1871 {
1872         struct rcu_state *rsp;
1873
1874         if (cpu_is_offline(smp_processor_id()))
1875                 return;
1876         trace_rcu_utilization("Start RCU core");
1877         for_each_rcu_flavor(rsp)
1878                 __rcu_process_callbacks(rsp);
1879         trace_rcu_utilization("End RCU core");
1880 }
1881
1882 /*
1883  * Schedule RCU callback invocation.  If the specified type of RCU
1884  * does not support RCU priority boosting, just do a direct call,
1885  * otherwise wake up the per-CPU kernel kthread.  Note that because we
1886  * are running on the current CPU with interrupts disabled, the
1887  * rcu_cpu_kthread_task cannot disappear out from under us.
1888  */
1889 static void invoke_rcu_callbacks(struct rcu_state *rsp, struct rcu_data *rdp)
1890 {
1891         if (unlikely(!ACCESS_ONCE(rcu_scheduler_fully_active)))
1892                 return;
1893         if (likely(!rsp->boost)) {
1894                 rcu_do_batch(rsp, rdp);
1895                 return;
1896         }
1897         invoke_rcu_callbacks_kthread();
1898 }
1899
1900 static void invoke_rcu_core(void)
1901 {
1902         raise_softirq(RCU_SOFTIRQ);
1903 }
1904
1905 /*
1906  * Handle any core-RCU processing required by a call_rcu() invocation.
1907  */
1908 static void __call_rcu_core(struct rcu_state *rsp, struct rcu_data *rdp,
1909                             struct rcu_head *head, unsigned long flags)
1910 {
1911         /*
1912          * If called from an extended quiescent state, invoke the RCU
1913          * core in order to force a re-evaluation of RCU's idleness.
1914          */
1915         if (rcu_is_cpu_idle() && cpu_online(smp_processor_id()))
1916                 invoke_rcu_core();
1917
1918         /* If interrupts were disabled or CPU offline, don't invoke RCU core. */
1919         if (irqs_disabled_flags(flags) || cpu_is_offline(smp_processor_id()))
1920                 return;
1921
1922         /*
1923          * Force the grace period if too many callbacks or too long waiting.
1924          * Enforce hysteresis, and don't invoke force_quiescent_state()
1925          * if some other CPU has recently done so.  Also, don't bother
1926          * invoking force_quiescent_state() if the newly enqueued callback
1927          * is the only one waiting for a grace period to complete.
1928          */
1929         if (unlikely(rdp->qlen > rdp->qlen_last_fqs_check + qhimark)) {
1930
1931                 /* Are we ignoring a completed grace period? */
1932                 rcu_process_gp_end(rsp, rdp);
1933                 check_for_new_grace_period(rsp, rdp);
1934
1935                 /* Start a new grace period if one not already started. */
1936                 if (!rcu_gp_in_progress(rsp)) {
1937                         unsigned long nestflag;
1938                         struct rcu_node *rnp_root = rcu_get_root(rsp);
1939
1940                         raw_spin_lock_irqsave(&rnp_root->lock, nestflag);
1941                         rcu_start_gp(rsp, nestflag);  /* rlses rnp_root->lock */
1942                 } else {
1943                         /* Give the grace period a kick. */
1944                         rdp->blimit = LONG_MAX;
1945                         if (rsp->n_force_qs == rdp->n_force_qs_snap &&
1946                             *rdp->nxttail[RCU_DONE_TAIL] != head)
1947                                 force_quiescent_state(rsp);
1948                         rdp->n_force_qs_snap = rsp->n_force_qs;
1949                         rdp->qlen_last_fqs_check = rdp->qlen;
1950                 }
1951         }
1952 }
1953
1954 static void
1955 __call_rcu(struct rcu_head *head, void (*func)(struct rcu_head *rcu),
1956            struct rcu_state *rsp, bool lazy)
1957 {
1958         unsigned long flags;
1959         struct rcu_data *rdp;
1960
1961         WARN_ON_ONCE((unsigned long)head & 0x3); /* Misaligned rcu_head! */
1962         debug_rcu_head_queue(head);
1963         head->func = func;
1964         head->next = NULL;
1965
1966         /*
1967          * Opportunistically note grace-period endings and beginnings.
1968          * Note that we might see a beginning right after we see an
1969          * end, but never vice versa, since this CPU has to pass through
1970          * a quiescent state betweentimes.
1971          */
1972         local_irq_save(flags);
1973         rdp = this_cpu_ptr(rsp->rda);
1974
1975         /* Add the callback to our list. */
1976         if (unlikely(rdp->nxttail[RCU_NEXT_TAIL] == NULL)) {
1977                 /* _call_rcu() is illegal on offline CPU; leak the callback. */
1978                 WARN_ON_ONCE(1);
1979                 local_irq_restore(flags);
1980                 return;
1981         }
1982         ACCESS_ONCE(rdp->qlen)++;
1983         if (lazy)
1984                 rdp->qlen_lazy++;
1985         else
1986                 rcu_idle_count_callbacks_posted();
1987         smp_mb();  /* Count before adding callback for rcu_barrier(). */
1988         *rdp->nxttail[RCU_NEXT_TAIL] = head;
1989         rdp->nxttail[RCU_NEXT_TAIL] = &head->next;
1990
1991         if (__is_kfree_rcu_offset((unsigned long)func))
1992                 trace_rcu_kfree_callback(rsp->name, head, (unsigned long)func,
1993                                          rdp->qlen_lazy, rdp->qlen);
1994         else
1995                 trace_rcu_callback(rsp->name, head, rdp->qlen_lazy, rdp->qlen);
1996
1997         /* Go handle any RCU core processing required. */
1998         __call_rcu_core(rsp, rdp, head, flags);
1999         local_irq_restore(flags);
2000 }
2001
2002 /*
2003  * Queue an RCU-sched callback for invocation after a grace period.
2004  */
2005 void call_rcu_sched(struct rcu_head *head, void (*func)(struct rcu_head *rcu))
2006 {
2007         __call_rcu(head, func, &rcu_sched_state, 0);
2008 }
2009 EXPORT_SYMBOL_GPL(call_rcu_sched);
2010
2011 /*
2012  * Queue an RCU callback for invocation after a quicker grace period.
2013  */
2014 void call_rcu_bh(struct rcu_head *head, void (*func)(struct rcu_head *rcu))
2015 {
2016         __call_rcu(head, func, &rcu_bh_state, 0);
2017 }
2018 EXPORT_SYMBOL_GPL(call_rcu_bh);
2019
2020 /*
2021  * Because a context switch is a grace period for RCU-sched and RCU-bh,
2022  * any blocking grace-period wait automatically implies a grace period
2023  * if there is only one CPU online at any point time during execution
2024  * of either synchronize_sched() or synchronize_rcu_bh().  It is OK to
2025  * occasionally incorrectly indicate that there are multiple CPUs online
2026  * when there was in fact only one the whole time, as this just adds
2027  * some overhead: RCU still operates correctly.
2028  */
2029 static inline int rcu_blocking_is_gp(void)
2030 {
2031         int ret;
2032
2033         might_sleep();  /* Check for RCU read-side critical section. */
2034         preempt_disable();
2035         ret = num_online_cpus() <= 1;
2036         preempt_enable();
2037         return ret;
2038 }
2039
2040 /**
2041  * synchronize_sched - wait until an rcu-sched grace period has elapsed.
2042  *
2043  * Control will return to the caller some time after a full rcu-sched
2044  * grace period has elapsed, in other words after all currently executing
2045  * rcu-sched read-side critical sections have completed.   These read-side
2046  * critical sections are delimited by rcu_read_lock_sched() and
2047  * rcu_read_unlock_sched(), and may be nested.  Note that preempt_disable(),
2048  * local_irq_disable(), and so on may be used in place of
2049  * rcu_read_lock_sched().
2050  *
2051  * This means that all preempt_disable code sequences, including NMI and
2052  * hardware-interrupt handlers, in progress on entry will have completed
2053  * before this primitive returns.  However, this does not guarantee that
2054  * softirq handlers will have completed, since in some kernels, these
2055  * handlers can run in process context, and can block.
2056  *
2057  * This primitive provides the guarantees made by the (now removed)
2058  * synchronize_kernel() API.  In contrast, synchronize_rcu() only
2059  * guarantees that rcu_read_lock() sections will have completed.
2060  * In "classic RCU", these two guarantees happen to be one and
2061  * the same, but can differ in realtime RCU implementations.
2062  */
2063 void synchronize_sched(void)
2064 {
2065         rcu_lockdep_assert(!lock_is_held(&rcu_bh_lock_map) &&
2066                            !lock_is_held(&rcu_lock_map) &&
2067                            !lock_is_held(&rcu_sched_lock_map),
2068                            "Illegal synchronize_sched() in RCU-sched read-side critical section");
2069         if (rcu_blocking_is_gp())
2070                 return;
2071         wait_rcu_gp(call_rcu_sched);
2072 }
2073 EXPORT_SYMBOL_GPL(synchronize_sched);
2074
2075 /**
2076  * synchronize_rcu_bh - wait until an rcu_bh grace period has elapsed.
2077  *
2078  * Control will return to the caller some time after a full rcu_bh grace
2079  * period has elapsed, in other words after all currently executing rcu_bh
2080  * read-side critical sections have completed.  RCU read-side critical
2081  * sections are delimited by rcu_read_lock_bh() and rcu_read_unlock_bh(),
2082  * and may be nested.
2083  */
2084 void synchronize_rcu_bh(void)
2085 {
2086         rcu_lockdep_assert(!lock_is_held(&rcu_bh_lock_map) &&
2087                            !lock_is_held(&rcu_lock_map) &&
2088                            !lock_is_held(&rcu_sched_lock_map),
2089                            "Illegal synchronize_rcu_bh() in RCU-bh read-side critical section");
2090         if (rcu_blocking_is_gp())
2091                 return;
2092         wait_rcu_gp(call_rcu_bh);
2093 }
2094 EXPORT_SYMBOL_GPL(synchronize_rcu_bh);
2095
2096 static atomic_t sync_sched_expedited_started = ATOMIC_INIT(0);
2097 static atomic_t sync_sched_expedited_done = ATOMIC_INIT(0);
2098
2099 static int synchronize_sched_expedited_cpu_stop(void *data)
2100 {
2101         /*
2102          * There must be a full memory barrier on each affected CPU
2103          * between the time that try_stop_cpus() is called and the
2104          * time that it returns.
2105          *
2106          * In the current initial implementation of cpu_stop, the
2107          * above condition is already met when the control reaches
2108          * this point and the following smp_mb() is not strictly
2109          * necessary.  Do smp_mb() anyway for documentation and
2110          * robustness against future implementation changes.
2111          */
2112         smp_mb(); /* See above comment block. */
2113         return 0;
2114 }
2115
2116 /**
2117  * synchronize_sched_expedited - Brute-force RCU-sched grace period
2118  *
2119  * Wait for an RCU-sched grace period to elapse, but use a "big hammer"
2120  * approach to force the grace period to end quickly.  This consumes
2121  * significant time on all CPUs and is unfriendly to real-time workloads,
2122  * so is thus not recommended for any sort of common-case code.  In fact,
2123  * if you are using synchronize_sched_expedited() in a loop, please
2124  * restructure your code to batch your updates, and then use a single
2125  * synchronize_sched() instead.
2126  *
2127  * Note that it is illegal to call this function while holding any lock
2128  * that is acquired by a CPU-hotplug notifier.  And yes, it is also illegal
2129  * to call this function from a CPU-hotplug notifier.  Failing to observe
2130  * these restriction will result in deadlock.
2131  *
2132  * This implementation can be thought of as an application of ticket
2133  * locking to RCU, with sync_sched_expedited_started and
2134  * sync_sched_expedited_done taking on the roles of the halves
2135  * of the ticket-lock word.  Each task atomically increments
2136  * sync_sched_expedited_started upon entry, snapshotting the old value,
2137  * then attempts to stop all the CPUs.  If this succeeds, then each
2138  * CPU will have executed a context switch, resulting in an RCU-sched
2139  * grace period.  We are then done, so we use atomic_cmpxchg() to
2140  * update sync_sched_expedited_done to match our snapshot -- but
2141  * only if someone else has not already advanced past our snapshot.
2142  *
2143  * On the other hand, if try_stop_cpus() fails, we check the value
2144  * of sync_sched_expedited_done.  If it has advanced past our
2145  * initial snapshot, then someone else must have forced a grace period
2146  * some time after we took our snapshot.  In this case, our work is
2147  * done for us, and we can simply return.  Otherwise, we try again,
2148  * but keep our initial snapshot for purposes of checking for someone
2149  * doing our work for us.
2150  *
2151  * If we fail too many times in a row, we fall back to synchronize_sched().
2152  */
2153 void synchronize_sched_expedited(void)
2154 {
2155         int firstsnap, s, snap, trycount = 0;
2156
2157         /* Note that atomic_inc_return() implies full memory barrier. */
2158         firstsnap = snap = atomic_inc_return(&sync_sched_expedited_started);
2159         get_online_cpus();
2160         WARN_ON_ONCE(cpu_is_offline(raw_smp_processor_id()));
2161
2162         /*
2163          * Each pass through the following loop attempts to force a
2164          * context switch on each CPU.
2165          */
2166         while (try_stop_cpus(cpu_online_mask,
2167                              synchronize_sched_expedited_cpu_stop,
2168                              NULL) == -EAGAIN) {
2169                 put_online_cpus();
2170
2171                 /* No joy, try again later.  Or just synchronize_sched(). */
2172                 if (trycount++ < 10) {
2173                         udelay(trycount * num_online_cpus());
2174                 } else {
2175                         synchronize_sched();
2176                         return;
2177                 }
2178
2179                 /* Check to see if someone else did our work for us. */
2180                 s = atomic_read(&sync_sched_expedited_done);
2181                 if (UINT_CMP_GE((unsigned)s, (unsigned)firstsnap)) {
2182                         smp_mb(); /* ensure test happens before caller kfree */
2183                         return;
2184                 }
2185
2186                 /*
2187                  * Refetching sync_sched_expedited_started allows later
2188                  * callers to piggyback on our grace period.  We subtract
2189                  * 1 to get the same token that the last incrementer got.
2190                  * We retry after they started, so our grace period works
2191                  * for them, and they started after our first try, so their
2192                  * grace period works for us.
2193                  */
2194                 get_online_cpus();
2195                 snap = atomic_read(&sync_sched_expedited_started);
2196                 smp_mb(); /* ensure read is before try_stop_cpus(). */
2197         }
2198
2199         /*
2200          * Everyone up to our most recent fetch is covered by our grace
2201          * period.  Update the counter, but only if our work is still
2202          * relevant -- which it won't be if someone who started later
2203          * than we did beat us to the punch.
2204          */
2205         do {
2206                 s = atomic_read(&sync_sched_expedited_done);
2207                 if (UINT_CMP_GE((unsigned)s, (unsigned)snap)) {
2208                         smp_mb(); /* ensure test happens before caller kfree */
2209                         break;
2210                 }
2211         } while (atomic_cmpxchg(&sync_sched_expedited_done, s, snap) != s);
2212
2213         put_online_cpus();
2214 }
2215 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
2216
2217 /*
2218  * Check to see if there is any immediate RCU-related work to be done
2219  * by the current CPU, for the specified type of RCU, returning 1 if so.
2220  * The checks are in order of increasing expense: checks that can be
2221  * carried out against CPU-local state are performed first.  However,
2222  * we must check for CPU stalls first, else we might not get a chance.
2223  */
2224 static int __rcu_pending(struct rcu_state *rsp, struct rcu_data *rdp)
2225 {
2226         struct rcu_node *rnp = rdp->mynode;
2227
2228         rdp->n_rcu_pending++;
2229
2230         /* Check for CPU stalls, if enabled. */
2231         check_cpu_stall(rsp, rdp);
2232
2233         /* Is the RCU core waiting for a quiescent state from this CPU? */
2234         if (rcu_scheduler_fully_active &&
2235             rdp->qs_pending && !rdp->passed_quiesce) {
2236                 rdp->n_rp_qs_pending++;
2237         } else if (rdp->qs_pending && rdp->passed_quiesce) {
2238                 rdp->n_rp_report_qs++;
2239                 return 1;
2240         }
2241
2242         /* Does this CPU have callbacks ready to invoke? */
2243         if (cpu_has_callbacks_ready_to_invoke(rdp)) {
2244                 rdp->n_rp_cb_ready++;
2245                 return 1;
2246         }
2247
2248         /* Has RCU gone idle with this CPU needing another grace period? */
2249         if (cpu_needs_another_gp(rsp, rdp)) {
2250                 rdp->n_rp_cpu_needs_gp++;
2251                 return 1;
2252         }
2253
2254         /* Has another RCU grace period completed?  */
2255         if (ACCESS_ONCE(rnp->completed) != rdp->completed) { /* outside lock */
2256                 rdp->n_rp_gp_completed++;
2257                 return 1;
2258         }
2259
2260         /* Has a new RCU grace period started? */
2261         if (ACCESS_ONCE(rnp->gpnum) != rdp->gpnum) { /* outside lock */
2262                 rdp->n_rp_gp_started++;
2263                 return 1;
2264         }
2265
2266         /* nothing to do */
2267         rdp->n_rp_need_nothing++;
2268         return 0;
2269 }
2270
2271 /*
2272  * Check to see if there is any immediate RCU-related work to be done
2273  * by the current CPU, returning 1 if so.  This function is part of the
2274  * RCU implementation; it is -not- an exported member of the RCU API.
2275  */
2276 static int rcu_pending(int cpu)
2277 {
2278         struct rcu_state *rsp;
2279
2280         for_each_rcu_flavor(rsp)
2281                 if (__rcu_pending(rsp, per_cpu_ptr(rsp->rda, cpu)))
2282                         return 1;
2283         return 0;
2284 }
2285
2286 /*
2287  * Check to see if any future RCU-related work will need to be done
2288  * by the current CPU, even if none need be done immediately, returning
2289  * 1 if so.
2290  */
2291 static int rcu_cpu_has_callbacks(int cpu)
2292 {
2293         struct rcu_state *rsp;
2294
2295         /* RCU callbacks either ready or pending? */
2296         for_each_rcu_flavor(rsp)
2297                 if (per_cpu_ptr(rsp->rda, cpu)->nxtlist)
2298                         return 1;
2299         return 0;
2300 }
2301
2302 /*
2303  * Helper function for _rcu_barrier() tracing.  If tracing is disabled,
2304  * the compiler is expected to optimize this away.
2305  */
2306 static void _rcu_barrier_trace(struct rcu_state *rsp, char *s,
2307                                int cpu, unsigned long done)
2308 {
2309         trace_rcu_barrier(rsp->name, s, cpu,
2310                           atomic_read(&rsp->barrier_cpu_count), done);
2311 }
2312
2313 /*
2314  * RCU callback function for _rcu_barrier().  If we are last, wake
2315  * up the task executing _rcu_barrier().
2316  */
2317 static void rcu_barrier_callback(struct rcu_head *rhp)
2318 {
2319         struct rcu_data *rdp = container_of(rhp, struct rcu_data, barrier_head);
2320         struct rcu_state *rsp = rdp->rsp;
2321
2322         if (atomic_dec_and_test(&rsp->barrier_cpu_count)) {
2323                 _rcu_barrier_trace(rsp, "LastCB", -1, rsp->n_barrier_done);
2324                 complete(&rsp->barrier_completion);
2325         } else {
2326                 _rcu_barrier_trace(rsp, "CB", -1, rsp->n_barrier_done);
2327         }
2328 }
2329
2330 /*
2331  * Called with preemption disabled, and from cross-cpu IRQ context.
2332  */
2333 static void rcu_barrier_func(void *type)
2334 {
2335         struct rcu_state *rsp = type;
2336         struct rcu_data *rdp = __this_cpu_ptr(rsp->rda);
2337
2338         _rcu_barrier_trace(rsp, "IRQ", -1, rsp->n_barrier_done);
2339         atomic_inc(&rsp->barrier_cpu_count);
2340         rsp->call(&rdp->barrier_head, rcu_barrier_callback);
2341 }
2342
2343 /*
2344  * Orchestrate the specified type of RCU barrier, waiting for all
2345  * RCU callbacks of the specified type to complete.
2346  */
2347 static void _rcu_barrier(struct rcu_state *rsp)
2348 {
2349         int cpu;
2350         struct rcu_data *rdp;
2351         unsigned long snap = ACCESS_ONCE(rsp->n_barrier_done);
2352         unsigned long snap_done;
2353
2354         _rcu_barrier_trace(rsp, "Begin", -1, snap);
2355
2356         /* Take mutex to serialize concurrent rcu_barrier() requests. */
2357         mutex_lock(&rsp->barrier_mutex);
2358
2359         /*
2360          * Ensure that all prior references, including to ->n_barrier_done,
2361          * are ordered before the _rcu_barrier() machinery.
2362          */
2363         smp_mb();  /* See above block comment. */
2364
2365         /*
2366          * Recheck ->n_barrier_done to see if others did our work for us.
2367          * This means checking ->n_barrier_done for an even-to-odd-to-even
2368          * transition.  The "if" expression below therefore rounds the old
2369          * value up to the next even number and adds two before comparing.
2370          */
2371         snap_done = ACCESS_ONCE(rsp->n_barrier_done);
2372         _rcu_barrier_trace(rsp, "Check", -1, snap_done);
2373         if (ULONG_CMP_GE(snap_done, ((snap + 1) & ~0x1) + 2)) {
2374                 _rcu_barrier_trace(rsp, "EarlyExit", -1, snap_done);
2375                 smp_mb(); /* caller's subsequent code after above check. */
2376                 mutex_unlock(&rsp->barrier_mutex);
2377                 return;
2378         }
2379
2380         /*
2381          * Increment ->n_barrier_done to avoid duplicate work.  Use
2382          * ACCESS_ONCE() to prevent the compiler from speculating
2383          * the increment to precede the early-exit check.
2384          */
2385         ACCESS_ONCE(rsp->n_barrier_done)++;
2386         WARN_ON_ONCE((rsp->n_barrier_done & 0x1) != 1);
2387         _rcu_barrier_trace(rsp, "Inc1", -1, rsp->n_barrier_done);
2388         smp_mb(); /* Order ->n_barrier_done increment with below mechanism. */
2389
2390         /*
2391          * Initialize the count to one rather than to zero in order to
2392          * avoid a too-soon return to zero in case of a short grace period
2393          * (or preemption of this task).  Exclude CPU-hotplug operations
2394          * to ensure that no offline CPU has callbacks queued.
2395          */
2396         init_completion(&rsp->barrier_completion);
2397         atomic_set(&rsp->barrier_cpu_count, 1);
2398         get_online_cpus();
2399
2400         /*
2401          * Force each CPU with callbacks to register a new callback.
2402          * When that callback is invoked, we will know that all of the
2403          * corresponding CPU's preceding callbacks have been invoked.
2404          */
2405         for_each_online_cpu(cpu) {
2406                 rdp = per_cpu_ptr(rsp->rda, cpu);
2407                 if (ACCESS_ONCE(rdp->qlen)) {
2408                         _rcu_barrier_trace(rsp, "OnlineQ", cpu,
2409                                            rsp->n_barrier_done);
2410                         smp_call_function_single(cpu, rcu_barrier_func, rsp, 1);
2411                 } else {
2412                         _rcu_barrier_trace(rsp, "OnlineNQ", cpu,
2413                                            rsp->n_barrier_done);
2414                 }
2415         }
2416         put_online_cpus();
2417
2418         /*
2419          * Now that we have an rcu_barrier_callback() callback on each
2420          * CPU, and thus each counted, remove the initial count.
2421          */
2422         if (atomic_dec_and_test(&rsp->barrier_cpu_count))
2423                 complete(&rsp->barrier_completion);
2424
2425         /* Increment ->n_barrier_done to prevent duplicate work. */
2426         smp_mb(); /* Keep increment after above mechanism. */
2427         ACCESS_ONCE(rsp->n_barrier_done)++;
2428         WARN_ON_ONCE((rsp->n_barrier_done & 0x1) != 0);
2429         _rcu_barrier_trace(rsp, "Inc2", -1, rsp->n_barrier_done);
2430         smp_mb(); /* Keep increment before caller's subsequent code. */
2431
2432         /* Wait for all rcu_barrier_callback() callbacks to be invoked. */
2433         wait_for_completion(&rsp->barrier_completion);
2434
2435         /* Other rcu_barrier() invocations can now safely proceed. */
2436         mutex_unlock(&rsp->barrier_mutex);
2437 }
2438
2439 /**
2440  * rcu_barrier_bh - Wait until all in-flight call_rcu_bh() callbacks complete.
2441  */
2442 void rcu_barrier_bh(void)
2443 {
2444         _rcu_barrier(&rcu_bh_state);
2445 }
2446 EXPORT_SYMBOL_GPL(rcu_barrier_bh);
2447
2448 /**
2449  * rcu_barrier_sched - Wait for in-flight call_rcu_sched() callbacks.
2450  */
2451 void rcu_barrier_sched(void)
2452 {
2453         _rcu_barrier(&rcu_sched_state);
2454 }
2455 EXPORT_SYMBOL_GPL(rcu_barrier_sched);
2456
2457 /*
2458  * Do boot-time initialization of a CPU's per-CPU RCU data.
2459  */
2460 static void __init
2461 rcu_boot_init_percpu_data(int cpu, struct rcu_state *rsp)
2462 {
2463         unsigned long flags;
2464         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
2465         struct rcu_node *rnp = rcu_get_root(rsp);
2466
2467         /* Set up local state, ensuring consistent view of global state. */
2468         raw_spin_lock_irqsave(&rnp->lock, flags);
2469         rdp->grpmask = 1UL << (cpu - rdp->mynode->grplo);
2470         init_callback_list(rdp);
2471         rdp->qlen_lazy = 0;
2472         ACCESS_ONCE(rdp->qlen) = 0;
2473         rdp->dynticks = &per_cpu(rcu_dynticks, cpu);
2474         WARN_ON_ONCE(rdp->dynticks->dynticks_nesting != DYNTICK_TASK_EXIT_IDLE);
2475         WARN_ON_ONCE(atomic_read(&rdp->dynticks->dynticks) != 1);
2476         rdp->cpu = cpu;
2477         rdp->rsp = rsp;
2478         raw_spin_unlock_irqrestore(&rnp->lock, flags);
2479 }
2480
2481 /*
2482  * Initialize a CPU's per-CPU RCU data.  Note that only one online or
2483  * offline event can be happening at a given time.  Note also that we
2484  * can accept some slop in the rsp->completed access due to the fact
2485  * that this CPU cannot possibly have any RCU callbacks in flight yet.
2486  */
2487 static void __cpuinit
2488 rcu_init_percpu_data(int cpu, struct rcu_state *rsp, int preemptible)
2489 {
2490         unsigned long flags;
2491         unsigned long mask;
2492         struct rcu_data *rdp = per_cpu_ptr(rsp->rda, cpu);
2493         struct rcu_node *rnp = rcu_get_root(rsp);
2494
2495         /* Set up local state, ensuring consistent view of global state. */
2496         raw_spin_lock_irqsave(&rnp->lock, flags);
2497         rdp->beenonline = 1;     /* We have now been online. */
2498         rdp->preemptible = preemptible;
2499         rdp->qlen_last_fqs_check = 0;
2500         rdp->n_force_qs_snap = rsp->n_force_qs;
2501         rdp->blimit = blimit;
2502         init_callback_list(rdp);  /* Re-enable callbacks on this CPU. */
2503         rdp->dynticks->dynticks_nesting = DYNTICK_TASK_EXIT_IDLE;
2504         atomic_set(&rdp->dynticks->dynticks,
2505                    (atomic_read(&rdp->dynticks->dynticks) & ~0x1) + 1);
2506         rcu_prepare_for_idle_init(cpu);
2507         raw_spin_unlock(&rnp->lock);            /* irqs remain disabled. */
2508
2509         /*
2510          * A new grace period might start here.  If so, we won't be part
2511          * of it, but that is OK, as we are currently in a quiescent state.
2512          */
2513
2514         /* Exclude any attempts to start a new GP on large systems. */
2515         raw_spin_lock(&rsp->onofflock);         /* irqs already disabled. */
2516
2517         /* Add CPU to rcu_node bitmasks. */
2518         rnp = rdp->mynode;
2519         mask = rdp->grpmask;
2520         do {
2521                 /* Exclude any attempts to start a new GP on small systems. */
2522                 raw_spin_lock(&rnp->lock);      /* irqs already disabled. */
2523                 rnp->qsmaskinit |= mask;
2524                 mask = rnp->grpmask;
2525                 if (rnp == rdp->mynode) {
2526                         /*
2527                          * If there is a grace period in progress, we will
2528                          * set up to wait for it next time we run the
2529                          * RCU core code.
2530                          */
2531                         rdp->gpnum = rnp->completed;
2532                         rdp->completed = rnp->completed;
2533                         rdp->passed_quiesce = 0;
2534                         rdp->qs_pending = 0;
2535                         trace_rcu_grace_period(rsp->name, rdp->gpnum, "cpuonl");
2536                 }
2537                 raw_spin_unlock(&rnp->lock); /* irqs already disabled. */
2538                 rnp = rnp->parent;
2539         } while (rnp != NULL && !(rnp->qsmaskinit & mask));
2540
2541         raw_spin_unlock_irqrestore(&rsp->onofflock, flags);
2542 }
2543
2544 static void __cpuinit rcu_prepare_cpu(int cpu)
2545 {
2546         struct rcu_state *rsp;
2547
2548         for_each_rcu_flavor(rsp)
2549                 rcu_init_percpu_data(cpu, rsp,
2550                                      strcmp(rsp->name, "rcu_preempt") == 0);
2551 }
2552
2553 /*
2554  * Handle CPU online/offline notification events.
2555  */
2556 static int __cpuinit rcu_cpu_notify(struct notifier_block *self,
2557                                     unsigned long action, void *hcpu)
2558 {
2559         long cpu = (long)hcpu;
2560         struct rcu_data *rdp = per_cpu_ptr(rcu_state->rda, cpu);
2561         struct rcu_node *rnp = rdp->mynode;
2562         struct rcu_state *rsp;
2563
2564         trace_rcu_utilization("Start CPU hotplug");
2565         switch (action) {
2566         case CPU_UP_PREPARE:
2567         case CPU_UP_PREPARE_FROZEN:
2568                 rcu_prepare_cpu(cpu);
2569                 rcu_prepare_kthreads(cpu);
2570                 break;
2571         case CPU_ONLINE:
2572         case CPU_DOWN_FAILED:
2573                 rcu_boost_kthread_setaffinity(rnp, -1);
2574                 break;
2575         case CPU_DOWN_PREPARE:
2576                 rcu_boost_kthread_setaffinity(rnp, cpu);
2577                 break;
2578         case CPU_DYING:
2579         case CPU_DYING_FROZEN:
2580                 /*
2581                  * The whole machine is "stopped" except this CPU, so we can
2582                  * touch any data without introducing corruption. We send the
2583                  * dying CPU's callbacks to an arbitrarily chosen online CPU.
2584                  */
2585                 for_each_rcu_flavor(rsp)
2586                         rcu_cleanup_dying_cpu(rsp);
2587                 rcu_cleanup_after_idle(cpu);
2588                 break;
2589         case CPU_DEAD:
2590         case CPU_DEAD_FROZEN:
2591         case CPU_UP_CANCELED:
2592         case CPU_UP_CANCELED_FROZEN:
2593                 for_each_rcu_flavor(rsp)
2594                         rcu_cleanup_dead_cpu(cpu, rsp);
2595                 break;
2596         default:
2597                 break;
2598         }
2599         trace_rcu_utilization("End CPU hotplug");
2600         return NOTIFY_OK;
2601 }
2602
2603 /*
2604  * Spawn the kthread that handles this RCU flavor's grace periods.
2605  */
2606 static int __init rcu_spawn_gp_kthread(void)
2607 {
2608         unsigned long flags;
2609         struct rcu_node *rnp;
2610         struct rcu_state *rsp;
2611         struct task_struct *t;
2612
2613         for_each_rcu_flavor(rsp) {
2614                 t = kthread_run(rcu_gp_kthread, rsp, rsp->name);
2615                 BUG_ON(IS_ERR(t));
2616                 rnp = rcu_get_root(rsp);
2617                 raw_spin_lock_irqsave(&rnp->lock, flags);
2618                 rsp->gp_kthread = t;
2619                 raw_spin_unlock_irqrestore(&rnp->lock, flags);
2620         }
2621         return 0;
2622 }
2623 early_initcall(rcu_spawn_gp_kthread);
2624
2625 /*
2626  * This function is invoked towards the end of the scheduler's initialization
2627  * process.  Before this is called, the idle task might contain
2628  * RCU read-side critical sections (during which time, this idle
2629  * task is booting the system).  After this function is called, the
2630  * idle tasks are prohibited from containing RCU read-side critical
2631  * sections.  This function also enables RCU lockdep checking.
2632  */
2633 void rcu_scheduler_starting(void)
2634 {
2635         WARN_ON(num_online_cpus() != 1);
2636         WARN_ON(nr_context_switches() > 0);
2637         rcu_scheduler_active = 1;
2638 }
2639
2640 /*
2641  * Compute the per-level fanout, either using the exact fanout specified
2642  * or balancing the tree, depending on CONFIG_RCU_FANOUT_EXACT.
2643  */
2644 #ifdef CONFIG_RCU_FANOUT_EXACT
2645 static void __init rcu_init_levelspread(struct rcu_state *rsp)
2646 {
2647         int i;
2648
2649         for (i = rcu_num_lvls - 1; i > 0; i--)
2650                 rsp->levelspread[i] = CONFIG_RCU_FANOUT;
2651         rsp->levelspread[0] = rcu_fanout_leaf;
2652 }
2653 #else /* #ifdef CONFIG_RCU_FANOUT_EXACT */
2654 static void __init rcu_init_levelspread(struct rcu_state *rsp)
2655 {
2656         int ccur;
2657         int cprv;
2658         int i;
2659
2660         cprv = nr_cpu_ids;
2661         for (i = rcu_num_lvls - 1; i >= 0; i--) {
2662                 ccur = rsp->levelcnt[i];
2663                 rsp->levelspread[i] = (cprv + ccur - 1) / ccur;
2664                 cprv = ccur;
2665         }
2666 }
2667 #endif /* #else #ifdef CONFIG_RCU_FANOUT_EXACT */
2668
2669 /*
2670  * Helper function for rcu_init() that initializes one rcu_state structure.
2671  */
2672 static void __init rcu_init_one(struct rcu_state *rsp,
2673                 struct rcu_data __percpu *rda)
2674 {
2675         static char *buf[] = { "rcu_node_0",
2676                                "rcu_node_1",
2677                                "rcu_node_2",
2678                                "rcu_node_3" };  /* Match MAX_RCU_LVLS */
2679         static char *fqs[] = { "rcu_node_fqs_0",
2680                                "rcu_node_fqs_1",
2681                                "rcu_node_fqs_2",
2682                                "rcu_node_fqs_3" };  /* Match MAX_RCU_LVLS */
2683         int cpustride = 1;
2684         int i;
2685         int j;
2686         struct rcu_node *rnp;
2687
2688         BUILD_BUG_ON(MAX_RCU_LVLS > ARRAY_SIZE(buf));  /* Fix buf[] init! */
2689
2690         /* Initialize the level-tracking arrays. */
2691
2692         for (i = 0; i < rcu_num_lvls; i++)
2693                 rsp->levelcnt[i] = num_rcu_lvl[i];
2694         for (i = 1; i < rcu_num_lvls; i++)
2695                 rsp->level[i] = rsp->level[i - 1] + rsp->levelcnt[i - 1];
2696         rcu_init_levelspread(rsp);
2697
2698         /* Initialize the elements themselves, starting from the leaves. */
2699
2700         for (i = rcu_num_lvls - 1; i >= 0; i--) {
2701                 cpustride *= rsp->levelspread[i];
2702                 rnp = rsp->level[i];
2703                 for (j = 0; j < rsp->levelcnt[i]; j++, rnp++) {
2704                         raw_spin_lock_init(&rnp->lock);
2705                         lockdep_set_class_and_name(&rnp->lock,
2706                                                    &rcu_node_class[i], buf[i]);
2707                         raw_spin_lock_init(&rnp->fqslock);
2708                         lockdep_set_class_and_name(&rnp->fqslock,
2709                                                    &rcu_fqs_class[i], fqs[i]);
2710                         rnp->gpnum = rsp->gpnum;
2711                         rnp->completed = rsp->completed;
2712                         rnp->qsmask = 0;
2713                         rnp->qsmaskinit = 0;
2714                         rnp->grplo = j * cpustride;
2715                         rnp->grphi = (j + 1) * cpustride - 1;
2716                         if (rnp->grphi >= NR_CPUS)
2717                                 rnp->grphi = NR_CPUS - 1;
2718                         if (i == 0) {
2719                                 rnp->grpnum = 0;
2720                                 rnp->grpmask = 0;
2721                                 rnp->parent = NULL;
2722                         } else {
2723                                 rnp->grpnum = j % rsp->levelspread[i - 1];
2724                                 rnp->grpmask = 1UL << rnp->grpnum;
2725                                 rnp->parent = rsp->level[i - 1] +
2726                                               j / rsp->levelspread[i - 1];
2727                         }
2728                         rnp->level = i;
2729                         INIT_LIST_HEAD(&rnp->blkd_tasks);
2730                 }
2731         }
2732
2733         rsp->rda = rda;
2734         init_waitqueue_head(&rsp->gp_wq);
2735         rnp = rsp->level[rcu_num_lvls - 1];
2736         for_each_possible_cpu(i) {
2737                 while (i > rnp->grphi)
2738                         rnp++;
2739                 per_cpu_ptr(rsp->rda, i)->mynode = rnp;
2740                 rcu_boot_init_percpu_data(i, rsp);
2741         }
2742         list_add(&rsp->flavors, &rcu_struct_flavors);
2743 }
2744
2745 /*
2746  * Compute the rcu_node tree geometry from kernel parameters.  This cannot
2747  * replace the definitions in rcutree.h because those are needed to size
2748  * the ->node array in the rcu_state structure.
2749  */
2750 static void __init rcu_init_geometry(void)
2751 {
2752         int i;
2753         int j;
2754         int n = nr_cpu_ids;
2755         int rcu_capacity[MAX_RCU_LVLS + 1];
2756
2757         /* If the compile-time values are accurate, just leave. */
2758         if (rcu_fanout_leaf == CONFIG_RCU_FANOUT_LEAF &&
2759             nr_cpu_ids == NR_CPUS)
2760                 return;
2761
2762         /*
2763          * Compute number of nodes that can be handled an rcu_node tree
2764          * with the given number of levels.  Setting rcu_capacity[0] makes
2765          * some of the arithmetic easier.
2766          */
2767         rcu_capacity[0] = 1;
2768         rcu_capacity[1] = rcu_fanout_leaf;
2769         for (i = 2; i <= MAX_RCU_LVLS; i++)
2770                 rcu_capacity[i] = rcu_capacity[i - 1] * CONFIG_RCU_FANOUT;
2771
2772         /*
2773          * The boot-time rcu_fanout_leaf parameter is only permitted
2774          * to increase the leaf-level fanout, not decrease it.  Of course,
2775          * the leaf-level fanout cannot exceed the number of bits in
2776          * the rcu_node masks.  Finally, the tree must be able to accommodate
2777          * the configured number of CPUs.  Complain and fall back to the
2778          * compile-time values if these limits are exceeded.
2779          */
2780         if (rcu_fanout_leaf < CONFIG_RCU_FANOUT_LEAF ||
2781             rcu_fanout_leaf > sizeof(unsigned long) * 8 ||
2782             n > rcu_capacity[MAX_RCU_LVLS]) {
2783                 WARN_ON(1);
2784                 return;
2785         }
2786
2787         /* Calculate the number of rcu_nodes at each level of the tree. */
2788         for (i = 1; i <= MAX_RCU_LVLS; i++)
2789                 if (n <= rcu_capacity[i]) {
2790                         for (j = 0; j <= i; j++)
2791                                 num_rcu_lvl[j] =
2792                                         DIV_ROUND_UP(n, rcu_capacity[i - j]);
2793                         rcu_num_lvls = i;
2794                         for (j = i + 1; j <= MAX_RCU_LVLS; j++)
2795                                 num_rcu_lvl[j] = 0;
2796                         break;
2797                 }
2798
2799         /* Calculate the total number of rcu_node structures. */
2800         rcu_num_nodes = 0;
2801         for (i = 0; i <= MAX_RCU_LVLS; i++)
2802                 rcu_num_nodes += num_rcu_lvl[i];
2803         rcu_num_nodes -= n;
2804 }
2805
2806 void __init rcu_init(void)
2807 {
2808         int cpu;
2809
2810         rcu_bootup_announce();
2811         rcu_init_geometry();
2812         rcu_init_one(&rcu_sched_state, &rcu_sched_data);
2813         rcu_init_one(&rcu_bh_state, &rcu_bh_data);
2814         __rcu_init_preempt();
2815          open_softirq(RCU_SOFTIRQ, rcu_process_callbacks);
2816
2817         /*
2818          * We don't need protection against CPU-hotplug here because
2819          * this is called early in boot, before either interrupts
2820          * or the scheduler are operational.
2821          */
2822         cpu_notifier(rcu_cpu_notify, 0);
2823         for_each_online_cpu(cpu)
2824                 rcu_cpu_notify(NULL, CPU_UP_PREPARE, (void *)(long)cpu);
2825         check_cpu_stall_init();
2826 }
2827
2828 #include "rcutree_plugin.h"