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