rcu: Remove last non-flavor-traversal rsp local variable from tree_plugin.h
[linux-block.git] / kernel / rcu / tree_plugin.h
1 /*
2  * Read-Copy Update mechanism for mutual exclusion (tree-based version)
3  * Internal non-public definitions that provide either classic
4  * or preemptible semantics.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, you can access it online at
18  * http://www.gnu.org/licenses/gpl-2.0.html.
19  *
20  * Copyright Red Hat, 2009
21  * Copyright IBM Corporation, 2009
22  *
23  * Author: Ingo Molnar <mingo@elte.hu>
24  *         Paul E. McKenney <paulmck@linux.vnet.ibm.com>
25  */
26
27 #include <linux/delay.h>
28 #include <linux/gfp.h>
29 #include <linux/oom.h>
30 #include <linux/sched/debug.h>
31 #include <linux/smpboot.h>
32 #include <linux/sched/isolation.h>
33 #include <uapi/linux/sched/types.h>
34 #include "../time/tick-internal.h"
35
36 #ifdef CONFIG_RCU_BOOST
37
38 #include "../locking/rtmutex_common.h"
39
40 /*
41  * Control variables for per-CPU and per-rcu_node kthreads.  These
42  * handle all flavors of RCU.
43  */
44 static DEFINE_PER_CPU(struct task_struct *, rcu_cpu_kthread_task);
45 DEFINE_PER_CPU(unsigned int, rcu_cpu_kthread_status);
46 DEFINE_PER_CPU(unsigned int, rcu_cpu_kthread_loops);
47 DEFINE_PER_CPU(char, rcu_cpu_has_work);
48
49 #else /* #ifdef CONFIG_RCU_BOOST */
50
51 /*
52  * Some architectures do not define rt_mutexes, but if !CONFIG_RCU_BOOST,
53  * all uses are in dead code.  Provide a definition to keep the compiler
54  * happy, but add WARN_ON_ONCE() to complain if used in the wrong place.
55  * This probably needs to be excluded from -rt builds.
56  */
57 #define rt_mutex_owner(a) ({ WARN_ON_ONCE(1); NULL; })
58 #define rt_mutex_futex_unlock(x) WARN_ON_ONCE(1)
59
60 #endif /* #else #ifdef CONFIG_RCU_BOOST */
61
62 #ifdef CONFIG_RCU_NOCB_CPU
63 static cpumask_var_t rcu_nocb_mask; /* CPUs to have callbacks offloaded. */
64 static bool __read_mostly rcu_nocb_poll;    /* Offload kthread are to poll. */
65 #endif /* #ifdef CONFIG_RCU_NOCB_CPU */
66
67 /*
68  * Check the RCU kernel configuration parameters and print informative
69  * messages about anything out of the ordinary.
70  */
71 static void __init rcu_bootup_announce_oddness(void)
72 {
73         if (IS_ENABLED(CONFIG_RCU_TRACE))
74                 pr_info("\tRCU event tracing is enabled.\n");
75         if ((IS_ENABLED(CONFIG_64BIT) && RCU_FANOUT != 64) ||
76             (!IS_ENABLED(CONFIG_64BIT) && RCU_FANOUT != 32))
77                 pr_info("\tCONFIG_RCU_FANOUT set to non-default value of %d.\n",
78                         RCU_FANOUT);
79         if (rcu_fanout_exact)
80                 pr_info("\tHierarchical RCU autobalancing is disabled.\n");
81         if (IS_ENABLED(CONFIG_RCU_FAST_NO_HZ))
82                 pr_info("\tRCU dyntick-idle grace-period acceleration is enabled.\n");
83         if (IS_ENABLED(CONFIG_PROVE_RCU))
84                 pr_info("\tRCU lockdep checking is enabled.\n");
85         if (RCU_NUM_LVLS >= 4)
86                 pr_info("\tFour(or more)-level hierarchy is enabled.\n");
87         if (RCU_FANOUT_LEAF != 16)
88                 pr_info("\tBuild-time adjustment of leaf fanout to %d.\n",
89                         RCU_FANOUT_LEAF);
90         if (rcu_fanout_leaf != RCU_FANOUT_LEAF)
91                 pr_info("\tBoot-time adjustment of leaf fanout to %d.\n",
92                         rcu_fanout_leaf);
93         if (nr_cpu_ids != NR_CPUS)
94                 pr_info("\tRCU restricting CPUs from NR_CPUS=%d to nr_cpu_ids=%u.\n", NR_CPUS, nr_cpu_ids);
95 #ifdef CONFIG_RCU_BOOST
96         pr_info("\tRCU priority boosting: priority %d delay %d ms.\n",
97                 kthread_prio, CONFIG_RCU_BOOST_DELAY);
98 #endif
99         if (blimit != DEFAULT_RCU_BLIMIT)
100                 pr_info("\tBoot-time adjustment of callback invocation limit to %ld.\n", blimit);
101         if (qhimark != DEFAULT_RCU_QHIMARK)
102                 pr_info("\tBoot-time adjustment of callback high-water mark to %ld.\n", qhimark);
103         if (qlowmark != DEFAULT_RCU_QLOMARK)
104                 pr_info("\tBoot-time adjustment of callback low-water mark to %ld.\n", qlowmark);
105         if (jiffies_till_first_fqs != ULONG_MAX)
106                 pr_info("\tBoot-time adjustment of first FQS scan delay to %ld jiffies.\n", jiffies_till_first_fqs);
107         if (jiffies_till_next_fqs != ULONG_MAX)
108                 pr_info("\tBoot-time adjustment of subsequent FQS scan delay to %ld jiffies.\n", jiffies_till_next_fqs);
109         if (rcu_kick_kthreads)
110                 pr_info("\tKick kthreads if too-long grace period.\n");
111         if (IS_ENABLED(CONFIG_DEBUG_OBJECTS_RCU_HEAD))
112                 pr_info("\tRCU callback double-/use-after-free debug enabled.\n");
113         if (gp_preinit_delay)
114                 pr_info("\tRCU debug GP pre-init slowdown %d jiffies.\n", gp_preinit_delay);
115         if (gp_init_delay)
116                 pr_info("\tRCU debug GP init slowdown %d jiffies.\n", gp_init_delay);
117         if (gp_cleanup_delay)
118                 pr_info("\tRCU debug GP init slowdown %d jiffies.\n", gp_cleanup_delay);
119         if (IS_ENABLED(CONFIG_RCU_EQS_DEBUG))
120                 pr_info("\tRCU debug extended QS entry/exit.\n");
121         rcupdate_announce_bootup_oddness();
122 }
123
124 #ifdef CONFIG_PREEMPT_RCU
125
126 static void rcu_report_exp_rnp(struct rcu_node *rnp, bool wake);
127 static void rcu_read_unlock_special(struct task_struct *t);
128
129 /*
130  * Tell them what RCU they are running.
131  */
132 static void __init rcu_bootup_announce(void)
133 {
134         pr_info("Preemptible hierarchical RCU implementation.\n");
135         rcu_bootup_announce_oddness();
136 }
137
138 /* Flags for rcu_preempt_ctxt_queue() decision table. */
139 #define RCU_GP_TASKS    0x8
140 #define RCU_EXP_TASKS   0x4
141 #define RCU_GP_BLKD     0x2
142 #define RCU_EXP_BLKD    0x1
143
144 /*
145  * Queues a task preempted within an RCU-preempt read-side critical
146  * section into the appropriate location within the ->blkd_tasks list,
147  * depending on the states of any ongoing normal and expedited grace
148  * periods.  The ->gp_tasks pointer indicates which element the normal
149  * grace period is waiting on (NULL if none), and the ->exp_tasks pointer
150  * indicates which element the expedited grace period is waiting on (again,
151  * NULL if none).  If a grace period is waiting on a given element in the
152  * ->blkd_tasks list, it also waits on all subsequent elements.  Thus,
153  * adding a task to the tail of the list blocks any grace period that is
154  * already waiting on one of the elements.  In contrast, adding a task
155  * to the head of the list won't block any grace period that is already
156  * waiting on one of the elements.
157  *
158  * This queuing is imprecise, and can sometimes make an ongoing grace
159  * period wait for a task that is not strictly speaking blocking it.
160  * Given the choice, we needlessly block a normal grace period rather than
161  * blocking an expedited grace period.
162  *
163  * Note that an endless sequence of expedited grace periods still cannot
164  * indefinitely postpone a normal grace period.  Eventually, all of the
165  * fixed number of preempted tasks blocking the normal grace period that are
166  * not also blocking the expedited grace period will resume and complete
167  * their RCU read-side critical sections.  At that point, the ->gp_tasks
168  * pointer will equal the ->exp_tasks pointer, at which point the end of
169  * the corresponding expedited grace period will also be the end of the
170  * normal grace period.
171  */
172 static void rcu_preempt_ctxt_queue(struct rcu_node *rnp, struct rcu_data *rdp)
173         __releases(rnp->lock) /* But leaves rrupts disabled. */
174 {
175         int blkd_state = (rnp->gp_tasks ? RCU_GP_TASKS : 0) +
176                          (rnp->exp_tasks ? RCU_EXP_TASKS : 0) +
177                          (rnp->qsmask & rdp->grpmask ? RCU_GP_BLKD : 0) +
178                          (rnp->expmask & rdp->grpmask ? RCU_EXP_BLKD : 0);
179         struct task_struct *t = current;
180
181         raw_lockdep_assert_held_rcu_node(rnp);
182         WARN_ON_ONCE(rdp->mynode != rnp);
183         WARN_ON_ONCE(!rcu_is_leaf_node(rnp));
184         /* RCU better not be waiting on newly onlined CPUs! */
185         WARN_ON_ONCE(rnp->qsmaskinitnext & ~rnp->qsmaskinit & rnp->qsmask &
186                      rdp->grpmask);
187
188         /*
189          * Decide where to queue the newly blocked task.  In theory,
190          * this could be an if-statement.  In practice, when I tried
191          * that, it was quite messy.
192          */
193         switch (blkd_state) {
194         case 0:
195         case                RCU_EXP_TASKS:
196         case                RCU_EXP_TASKS + RCU_GP_BLKD:
197         case RCU_GP_TASKS:
198         case RCU_GP_TASKS + RCU_EXP_TASKS:
199
200                 /*
201                  * Blocking neither GP, or first task blocking the normal
202                  * GP but not blocking the already-waiting expedited GP.
203                  * Queue at the head of the list to avoid unnecessarily
204                  * blocking the already-waiting GPs.
205                  */
206                 list_add(&t->rcu_node_entry, &rnp->blkd_tasks);
207                 break;
208
209         case                                              RCU_EXP_BLKD:
210         case                                RCU_GP_BLKD:
211         case                                RCU_GP_BLKD + RCU_EXP_BLKD:
212         case RCU_GP_TASKS +                               RCU_EXP_BLKD:
213         case RCU_GP_TASKS +                 RCU_GP_BLKD + RCU_EXP_BLKD:
214         case RCU_GP_TASKS + RCU_EXP_TASKS + RCU_GP_BLKD + RCU_EXP_BLKD:
215
216                 /*
217                  * First task arriving that blocks either GP, or first task
218                  * arriving that blocks the expedited GP (with the normal
219                  * GP already waiting), or a task arriving that blocks
220                  * both GPs with both GPs already waiting.  Queue at the
221                  * tail of the list to avoid any GP waiting on any of the
222                  * already queued tasks that are not blocking it.
223                  */
224                 list_add_tail(&t->rcu_node_entry, &rnp->blkd_tasks);
225                 break;
226
227         case                RCU_EXP_TASKS +               RCU_EXP_BLKD:
228         case                RCU_EXP_TASKS + RCU_GP_BLKD + RCU_EXP_BLKD:
229         case RCU_GP_TASKS + RCU_EXP_TASKS +               RCU_EXP_BLKD:
230
231                 /*
232                  * Second or subsequent task blocking the expedited GP.
233                  * The task either does not block the normal GP, or is the
234                  * first task blocking the normal GP.  Queue just after
235                  * the first task blocking the expedited GP.
236                  */
237                 list_add(&t->rcu_node_entry, rnp->exp_tasks);
238                 break;
239
240         case RCU_GP_TASKS +                 RCU_GP_BLKD:
241         case RCU_GP_TASKS + RCU_EXP_TASKS + RCU_GP_BLKD:
242
243                 /*
244                  * Second or subsequent task blocking the normal GP.
245                  * The task does not block the expedited GP. Queue just
246                  * after the first task blocking the normal GP.
247                  */
248                 list_add(&t->rcu_node_entry, rnp->gp_tasks);
249                 break;
250
251         default:
252
253                 /* Yet another exercise in excessive paranoia. */
254                 WARN_ON_ONCE(1);
255                 break;
256         }
257
258         /*
259          * We have now queued the task.  If it was the first one to
260          * block either grace period, update the ->gp_tasks and/or
261          * ->exp_tasks pointers, respectively, to reference the newly
262          * blocked tasks.
263          */
264         if (!rnp->gp_tasks && (blkd_state & RCU_GP_BLKD)) {
265                 rnp->gp_tasks = &t->rcu_node_entry;
266                 WARN_ON_ONCE(rnp->completedqs == rnp->gp_seq);
267         }
268         if (!rnp->exp_tasks && (blkd_state & RCU_EXP_BLKD))
269                 rnp->exp_tasks = &t->rcu_node_entry;
270         WARN_ON_ONCE(!(blkd_state & RCU_GP_BLKD) !=
271                      !(rnp->qsmask & rdp->grpmask));
272         WARN_ON_ONCE(!(blkd_state & RCU_EXP_BLKD) !=
273                      !(rnp->expmask & rdp->grpmask));
274         raw_spin_unlock_rcu_node(rnp); /* interrupts remain disabled. */
275
276         /*
277          * Report the quiescent state for the expedited GP.  This expedited
278          * GP should not be able to end until we report, so there should be
279          * no need to check for a subsequent expedited GP.  (Though we are
280          * still in a quiescent state in any case.)
281          */
282         if (blkd_state & RCU_EXP_BLKD && rdp->deferred_qs)
283                 rcu_report_exp_rdp(rdp);
284         else
285                 WARN_ON_ONCE(rdp->deferred_qs);
286 }
287
288 /*
289  * Record a preemptible-RCU quiescent state for the specified CPU.
290  * Note that this does not necessarily mean that the task currently running
291  * on the CPU is in a quiescent state:  Instead, it means that the current
292  * grace period need not wait on any RCU read-side critical section that
293  * starts later on this CPU.  It also means that if the current task is
294  * in an RCU read-side critical section, it has already added itself to
295  * some leaf rcu_node structure's ->blkd_tasks list.  In addition to the
296  * current task, there might be any number of other tasks blocked while
297  * in an RCU read-side critical section.
298  *
299  * Callers to this function must disable preemption.
300  */
301 static void rcu_qs(void)
302 {
303         RCU_LOCKDEP_WARN(preemptible(), "rcu_qs() invoked with preemption enabled!!!\n");
304         if (__this_cpu_read(rcu_data.cpu_no_qs.s)) {
305                 trace_rcu_grace_period(TPS("rcu_preempt"),
306                                        __this_cpu_read(rcu_data.gp_seq),
307                                        TPS("cpuqs"));
308                 __this_cpu_write(rcu_data.cpu_no_qs.b.norm, false);
309                 barrier(); /* Coordinate with rcu_flavor_check_callbacks(). */
310                 current->rcu_read_unlock_special.b.need_qs = false;
311         }
312 }
313
314 /*
315  * We have entered the scheduler, and the current task might soon be
316  * context-switched away from.  If this task is in an RCU read-side
317  * critical section, we will no longer be able to rely on the CPU to
318  * record that fact, so we enqueue the task on the blkd_tasks list.
319  * The task will dequeue itself when it exits the outermost enclosing
320  * RCU read-side critical section.  Therefore, the current grace period
321  * cannot be permitted to complete until the blkd_tasks list entries
322  * predating the current grace period drain, in other words, until
323  * rnp->gp_tasks becomes NULL.
324  *
325  * Caller must disable interrupts.
326  */
327 void rcu_note_context_switch(bool preempt)
328 {
329         struct task_struct *t = current;
330         struct rcu_data *rdp = this_cpu_ptr(&rcu_data);
331         struct rcu_node *rnp;
332
333         barrier(); /* Avoid RCU read-side critical sections leaking down. */
334         trace_rcu_utilization(TPS("Start context switch"));
335         lockdep_assert_irqs_disabled();
336         WARN_ON_ONCE(!preempt && t->rcu_read_lock_nesting > 0);
337         if (t->rcu_read_lock_nesting > 0 &&
338             !t->rcu_read_unlock_special.b.blocked) {
339
340                 /* Possibly blocking in an RCU read-side critical section. */
341                 rnp = rdp->mynode;
342                 raw_spin_lock_rcu_node(rnp);
343                 t->rcu_read_unlock_special.b.blocked = true;
344                 t->rcu_blocked_node = rnp;
345
346                 /*
347                  * Verify the CPU's sanity, trace the preemption, and
348                  * then queue the task as required based on the states
349                  * of any ongoing and expedited grace periods.
350                  */
351                 WARN_ON_ONCE((rdp->grpmask & rcu_rnp_online_cpus(rnp)) == 0);
352                 WARN_ON_ONCE(!list_empty(&t->rcu_node_entry));
353                 trace_rcu_preempt_task(rcu_state.name,
354                                        t->pid,
355                                        (rnp->qsmask & rdp->grpmask)
356                                        ? rnp->gp_seq
357                                        : rcu_seq_snap(&rnp->gp_seq));
358                 rcu_preempt_ctxt_queue(rnp, rdp);
359         } else if (t->rcu_read_lock_nesting < 0 &&
360                    t->rcu_read_unlock_special.s) {
361
362                 /*
363                  * Complete exit from RCU read-side critical section on
364                  * behalf of preempted instance of __rcu_read_unlock().
365                  */
366                 rcu_read_unlock_special(t);
367                 rcu_preempt_deferred_qs(t);
368         } else {
369                 rcu_preempt_deferred_qs(t);
370         }
371
372         /*
373          * Either we were not in an RCU read-side critical section to
374          * begin with, or we have now recorded that critical section
375          * globally.  Either way, we can now note a quiescent state
376          * for this CPU.  Again, if we were in an RCU read-side critical
377          * section, and if that critical section was blocking the current
378          * grace period, then the fact that the task has been enqueued
379          * means that we continue to block the current grace period.
380          */
381         rcu_qs();
382         if (rdp->deferred_qs)
383                 rcu_report_exp_rdp(rdp);
384         trace_rcu_utilization(TPS("End context switch"));
385         barrier(); /* Avoid RCU read-side critical sections leaking up. */
386 }
387 EXPORT_SYMBOL_GPL(rcu_note_context_switch);
388
389 /*
390  * Check for preempted RCU readers blocking the current grace period
391  * for the specified rcu_node structure.  If the caller needs a reliable
392  * answer, it must hold the rcu_node's ->lock.
393  */
394 static int rcu_preempt_blocked_readers_cgp(struct rcu_node *rnp)
395 {
396         return rnp->gp_tasks != NULL;
397 }
398
399 /*
400  * Preemptible RCU implementation for rcu_read_lock().
401  * Just increment ->rcu_read_lock_nesting, shared state will be updated
402  * if we block.
403  */
404 void __rcu_read_lock(void)
405 {
406         current->rcu_read_lock_nesting++;
407         barrier();  /* critical section after entry code. */
408 }
409 EXPORT_SYMBOL_GPL(__rcu_read_lock);
410
411 /*
412  * Preemptible RCU implementation for rcu_read_unlock().
413  * Decrement ->rcu_read_lock_nesting.  If the result is zero (outermost
414  * rcu_read_unlock()) and ->rcu_read_unlock_special is non-zero, then
415  * invoke rcu_read_unlock_special() to clean up after a context switch
416  * in an RCU read-side critical section and other special cases.
417  */
418 void __rcu_read_unlock(void)
419 {
420         struct task_struct *t = current;
421
422         if (t->rcu_read_lock_nesting != 1) {
423                 --t->rcu_read_lock_nesting;
424         } else {
425                 barrier();  /* critical section before exit code. */
426                 t->rcu_read_lock_nesting = INT_MIN;
427                 barrier();  /* assign before ->rcu_read_unlock_special load */
428                 if (unlikely(READ_ONCE(t->rcu_read_unlock_special.s)))
429                         rcu_read_unlock_special(t);
430                 barrier();  /* ->rcu_read_unlock_special load before assign */
431                 t->rcu_read_lock_nesting = 0;
432         }
433 #ifdef CONFIG_PROVE_LOCKING
434         {
435                 int rrln = READ_ONCE(t->rcu_read_lock_nesting);
436
437                 WARN_ON_ONCE(rrln < 0 && rrln > INT_MIN / 2);
438         }
439 #endif /* #ifdef CONFIG_PROVE_LOCKING */
440 }
441 EXPORT_SYMBOL_GPL(__rcu_read_unlock);
442
443 /*
444  * Advance a ->blkd_tasks-list pointer to the next entry, instead
445  * returning NULL if at the end of the list.
446  */
447 static struct list_head *rcu_next_node_entry(struct task_struct *t,
448                                              struct rcu_node *rnp)
449 {
450         struct list_head *np;
451
452         np = t->rcu_node_entry.next;
453         if (np == &rnp->blkd_tasks)
454                 np = NULL;
455         return np;
456 }
457
458 /*
459  * Return true if the specified rcu_node structure has tasks that were
460  * preempted within an RCU read-side critical section.
461  */
462 static bool rcu_preempt_has_tasks(struct rcu_node *rnp)
463 {
464         return !list_empty(&rnp->blkd_tasks);
465 }
466
467 /*
468  * Report deferred quiescent states.  The deferral time can
469  * be quite short, for example, in the case of the call from
470  * rcu_read_unlock_special().
471  */
472 static void
473 rcu_preempt_deferred_qs_irqrestore(struct task_struct *t, unsigned long flags)
474 {
475         bool empty_exp;
476         bool empty_norm;
477         bool empty_exp_now;
478         struct list_head *np;
479         bool drop_boost_mutex = false;
480         struct rcu_data *rdp;
481         struct rcu_node *rnp;
482         union rcu_special special;
483
484         /*
485          * If RCU core is waiting for this CPU to exit its critical section,
486          * report the fact that it has exited.  Because irqs are disabled,
487          * t->rcu_read_unlock_special cannot change.
488          */
489         special = t->rcu_read_unlock_special;
490         rdp = this_cpu_ptr(&rcu_data);
491         if (!special.s && !rdp->deferred_qs) {
492                 local_irq_restore(flags);
493                 return;
494         }
495         if (special.b.need_qs) {
496                 rcu_qs();
497                 t->rcu_read_unlock_special.b.need_qs = false;
498                 if (!t->rcu_read_unlock_special.s && !rdp->deferred_qs) {
499                         local_irq_restore(flags);
500                         return;
501                 }
502         }
503
504         /*
505          * Respond to a request by an expedited grace period for a
506          * quiescent state from this CPU.  Note that requests from
507          * tasks are handled when removing the task from the
508          * blocked-tasks list below.
509          */
510         if (rdp->deferred_qs) {
511                 rcu_report_exp_rdp(rdp);
512                 if (!t->rcu_read_unlock_special.s) {
513                         local_irq_restore(flags);
514                         return;
515                 }
516         }
517
518         /* Clean up if blocked during RCU read-side critical section. */
519         if (special.b.blocked) {
520                 t->rcu_read_unlock_special.b.blocked = false;
521
522                 /*
523                  * Remove this task from the list it blocked on.  The task
524                  * now remains queued on the rcu_node corresponding to the
525                  * CPU it first blocked on, so there is no longer any need
526                  * to loop.  Retain a WARN_ON_ONCE() out of sheer paranoia.
527                  */
528                 rnp = t->rcu_blocked_node;
529                 raw_spin_lock_rcu_node(rnp); /* irqs already disabled. */
530                 WARN_ON_ONCE(rnp != t->rcu_blocked_node);
531                 WARN_ON_ONCE(!rcu_is_leaf_node(rnp));
532                 empty_norm = !rcu_preempt_blocked_readers_cgp(rnp);
533                 WARN_ON_ONCE(rnp->completedqs == rnp->gp_seq &&
534                              (!empty_norm || rnp->qsmask));
535                 empty_exp = sync_rcu_preempt_exp_done(rnp);
536                 smp_mb(); /* ensure expedited fastpath sees end of RCU c-s. */
537                 np = rcu_next_node_entry(t, rnp);
538                 list_del_init(&t->rcu_node_entry);
539                 t->rcu_blocked_node = NULL;
540                 trace_rcu_unlock_preempted_task(TPS("rcu_preempt"),
541                                                 rnp->gp_seq, t->pid);
542                 if (&t->rcu_node_entry == rnp->gp_tasks)
543                         rnp->gp_tasks = np;
544                 if (&t->rcu_node_entry == rnp->exp_tasks)
545                         rnp->exp_tasks = np;
546                 if (IS_ENABLED(CONFIG_RCU_BOOST)) {
547                         /* Snapshot ->boost_mtx ownership w/rnp->lock held. */
548                         drop_boost_mutex = rt_mutex_owner(&rnp->boost_mtx) == t;
549                         if (&t->rcu_node_entry == rnp->boost_tasks)
550                                 rnp->boost_tasks = np;
551                 }
552
553                 /*
554                  * If this was the last task on the current list, and if
555                  * we aren't waiting on any CPUs, report the quiescent state.
556                  * Note that rcu_report_unblock_qs_rnp() releases rnp->lock,
557                  * so we must take a snapshot of the expedited state.
558                  */
559                 empty_exp_now = sync_rcu_preempt_exp_done(rnp);
560                 if (!empty_norm && !rcu_preempt_blocked_readers_cgp(rnp)) {
561                         trace_rcu_quiescent_state_report(TPS("preempt_rcu"),
562                                                          rnp->gp_seq,
563                                                          0, rnp->qsmask,
564                                                          rnp->level,
565                                                          rnp->grplo,
566                                                          rnp->grphi,
567                                                          !!rnp->gp_tasks);
568                         rcu_report_unblock_qs_rnp(rnp, flags);
569                 } else {
570                         raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
571                 }
572
573                 /* Unboost if we were boosted. */
574                 if (IS_ENABLED(CONFIG_RCU_BOOST) && drop_boost_mutex)
575                         rt_mutex_futex_unlock(&rnp->boost_mtx);
576
577                 /*
578                  * If this was the last task on the expedited lists,
579                  * then we need to report up the rcu_node hierarchy.
580                  */
581                 if (!empty_exp && empty_exp_now)
582                         rcu_report_exp_rnp(rnp, true);
583         } else {
584                 local_irq_restore(flags);
585         }
586 }
587
588 /*
589  * Is a deferred quiescent-state pending, and are we also not in
590  * an RCU read-side critical section?  It is the caller's responsibility
591  * to ensure it is otherwise safe to report any deferred quiescent
592  * states.  The reason for this is that it is safe to report a
593  * quiescent state during context switch even though preemption
594  * is disabled.  This function cannot be expected to understand these
595  * nuances, so the caller must handle them.
596  */
597 static bool rcu_preempt_need_deferred_qs(struct task_struct *t)
598 {
599         return (this_cpu_ptr(&rcu_data)->deferred_qs ||
600                 READ_ONCE(t->rcu_read_unlock_special.s)) &&
601                t->rcu_read_lock_nesting <= 0;
602 }
603
604 /*
605  * Report a deferred quiescent state if needed and safe to do so.
606  * As with rcu_preempt_need_deferred_qs(), "safe" involves only
607  * not being in an RCU read-side critical section.  The caller must
608  * evaluate safety in terms of interrupt, softirq, and preemption
609  * disabling.
610  */
611 static void rcu_preempt_deferred_qs(struct task_struct *t)
612 {
613         unsigned long flags;
614         bool couldrecurse = t->rcu_read_lock_nesting >= 0;
615
616         if (!rcu_preempt_need_deferred_qs(t))
617                 return;
618         if (couldrecurse)
619                 t->rcu_read_lock_nesting -= INT_MIN;
620         local_irq_save(flags);
621         rcu_preempt_deferred_qs_irqrestore(t, flags);
622         if (couldrecurse)
623                 t->rcu_read_lock_nesting += INT_MIN;
624 }
625
626 /*
627  * Handle special cases during rcu_read_unlock(), such as needing to
628  * notify RCU core processing or task having blocked during the RCU
629  * read-side critical section.
630  */
631 static void rcu_read_unlock_special(struct task_struct *t)
632 {
633         unsigned long flags;
634         bool preempt_bh_were_disabled =
635                         !!(preempt_count() & (PREEMPT_MASK | SOFTIRQ_MASK));
636         bool irqs_were_disabled;
637
638         /* NMI handlers cannot block and cannot safely manipulate state. */
639         if (in_nmi())
640                 return;
641
642         local_irq_save(flags);
643         irqs_were_disabled = irqs_disabled_flags(flags);
644         if ((preempt_bh_were_disabled || irqs_were_disabled) &&
645             t->rcu_read_unlock_special.b.blocked) {
646                 /* Need to defer quiescent state until everything is enabled. */
647                 raise_softirq_irqoff(RCU_SOFTIRQ);
648                 local_irq_restore(flags);
649                 return;
650         }
651         rcu_preempt_deferred_qs_irqrestore(t, flags);
652 }
653
654 /*
655  * Dump detailed information for all tasks blocking the current RCU
656  * grace period on the specified rcu_node structure.
657  */
658 static void rcu_print_detail_task_stall_rnp(struct rcu_node *rnp)
659 {
660         unsigned long flags;
661         struct task_struct *t;
662
663         raw_spin_lock_irqsave_rcu_node(rnp, flags);
664         if (!rcu_preempt_blocked_readers_cgp(rnp)) {
665                 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
666                 return;
667         }
668         t = list_entry(rnp->gp_tasks->prev,
669                        struct task_struct, rcu_node_entry);
670         list_for_each_entry_continue(t, &rnp->blkd_tasks, rcu_node_entry) {
671                 /*
672                  * We could be printing a lot while holding a spinlock.
673                  * Avoid triggering hard lockup.
674                  */
675                 touch_nmi_watchdog();
676                 sched_show_task(t);
677         }
678         raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
679 }
680
681 /*
682  * Dump detailed information for all tasks blocking the current RCU
683  * grace period.
684  */
685 static void rcu_print_detail_task_stall(void)
686 {
687         struct rcu_node *rnp = rcu_get_root();
688
689         rcu_print_detail_task_stall_rnp(rnp);
690         rcu_for_each_leaf_node(rnp)
691                 rcu_print_detail_task_stall_rnp(rnp);
692 }
693
694 static void rcu_print_task_stall_begin(struct rcu_node *rnp)
695 {
696         pr_err("\tTasks blocked on level-%d rcu_node (CPUs %d-%d):",
697                rnp->level, rnp->grplo, rnp->grphi);
698 }
699
700 static void rcu_print_task_stall_end(void)
701 {
702         pr_cont("\n");
703 }
704
705 /*
706  * Scan the current list of tasks blocked within RCU read-side critical
707  * sections, printing out the tid of each.
708  */
709 static int rcu_print_task_stall(struct rcu_node *rnp)
710 {
711         struct task_struct *t;
712         int ndetected = 0;
713
714         if (!rcu_preempt_blocked_readers_cgp(rnp))
715                 return 0;
716         rcu_print_task_stall_begin(rnp);
717         t = list_entry(rnp->gp_tasks->prev,
718                        struct task_struct, rcu_node_entry);
719         list_for_each_entry_continue(t, &rnp->blkd_tasks, rcu_node_entry) {
720                 pr_cont(" P%d", t->pid);
721                 ndetected++;
722         }
723         rcu_print_task_stall_end();
724         return ndetected;
725 }
726
727 /*
728  * Scan the current list of tasks blocked within RCU read-side critical
729  * sections, printing out the tid of each that is blocking the current
730  * expedited grace period.
731  */
732 static int rcu_print_task_exp_stall(struct rcu_node *rnp)
733 {
734         struct task_struct *t;
735         int ndetected = 0;
736
737         if (!rnp->exp_tasks)
738                 return 0;
739         t = list_entry(rnp->exp_tasks->prev,
740                        struct task_struct, rcu_node_entry);
741         list_for_each_entry_continue(t, &rnp->blkd_tasks, rcu_node_entry) {
742                 pr_cont(" P%d", t->pid);
743                 ndetected++;
744         }
745         return ndetected;
746 }
747
748 /*
749  * Check that the list of blocked tasks for the newly completed grace
750  * period is in fact empty.  It is a serious bug to complete a grace
751  * period that still has RCU readers blocked!  This function must be
752  * invoked -before- updating this rnp's ->gp_seq, and the rnp's ->lock
753  * must be held by the caller.
754  *
755  * Also, if there are blocked tasks on the list, they automatically
756  * block the newly created grace period, so set up ->gp_tasks accordingly.
757  */
758 static void rcu_preempt_check_blocked_tasks(struct rcu_node *rnp)
759 {
760         struct task_struct *t;
761
762         RCU_LOCKDEP_WARN(preemptible(), "rcu_preempt_check_blocked_tasks() invoked with preemption enabled!!!\n");
763         if (WARN_ON_ONCE(rcu_preempt_blocked_readers_cgp(rnp)))
764                 dump_blkd_tasks(rnp, 10);
765         if (rcu_preempt_has_tasks(rnp) &&
766             (rnp->qsmaskinit || rnp->wait_blkd_tasks)) {
767                 rnp->gp_tasks = rnp->blkd_tasks.next;
768                 t = container_of(rnp->gp_tasks, struct task_struct,
769                                  rcu_node_entry);
770                 trace_rcu_unlock_preempted_task(TPS("rcu_preempt-GPS"),
771                                                 rnp->gp_seq, t->pid);
772         }
773         WARN_ON_ONCE(rnp->qsmask);
774 }
775
776 /*
777  * Check for a quiescent state from the current CPU.  When a task blocks,
778  * the task is recorded in the corresponding CPU's rcu_node structure,
779  * which is checked elsewhere.
780  *
781  * Caller must disable hard irqs.
782  */
783 static void rcu_flavor_check_callbacks(int user)
784 {
785         struct task_struct *t = current;
786
787         if (user || rcu_is_cpu_rrupt_from_idle()) {
788                 rcu_note_voluntary_context_switch(current);
789         }
790         if (t->rcu_read_lock_nesting > 0 ||
791             (preempt_count() & (PREEMPT_MASK | SOFTIRQ_MASK))) {
792                 /* No QS, force context switch if deferred. */
793                 if (rcu_preempt_need_deferred_qs(t))
794                         resched_cpu(smp_processor_id());
795         } else if (rcu_preempt_need_deferred_qs(t)) {
796                 rcu_preempt_deferred_qs(t); /* Report deferred QS. */
797                 return;
798         } else if (!t->rcu_read_lock_nesting) {
799                 rcu_qs(); /* Report immediate QS. */
800                 return;
801         }
802
803         /* If GP is oldish, ask for help from rcu_read_unlock_special(). */
804         if (t->rcu_read_lock_nesting > 0 &&
805             __this_cpu_read(rcu_data.core_needs_qs) &&
806             __this_cpu_read(rcu_data.cpu_no_qs.b.norm) &&
807             !t->rcu_read_unlock_special.b.need_qs &&
808             time_after(jiffies, rcu_state.gp_start + HZ))
809                 t->rcu_read_unlock_special.b.need_qs = true;
810 }
811
812 /**
813  * synchronize_rcu - wait until a grace period has elapsed.
814  *
815  * Control will return to the caller some time after a full grace
816  * period has elapsed, in other words after all currently executing RCU
817  * read-side critical sections have completed.  Note, however, that
818  * upon return from synchronize_rcu(), the caller might well be executing
819  * concurrently with new RCU read-side critical sections that began while
820  * synchronize_rcu() was waiting.  RCU read-side critical sections are
821  * delimited by rcu_read_lock() and rcu_read_unlock(), and may be nested.
822  * In addition, regions of code across which interrupts, preemption, or
823  * softirqs have been disabled also serve as RCU read-side critical
824  * sections.  This includes hardware interrupt handlers, softirq handlers,
825  * and NMI handlers.
826  *
827  * Note that this guarantee implies further memory-ordering guarantees.
828  * On systems with more than one CPU, when synchronize_rcu() returns,
829  * each CPU is guaranteed to have executed a full memory barrier since the
830  * end of its last RCU-sched read-side critical section whose beginning
831  * preceded the call to synchronize_rcu().  In addition, each CPU having
832  * an RCU read-side critical section that extends beyond the return from
833  * synchronize_rcu() is guaranteed to have executed a full memory barrier
834  * after the beginning of synchronize_rcu() and before the beginning of
835  * that RCU read-side critical section.  Note that these guarantees include
836  * CPUs that are offline, idle, or executing in user mode, as well as CPUs
837  * that are executing in the kernel.
838  *
839  * Furthermore, if CPU A invoked synchronize_rcu(), which returned
840  * to its caller on CPU B, then both CPU A and CPU B are guaranteed
841  * to have executed a full memory barrier during the execution of
842  * synchronize_rcu() -- even if CPU A and CPU B are the same CPU (but
843  * again only if the system has more than one CPU).
844  */
845 void synchronize_rcu(void)
846 {
847         RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map) ||
848                          lock_is_held(&rcu_lock_map) ||
849                          lock_is_held(&rcu_sched_lock_map),
850                          "Illegal synchronize_rcu() in RCU read-side critical section");
851         if (rcu_scheduler_active == RCU_SCHEDULER_INACTIVE)
852                 return;
853         if (rcu_gp_is_expedited())
854                 synchronize_rcu_expedited();
855         else
856                 wait_rcu_gp(call_rcu);
857 }
858 EXPORT_SYMBOL_GPL(synchronize_rcu);
859
860 /*
861  * Check for a task exiting while in a preemptible-RCU read-side
862  * critical section, clean up if so.  No need to issue warnings,
863  * as debug_check_no_locks_held() already does this if lockdep
864  * is enabled.
865  */
866 void exit_rcu(void)
867 {
868         struct task_struct *t = current;
869
870         if (likely(list_empty(&current->rcu_node_entry)))
871                 return;
872         t->rcu_read_lock_nesting = 1;
873         barrier();
874         t->rcu_read_unlock_special.b.blocked = true;
875         __rcu_read_unlock();
876         rcu_preempt_deferred_qs(current);
877 }
878
879 /*
880  * Dump the blocked-tasks state, but limit the list dump to the
881  * specified number of elements.
882  */
883 static void
884 dump_blkd_tasks(struct rcu_node *rnp, int ncheck)
885 {
886         int cpu;
887         int i;
888         struct list_head *lhp;
889         bool onl;
890         struct rcu_data *rdp;
891         struct rcu_node *rnp1;
892
893         raw_lockdep_assert_held_rcu_node(rnp);
894         pr_info("%s: grp: %d-%d level: %d ->gp_seq %ld ->completedqs %ld\n",
895                 __func__, rnp->grplo, rnp->grphi, rnp->level,
896                 (long)rnp->gp_seq, (long)rnp->completedqs);
897         for (rnp1 = rnp; rnp1; rnp1 = rnp1->parent)
898                 pr_info("%s: %d:%d ->qsmask %#lx ->qsmaskinit %#lx ->qsmaskinitnext %#lx\n",
899                         __func__, rnp1->grplo, rnp1->grphi, rnp1->qsmask, rnp1->qsmaskinit, rnp1->qsmaskinitnext);
900         pr_info("%s: ->gp_tasks %p ->boost_tasks %p ->exp_tasks %p\n",
901                 __func__, rnp->gp_tasks, rnp->boost_tasks, rnp->exp_tasks);
902         pr_info("%s: ->blkd_tasks", __func__);
903         i = 0;
904         list_for_each(lhp, &rnp->blkd_tasks) {
905                 pr_cont(" %p", lhp);
906                 if (++i >= 10)
907                         break;
908         }
909         pr_cont("\n");
910         for (cpu = rnp->grplo; cpu <= rnp->grphi; cpu++) {
911                 rdp = per_cpu_ptr(&rcu_data, cpu);
912                 onl = !!(rdp->grpmask & rcu_rnp_online_cpus(rnp));
913                 pr_info("\t%d: %c online: %ld(%d) offline: %ld(%d)\n",
914                         cpu, ".o"[onl],
915                         (long)rdp->rcu_onl_gp_seq, rdp->rcu_onl_gp_flags,
916                         (long)rdp->rcu_ofl_gp_seq, rdp->rcu_ofl_gp_flags);
917         }
918 }
919
920 #else /* #ifdef CONFIG_PREEMPT_RCU */
921
922 /*
923  * Tell them what RCU they are running.
924  */
925 static void __init rcu_bootup_announce(void)
926 {
927         pr_info("Hierarchical RCU implementation.\n");
928         rcu_bootup_announce_oddness();
929 }
930
931 /*
932  * Note a quiescent state for PREEMPT=n.  Because we do not need to know
933  * how many quiescent states passed, just if there was at least one since
934  * the start of the grace period, this just sets a flag.  The caller must
935  * have disabled preemption.
936  */
937 static void rcu_qs(void)
938 {
939         RCU_LOCKDEP_WARN(preemptible(), "rcu_qs() invoked with preemption enabled!!!");
940         if (!__this_cpu_read(rcu_data.cpu_no_qs.s))
941                 return;
942         trace_rcu_grace_period(TPS("rcu_sched"),
943                                __this_cpu_read(rcu_data.gp_seq), TPS("cpuqs"));
944         __this_cpu_write(rcu_data.cpu_no_qs.b.norm, false);
945         if (!__this_cpu_read(rcu_data.cpu_no_qs.b.exp))
946                 return;
947         __this_cpu_write(rcu_data.cpu_no_qs.b.exp, false);
948         rcu_report_exp_rdp(this_cpu_ptr(&rcu_data));
949 }
950
951 /*
952  * Note a PREEMPT=n context switch.  The caller must have disabled interrupts.
953  */
954 void rcu_note_context_switch(bool preempt)
955 {
956         barrier(); /* Avoid RCU read-side critical sections leaking down. */
957         trace_rcu_utilization(TPS("Start context switch"));
958         rcu_qs();
959         /* Load rcu_urgent_qs before other flags. */
960         if (!smp_load_acquire(this_cpu_ptr(&rcu_dynticks.rcu_urgent_qs)))
961                 goto out;
962         this_cpu_write(rcu_dynticks.rcu_urgent_qs, false);
963         if (unlikely(raw_cpu_read(rcu_dynticks.rcu_need_heavy_qs)))
964                 rcu_momentary_dyntick_idle();
965         this_cpu_inc(rcu_dynticks.rcu_qs_ctr);
966         if (!preempt)
967                 rcu_tasks_qs(current);
968 out:
969         trace_rcu_utilization(TPS("End context switch"));
970         barrier(); /* Avoid RCU read-side critical sections leaking up. */
971 }
972 EXPORT_SYMBOL_GPL(rcu_note_context_switch);
973
974 /*
975  * Because preemptible RCU does not exist, there are never any preempted
976  * RCU readers.
977  */
978 static int rcu_preempt_blocked_readers_cgp(struct rcu_node *rnp)
979 {
980         return 0;
981 }
982
983 /*
984  * Because there is no preemptible RCU, there can be no readers blocked.
985  */
986 static bool rcu_preempt_has_tasks(struct rcu_node *rnp)
987 {
988         return false;
989 }
990
991 /*
992  * Because there is no preemptible RCU, there can be no deferred quiescent
993  * states.
994  */
995 static bool rcu_preempt_need_deferred_qs(struct task_struct *t)
996 {
997         return false;
998 }
999 static void rcu_preempt_deferred_qs(struct task_struct *t) { }
1000
1001 /*
1002  * Because preemptible RCU does not exist, we never have to check for
1003  * tasks blocked within RCU read-side critical sections.
1004  */
1005 static void rcu_print_detail_task_stall(void)
1006 {
1007 }
1008
1009 /*
1010  * Because preemptible RCU does not exist, we never have to check for
1011  * tasks blocked within RCU read-side critical sections.
1012  */
1013 static int rcu_print_task_stall(struct rcu_node *rnp)
1014 {
1015         return 0;
1016 }
1017
1018 /*
1019  * Because preemptible RCU does not exist, we never have to check for
1020  * tasks blocked within RCU read-side critical sections that are
1021  * blocking the current expedited grace period.
1022  */
1023 static int rcu_print_task_exp_stall(struct rcu_node *rnp)
1024 {
1025         return 0;
1026 }
1027
1028 /*
1029  * Because there is no preemptible RCU, there can be no readers blocked,
1030  * so there is no need to check for blocked tasks.  So check only for
1031  * bogus qsmask values.
1032  */
1033 static void rcu_preempt_check_blocked_tasks(struct rcu_node *rnp)
1034 {
1035         WARN_ON_ONCE(rnp->qsmask);
1036 }
1037
1038 /*
1039  * Check to see if this CPU is in a non-context-switch quiescent state
1040  * (user mode or idle loop for rcu, non-softirq execution for rcu_bh).
1041  * Also schedule RCU core processing.
1042  *
1043  * This function must be called from hardirq context.  It is normally
1044  * invoked from the scheduling-clock interrupt.
1045  */
1046 static void rcu_flavor_check_callbacks(int user)
1047 {
1048         if (user || rcu_is_cpu_rrupt_from_idle()) {
1049
1050                 /*
1051                  * Get here if this CPU took its interrupt from user
1052                  * mode or from the idle loop, and if this is not a
1053                  * nested interrupt.  In this case, the CPU is in
1054                  * a quiescent state, so note it.
1055                  *
1056                  * No memory barrier is required here because rcu_qs()
1057                  * references only CPU-local variables that other CPUs
1058                  * neither access nor modify, at least not while the
1059                  * corresponding CPU is online.
1060                  */
1061
1062                 rcu_qs();
1063         }
1064 }
1065
1066 /* PREEMPT=n implementation of synchronize_rcu(). */
1067 void synchronize_rcu(void)
1068 {
1069         RCU_LOCKDEP_WARN(lock_is_held(&rcu_bh_lock_map) ||
1070                          lock_is_held(&rcu_lock_map) ||
1071                          lock_is_held(&rcu_sched_lock_map),
1072                          "Illegal synchronize_rcu() in RCU-sched read-side critical section");
1073         if (rcu_blocking_is_gp())
1074                 return;
1075         if (rcu_gp_is_expedited())
1076                 synchronize_rcu_expedited();
1077         else
1078                 wait_rcu_gp(call_rcu);
1079 }
1080 EXPORT_SYMBOL_GPL(synchronize_rcu);
1081
1082 /*
1083  * Because preemptible RCU does not exist, tasks cannot possibly exit
1084  * while in preemptible RCU read-side critical sections.
1085  */
1086 void exit_rcu(void)
1087 {
1088 }
1089
1090 /*
1091  * Dump the guaranteed-empty blocked-tasks state.  Trust but verify.
1092  */
1093 static void
1094 dump_blkd_tasks(struct rcu_node *rnp, int ncheck)
1095 {
1096         WARN_ON_ONCE(!list_empty(&rnp->blkd_tasks));
1097 }
1098
1099 #endif /* #else #ifdef CONFIG_PREEMPT_RCU */
1100
1101 #ifdef CONFIG_RCU_BOOST
1102
1103 static void rcu_wake_cond(struct task_struct *t, int status)
1104 {
1105         /*
1106          * If the thread is yielding, only wake it when this
1107          * is invoked from idle
1108          */
1109         if (status != RCU_KTHREAD_YIELDING || is_idle_task(current))
1110                 wake_up_process(t);
1111 }
1112
1113 /*
1114  * Carry out RCU priority boosting on the task indicated by ->exp_tasks
1115  * or ->boost_tasks, advancing the pointer to the next task in the
1116  * ->blkd_tasks list.
1117  *
1118  * Note that irqs must be enabled: boosting the task can block.
1119  * Returns 1 if there are more tasks needing to be boosted.
1120  */
1121 static int rcu_boost(struct rcu_node *rnp)
1122 {
1123         unsigned long flags;
1124         struct task_struct *t;
1125         struct list_head *tb;
1126
1127         if (READ_ONCE(rnp->exp_tasks) == NULL &&
1128             READ_ONCE(rnp->boost_tasks) == NULL)
1129                 return 0;  /* Nothing left to boost. */
1130
1131         raw_spin_lock_irqsave_rcu_node(rnp, flags);
1132
1133         /*
1134          * Recheck under the lock: all tasks in need of boosting
1135          * might exit their RCU read-side critical sections on their own.
1136          */
1137         if (rnp->exp_tasks == NULL && rnp->boost_tasks == NULL) {
1138                 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1139                 return 0;
1140         }
1141
1142         /*
1143          * Preferentially boost tasks blocking expedited grace periods.
1144          * This cannot starve the normal grace periods because a second
1145          * expedited grace period must boost all blocked tasks, including
1146          * those blocking the pre-existing normal grace period.
1147          */
1148         if (rnp->exp_tasks != NULL)
1149                 tb = rnp->exp_tasks;
1150         else
1151                 tb = rnp->boost_tasks;
1152
1153         /*
1154          * We boost task t by manufacturing an rt_mutex that appears to
1155          * be held by task t.  We leave a pointer to that rt_mutex where
1156          * task t can find it, and task t will release the mutex when it
1157          * exits its outermost RCU read-side critical section.  Then
1158          * simply acquiring this artificial rt_mutex will boost task
1159          * t's priority.  (Thanks to tglx for suggesting this approach!)
1160          *
1161          * Note that task t must acquire rnp->lock to remove itself from
1162          * the ->blkd_tasks list, which it will do from exit() if from
1163          * nowhere else.  We therefore are guaranteed that task t will
1164          * stay around at least until we drop rnp->lock.  Note that
1165          * rnp->lock also resolves races between our priority boosting
1166          * and task t's exiting its outermost RCU read-side critical
1167          * section.
1168          */
1169         t = container_of(tb, struct task_struct, rcu_node_entry);
1170         rt_mutex_init_proxy_locked(&rnp->boost_mtx, t);
1171         raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1172         /* Lock only for side effect: boosts task t's priority. */
1173         rt_mutex_lock(&rnp->boost_mtx);
1174         rt_mutex_unlock(&rnp->boost_mtx);  /* Then keep lockdep happy. */
1175
1176         return READ_ONCE(rnp->exp_tasks) != NULL ||
1177                READ_ONCE(rnp->boost_tasks) != NULL;
1178 }
1179
1180 /*
1181  * Priority-boosting kthread, one per leaf rcu_node.
1182  */
1183 static int rcu_boost_kthread(void *arg)
1184 {
1185         struct rcu_node *rnp = (struct rcu_node *)arg;
1186         int spincnt = 0;
1187         int more2boost;
1188
1189         trace_rcu_utilization(TPS("Start boost kthread@init"));
1190         for (;;) {
1191                 rnp->boost_kthread_status = RCU_KTHREAD_WAITING;
1192                 trace_rcu_utilization(TPS("End boost kthread@rcu_wait"));
1193                 rcu_wait(rnp->boost_tasks || rnp->exp_tasks);
1194                 trace_rcu_utilization(TPS("Start boost kthread@rcu_wait"));
1195                 rnp->boost_kthread_status = RCU_KTHREAD_RUNNING;
1196                 more2boost = rcu_boost(rnp);
1197                 if (more2boost)
1198                         spincnt++;
1199                 else
1200                         spincnt = 0;
1201                 if (spincnt > 10) {
1202                         rnp->boost_kthread_status = RCU_KTHREAD_YIELDING;
1203                         trace_rcu_utilization(TPS("End boost kthread@rcu_yield"));
1204                         schedule_timeout_interruptible(2);
1205                         trace_rcu_utilization(TPS("Start boost kthread@rcu_yield"));
1206                         spincnt = 0;
1207                 }
1208         }
1209         /* NOTREACHED */
1210         trace_rcu_utilization(TPS("End boost kthread@notreached"));
1211         return 0;
1212 }
1213
1214 /*
1215  * Check to see if it is time to start boosting RCU readers that are
1216  * blocking the current grace period, and, if so, tell the per-rcu_node
1217  * kthread to start boosting them.  If there is an expedited grace
1218  * period in progress, it is always time to boost.
1219  *
1220  * The caller must hold rnp->lock, which this function releases.
1221  * The ->boost_kthread_task is immortal, so we don't need to worry
1222  * about it going away.
1223  */
1224 static void rcu_initiate_boost(struct rcu_node *rnp, unsigned long flags)
1225         __releases(rnp->lock)
1226 {
1227         struct task_struct *t;
1228
1229         raw_lockdep_assert_held_rcu_node(rnp);
1230         if (!rcu_preempt_blocked_readers_cgp(rnp) && rnp->exp_tasks == NULL) {
1231                 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1232                 return;
1233         }
1234         if (rnp->exp_tasks != NULL ||
1235             (rnp->gp_tasks != NULL &&
1236              rnp->boost_tasks == NULL &&
1237              rnp->qsmask == 0 &&
1238              ULONG_CMP_GE(jiffies, rnp->boost_time))) {
1239                 if (rnp->exp_tasks == NULL)
1240                         rnp->boost_tasks = rnp->gp_tasks;
1241                 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1242                 t = rnp->boost_kthread_task;
1243                 if (t)
1244                         rcu_wake_cond(t, rnp->boost_kthread_status);
1245         } else {
1246                 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1247         }
1248 }
1249
1250 /*
1251  * Wake up the per-CPU kthread to invoke RCU callbacks.
1252  */
1253 static void invoke_rcu_callbacks_kthread(void)
1254 {
1255         unsigned long flags;
1256
1257         local_irq_save(flags);
1258         __this_cpu_write(rcu_cpu_has_work, 1);
1259         if (__this_cpu_read(rcu_cpu_kthread_task) != NULL &&
1260             current != __this_cpu_read(rcu_cpu_kthread_task)) {
1261                 rcu_wake_cond(__this_cpu_read(rcu_cpu_kthread_task),
1262                               __this_cpu_read(rcu_cpu_kthread_status));
1263         }
1264         local_irq_restore(flags);
1265 }
1266
1267 /*
1268  * Is the current CPU running the RCU-callbacks kthread?
1269  * Caller must have preemption disabled.
1270  */
1271 static bool rcu_is_callbacks_kthread(void)
1272 {
1273         return __this_cpu_read(rcu_cpu_kthread_task) == current;
1274 }
1275
1276 #define RCU_BOOST_DELAY_JIFFIES DIV_ROUND_UP(CONFIG_RCU_BOOST_DELAY * HZ, 1000)
1277
1278 /*
1279  * Do priority-boost accounting for the start of a new grace period.
1280  */
1281 static void rcu_preempt_boost_start_gp(struct rcu_node *rnp)
1282 {
1283         rnp->boost_time = jiffies + RCU_BOOST_DELAY_JIFFIES;
1284 }
1285
1286 /*
1287  * Create an RCU-boost kthread for the specified node if one does not
1288  * already exist.  We only create this kthread for preemptible RCU.
1289  * Returns zero if all is well, a negated errno otherwise.
1290  */
1291 static int rcu_spawn_one_boost_kthread(struct rcu_node *rnp)
1292 {
1293         int rnp_index = rnp - rcu_get_root();
1294         unsigned long flags;
1295         struct sched_param sp;
1296         struct task_struct *t;
1297
1298         if (!IS_ENABLED(CONFIG_PREEMPT_RCU))
1299                 return 0;
1300
1301         if (!rcu_scheduler_fully_active || rcu_rnp_online_cpus(rnp) == 0)
1302                 return 0;
1303
1304         rcu_state.boost = 1;
1305         if (rnp->boost_kthread_task != NULL)
1306                 return 0;
1307         t = kthread_create(rcu_boost_kthread, (void *)rnp,
1308                            "rcub/%d", rnp_index);
1309         if (IS_ERR(t))
1310                 return PTR_ERR(t);
1311         raw_spin_lock_irqsave_rcu_node(rnp, flags);
1312         rnp->boost_kthread_task = t;
1313         raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1314         sp.sched_priority = kthread_prio;
1315         sched_setscheduler_nocheck(t, SCHED_FIFO, &sp);
1316         wake_up_process(t); /* get to TASK_INTERRUPTIBLE quickly. */
1317         return 0;
1318 }
1319
1320 static void rcu_kthread_do_work(void)
1321 {
1322         rcu_do_batch(this_cpu_ptr(&rcu_data));
1323 }
1324
1325 static void rcu_cpu_kthread_setup(unsigned int cpu)
1326 {
1327         struct sched_param sp;
1328
1329         sp.sched_priority = kthread_prio;
1330         sched_setscheduler_nocheck(current, SCHED_FIFO, &sp);
1331 }
1332
1333 static void rcu_cpu_kthread_park(unsigned int cpu)
1334 {
1335         per_cpu(rcu_cpu_kthread_status, cpu) = RCU_KTHREAD_OFFCPU;
1336 }
1337
1338 static int rcu_cpu_kthread_should_run(unsigned int cpu)
1339 {
1340         return __this_cpu_read(rcu_cpu_has_work);
1341 }
1342
1343 /*
1344  * Per-CPU kernel thread that invokes RCU callbacks.  This replaces the
1345  * RCU softirq used in flavors and configurations of RCU that do not
1346  * support RCU priority boosting.
1347  */
1348 static void rcu_cpu_kthread(unsigned int cpu)
1349 {
1350         unsigned int *statusp = this_cpu_ptr(&rcu_cpu_kthread_status);
1351         char work, *workp = this_cpu_ptr(&rcu_cpu_has_work);
1352         int spincnt;
1353
1354         for (spincnt = 0; spincnt < 10; spincnt++) {
1355                 trace_rcu_utilization(TPS("Start CPU kthread@rcu_wait"));
1356                 local_bh_disable();
1357                 *statusp = RCU_KTHREAD_RUNNING;
1358                 this_cpu_inc(rcu_cpu_kthread_loops);
1359                 local_irq_disable();
1360                 work = *workp;
1361                 *workp = 0;
1362                 local_irq_enable();
1363                 if (work)
1364                         rcu_kthread_do_work();
1365                 local_bh_enable();
1366                 if (*workp == 0) {
1367                         trace_rcu_utilization(TPS("End CPU kthread@rcu_wait"));
1368                         *statusp = RCU_KTHREAD_WAITING;
1369                         return;
1370                 }
1371         }
1372         *statusp = RCU_KTHREAD_YIELDING;
1373         trace_rcu_utilization(TPS("Start CPU kthread@rcu_yield"));
1374         schedule_timeout_interruptible(2);
1375         trace_rcu_utilization(TPS("End CPU kthread@rcu_yield"));
1376         *statusp = RCU_KTHREAD_WAITING;
1377 }
1378
1379 /*
1380  * Set the per-rcu_node kthread's affinity to cover all CPUs that are
1381  * served by the rcu_node in question.  The CPU hotplug lock is still
1382  * held, so the value of rnp->qsmaskinit will be stable.
1383  *
1384  * We don't include outgoingcpu in the affinity set, use -1 if there is
1385  * no outgoing CPU.  If there are no CPUs left in the affinity set,
1386  * this function allows the kthread to execute on any CPU.
1387  */
1388 static void rcu_boost_kthread_setaffinity(struct rcu_node *rnp, int outgoingcpu)
1389 {
1390         struct task_struct *t = rnp->boost_kthread_task;
1391         unsigned long mask = rcu_rnp_online_cpus(rnp);
1392         cpumask_var_t cm;
1393         int cpu;
1394
1395         if (!t)
1396                 return;
1397         if (!zalloc_cpumask_var(&cm, GFP_KERNEL))
1398                 return;
1399         for_each_leaf_node_possible_cpu(rnp, cpu)
1400                 if ((mask & leaf_node_cpu_bit(rnp, cpu)) &&
1401                     cpu != outgoingcpu)
1402                         cpumask_set_cpu(cpu, cm);
1403         if (cpumask_weight(cm) == 0)
1404                 cpumask_setall(cm);
1405         set_cpus_allowed_ptr(t, cm);
1406         free_cpumask_var(cm);
1407 }
1408
1409 static struct smp_hotplug_thread rcu_cpu_thread_spec = {
1410         .store                  = &rcu_cpu_kthread_task,
1411         .thread_should_run      = rcu_cpu_kthread_should_run,
1412         .thread_fn              = rcu_cpu_kthread,
1413         .thread_comm            = "rcuc/%u",
1414         .setup                  = rcu_cpu_kthread_setup,
1415         .park                   = rcu_cpu_kthread_park,
1416 };
1417
1418 /*
1419  * Spawn boost kthreads -- called as soon as the scheduler is running.
1420  */
1421 static void __init rcu_spawn_boost_kthreads(void)
1422 {
1423         struct rcu_node *rnp;
1424         int cpu;
1425
1426         for_each_possible_cpu(cpu)
1427                 per_cpu(rcu_cpu_has_work, cpu) = 0;
1428         BUG_ON(smpboot_register_percpu_thread(&rcu_cpu_thread_spec));
1429         rcu_for_each_leaf_node(rnp)
1430                 (void)rcu_spawn_one_boost_kthread(rnp);
1431 }
1432
1433 static void rcu_prepare_kthreads(int cpu)
1434 {
1435         struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
1436         struct rcu_node *rnp = rdp->mynode;
1437
1438         /* Fire up the incoming CPU's kthread and leaf rcu_node kthread. */
1439         if (rcu_scheduler_fully_active)
1440                 (void)rcu_spawn_one_boost_kthread(rnp);
1441 }
1442
1443 #else /* #ifdef CONFIG_RCU_BOOST */
1444
1445 static void rcu_initiate_boost(struct rcu_node *rnp, unsigned long flags)
1446         __releases(rnp->lock)
1447 {
1448         raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
1449 }
1450
1451 static void invoke_rcu_callbacks_kthread(void)
1452 {
1453         WARN_ON_ONCE(1);
1454 }
1455
1456 static bool rcu_is_callbacks_kthread(void)
1457 {
1458         return false;
1459 }
1460
1461 static void rcu_preempt_boost_start_gp(struct rcu_node *rnp)
1462 {
1463 }
1464
1465 static void rcu_boost_kthread_setaffinity(struct rcu_node *rnp, int outgoingcpu)
1466 {
1467 }
1468
1469 static void __init rcu_spawn_boost_kthreads(void)
1470 {
1471 }
1472
1473 static void rcu_prepare_kthreads(int cpu)
1474 {
1475 }
1476
1477 #endif /* #else #ifdef CONFIG_RCU_BOOST */
1478
1479 #if !defined(CONFIG_RCU_FAST_NO_HZ)
1480
1481 /*
1482  * Check to see if any future RCU-related work will need to be done
1483  * by the current CPU, even if none need be done immediately, returning
1484  * 1 if so.  This function is part of the RCU implementation; it is -not-
1485  * an exported member of the RCU API.
1486  *
1487  * Because we not have RCU_FAST_NO_HZ, just check whether this CPU needs
1488  * any flavor of RCU.
1489  */
1490 int rcu_needs_cpu(u64 basemono, u64 *nextevt)
1491 {
1492         *nextevt = KTIME_MAX;
1493         return rcu_cpu_has_callbacks(NULL);
1494 }
1495
1496 /*
1497  * Because we do not have RCU_FAST_NO_HZ, don't bother cleaning up
1498  * after it.
1499  */
1500 static void rcu_cleanup_after_idle(void)
1501 {
1502 }
1503
1504 /*
1505  * Do the idle-entry grace-period work, which, because CONFIG_RCU_FAST_NO_HZ=n,
1506  * is nothing.
1507  */
1508 static void rcu_prepare_for_idle(void)
1509 {
1510 }
1511
1512 /*
1513  * Don't bother keeping a running count of the number of RCU callbacks
1514  * posted because CONFIG_RCU_FAST_NO_HZ=n.
1515  */
1516 static void rcu_idle_count_callbacks_posted(void)
1517 {
1518 }
1519
1520 #else /* #if !defined(CONFIG_RCU_FAST_NO_HZ) */
1521
1522 /*
1523  * This code is invoked when a CPU goes idle, at which point we want
1524  * to have the CPU do everything required for RCU so that it can enter
1525  * the energy-efficient dyntick-idle mode.  This is handled by a
1526  * state machine implemented by rcu_prepare_for_idle() below.
1527  *
1528  * The following three proprocessor symbols control this state machine:
1529  *
1530  * RCU_IDLE_GP_DELAY gives the number of jiffies that a CPU is permitted
1531  *      to sleep in dyntick-idle mode with RCU callbacks pending.  This
1532  *      is sized to be roughly one RCU grace period.  Those energy-efficiency
1533  *      benchmarkers who might otherwise be tempted to set this to a large
1534  *      number, be warned: Setting RCU_IDLE_GP_DELAY too high can hang your
1535  *      system.  And if you are -that- concerned about energy efficiency,
1536  *      just power the system down and be done with it!
1537  * RCU_IDLE_LAZY_GP_DELAY gives the number of jiffies that a CPU is
1538  *      permitted to sleep in dyntick-idle mode with only lazy RCU
1539  *      callbacks pending.  Setting this too high can OOM your system.
1540  *
1541  * The values below work well in practice.  If future workloads require
1542  * adjustment, they can be converted into kernel config parameters, though
1543  * making the state machine smarter might be a better option.
1544  */
1545 #define RCU_IDLE_GP_DELAY 4             /* Roughly one grace period. */
1546 #define RCU_IDLE_LAZY_GP_DELAY (6 * HZ) /* Roughly six seconds. */
1547
1548 static int rcu_idle_gp_delay = RCU_IDLE_GP_DELAY;
1549 module_param(rcu_idle_gp_delay, int, 0644);
1550 static int rcu_idle_lazy_gp_delay = RCU_IDLE_LAZY_GP_DELAY;
1551 module_param(rcu_idle_lazy_gp_delay, int, 0644);
1552
1553 /*
1554  * Try to advance callbacks for all flavors of RCU on the current CPU, but
1555  * only if it has been awhile since the last time we did so.  Afterwards,
1556  * if there are any callbacks ready for immediate invocation, return true.
1557  */
1558 static bool __maybe_unused rcu_try_advance_all_cbs(void)
1559 {
1560         bool cbs_ready = false;
1561         struct rcu_data *rdp;
1562         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
1563         struct rcu_node *rnp;
1564         struct rcu_state *rsp;
1565
1566         /* Exit early if we advanced recently. */
1567         if (jiffies == rdtp->last_advance_all)
1568                 return false;
1569         rdtp->last_advance_all = jiffies;
1570
1571         for_each_rcu_flavor(rsp) {
1572                 rdp = this_cpu_ptr(&rcu_data);
1573                 rnp = rdp->mynode;
1574
1575                 /*
1576                  * Don't bother checking unless a grace period has
1577                  * completed since we last checked and there are
1578                  * callbacks not yet ready to invoke.
1579                  */
1580                 if ((rcu_seq_completed_gp(rdp->gp_seq,
1581                                           rcu_seq_current(&rnp->gp_seq)) ||
1582                      unlikely(READ_ONCE(rdp->gpwrap))) &&
1583                     rcu_segcblist_pend_cbs(&rdp->cblist))
1584                         note_gp_changes(rdp);
1585
1586                 if (rcu_segcblist_ready_cbs(&rdp->cblist))
1587                         cbs_ready = true;
1588         }
1589         return cbs_ready;
1590 }
1591
1592 /*
1593  * Allow the CPU to enter dyntick-idle mode unless it has callbacks ready
1594  * to invoke.  If the CPU has callbacks, try to advance them.  Tell the
1595  * caller to set the timeout based on whether or not there are non-lazy
1596  * callbacks.
1597  *
1598  * The caller must have disabled interrupts.
1599  */
1600 int rcu_needs_cpu(u64 basemono, u64 *nextevt)
1601 {
1602         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
1603         unsigned long dj;
1604
1605         lockdep_assert_irqs_disabled();
1606
1607         /* Snapshot to detect later posting of non-lazy callback. */
1608         rdtp->nonlazy_posted_snap = rdtp->nonlazy_posted;
1609
1610         /* If no callbacks, RCU doesn't need the CPU. */
1611         if (!rcu_cpu_has_callbacks(&rdtp->all_lazy)) {
1612                 *nextevt = KTIME_MAX;
1613                 return 0;
1614         }
1615
1616         /* Attempt to advance callbacks. */
1617         if (rcu_try_advance_all_cbs()) {
1618                 /* Some ready to invoke, so initiate later invocation. */
1619                 invoke_rcu_core();
1620                 return 1;
1621         }
1622         rdtp->last_accelerate = jiffies;
1623
1624         /* Request timer delay depending on laziness, and round. */
1625         if (!rdtp->all_lazy) {
1626                 dj = round_up(rcu_idle_gp_delay + jiffies,
1627                                rcu_idle_gp_delay) - jiffies;
1628         } else {
1629                 dj = round_jiffies(rcu_idle_lazy_gp_delay + jiffies) - jiffies;
1630         }
1631         *nextevt = basemono + dj * TICK_NSEC;
1632         return 0;
1633 }
1634
1635 /*
1636  * Prepare a CPU for idle from an RCU perspective.  The first major task
1637  * is to sense whether nohz mode has been enabled or disabled via sysfs.
1638  * The second major task is to check to see if a non-lazy callback has
1639  * arrived at a CPU that previously had only lazy callbacks.  The third
1640  * major task is to accelerate (that is, assign grace-period numbers to)
1641  * any recently arrived callbacks.
1642  *
1643  * The caller must have disabled interrupts.
1644  */
1645 static void rcu_prepare_for_idle(void)
1646 {
1647         bool needwake;
1648         struct rcu_data *rdp;
1649         struct rcu_dynticks *rdtp = this_cpu_ptr(&rcu_dynticks);
1650         struct rcu_node *rnp;
1651         struct rcu_state *rsp;
1652         int tne;
1653
1654         lockdep_assert_irqs_disabled();
1655         if (rcu_is_nocb_cpu(smp_processor_id()))
1656                 return;
1657
1658         /* Handle nohz enablement switches conservatively. */
1659         tne = READ_ONCE(tick_nohz_active);
1660         if (tne != rdtp->tick_nohz_enabled_snap) {
1661                 if (rcu_cpu_has_callbacks(NULL))
1662                         invoke_rcu_core(); /* force nohz to see update. */
1663                 rdtp->tick_nohz_enabled_snap = tne;
1664                 return;
1665         }
1666         if (!tne)
1667                 return;
1668
1669         /*
1670          * If a non-lazy callback arrived at a CPU having only lazy
1671          * callbacks, invoke RCU core for the side-effect of recalculating
1672          * idle duration on re-entry to idle.
1673          */
1674         if (rdtp->all_lazy &&
1675             rdtp->nonlazy_posted != rdtp->nonlazy_posted_snap) {
1676                 rdtp->all_lazy = false;
1677                 rdtp->nonlazy_posted_snap = rdtp->nonlazy_posted;
1678                 invoke_rcu_core();
1679                 return;
1680         }
1681
1682         /*
1683          * If we have not yet accelerated this jiffy, accelerate all
1684          * callbacks on this CPU.
1685          */
1686         if (rdtp->last_accelerate == jiffies)
1687                 return;
1688         rdtp->last_accelerate = jiffies;
1689         for_each_rcu_flavor(rsp) {
1690                 rdp = this_cpu_ptr(&rcu_data);
1691                 if (!rcu_segcblist_pend_cbs(&rdp->cblist))
1692                         continue;
1693                 rnp = rdp->mynode;
1694                 raw_spin_lock_rcu_node(rnp); /* irqs already disabled. */
1695                 needwake = rcu_accelerate_cbs(rnp, rdp);
1696                 raw_spin_unlock_rcu_node(rnp); /* irqs remain disabled. */
1697                 if (needwake)
1698                         rcu_gp_kthread_wake();
1699         }
1700 }
1701
1702 /*
1703  * Clean up for exit from idle.  Attempt to advance callbacks based on
1704  * any grace periods that elapsed while the CPU was idle, and if any
1705  * callbacks are now ready to invoke, initiate invocation.
1706  */
1707 static void rcu_cleanup_after_idle(void)
1708 {
1709         lockdep_assert_irqs_disabled();
1710         if (rcu_is_nocb_cpu(smp_processor_id()))
1711                 return;
1712         if (rcu_try_advance_all_cbs())
1713                 invoke_rcu_core();
1714 }
1715
1716 /*
1717  * Keep a running count of the number of non-lazy callbacks posted
1718  * on this CPU.  This running counter (which is never decremented) allows
1719  * rcu_prepare_for_idle() to detect when something out of the idle loop
1720  * posts a callback, even if an equal number of callbacks are invoked.
1721  * Of course, callbacks should only be posted from within a trace event
1722  * designed to be called from idle or from within RCU_NONIDLE().
1723  */
1724 static void rcu_idle_count_callbacks_posted(void)
1725 {
1726         __this_cpu_add(rcu_dynticks.nonlazy_posted, 1);
1727 }
1728
1729 #endif /* #else #if !defined(CONFIG_RCU_FAST_NO_HZ) */
1730
1731 #ifdef CONFIG_RCU_FAST_NO_HZ
1732
1733 static void print_cpu_stall_fast_no_hz(char *cp, int cpu)
1734 {
1735         struct rcu_dynticks *rdtp = &per_cpu(rcu_dynticks, cpu);
1736         unsigned long nlpd = rdtp->nonlazy_posted - rdtp->nonlazy_posted_snap;
1737
1738         sprintf(cp, "last_accelerate: %04lx/%04lx, nonlazy_posted: %ld, %c%c",
1739                 rdtp->last_accelerate & 0xffff, jiffies & 0xffff,
1740                 ulong2long(nlpd),
1741                 rdtp->all_lazy ? 'L' : '.',
1742                 rdtp->tick_nohz_enabled_snap ? '.' : 'D');
1743 }
1744
1745 #else /* #ifdef CONFIG_RCU_FAST_NO_HZ */
1746
1747 static void print_cpu_stall_fast_no_hz(char *cp, int cpu)
1748 {
1749         *cp = '\0';
1750 }
1751
1752 #endif /* #else #ifdef CONFIG_RCU_FAST_NO_HZ */
1753
1754 /* Initiate the stall-info list. */
1755 static void print_cpu_stall_info_begin(void)
1756 {
1757         pr_cont("\n");
1758 }
1759
1760 /*
1761  * Print out diagnostic information for the specified stalled CPU.
1762  *
1763  * If the specified CPU is aware of the current RCU grace period, then
1764  * print the number of scheduling clock interrupts the CPU has taken
1765  * during the time that it has been aware.  Otherwise, print the number
1766  * of RCU grace periods that this CPU is ignorant of, for example, "1"
1767  * if the CPU was aware of the previous grace period.
1768  *
1769  * Also print out idle and (if CONFIG_RCU_FAST_NO_HZ) idle-entry info.
1770  */
1771 static void print_cpu_stall_info(int cpu)
1772 {
1773         unsigned long delta;
1774         char fast_no_hz[72];
1775         struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
1776         struct rcu_dynticks *rdtp = rdp->dynticks;
1777         char *ticks_title;
1778         unsigned long ticks_value;
1779
1780         /*
1781          * We could be printing a lot while holding a spinlock.  Avoid
1782          * triggering hard lockup.
1783          */
1784         touch_nmi_watchdog();
1785
1786         ticks_value = rcu_seq_ctr(rcu_state.gp_seq - rdp->gp_seq);
1787         if (ticks_value) {
1788                 ticks_title = "GPs behind";
1789         } else {
1790                 ticks_title = "ticks this GP";
1791                 ticks_value = rdp->ticks_this_gp;
1792         }
1793         print_cpu_stall_fast_no_hz(fast_no_hz, cpu);
1794         delta = rcu_seq_ctr(rdp->mynode->gp_seq - rdp->rcu_iw_gp_seq);
1795         pr_err("\t%d-%c%c%c%c: (%lu %s) idle=%03x/%ld/%#lx softirq=%u/%u fqs=%ld %s\n",
1796                cpu,
1797                "O."[!!cpu_online(cpu)],
1798                "o."[!!(rdp->grpmask & rdp->mynode->qsmaskinit)],
1799                "N."[!!(rdp->grpmask & rdp->mynode->qsmaskinitnext)],
1800                !IS_ENABLED(CONFIG_IRQ_WORK) ? '?' :
1801                         rdp->rcu_iw_pending ? (int)min(delta, 9UL) + '0' :
1802                                 "!."[!delta],
1803                ticks_value, ticks_title,
1804                rcu_dynticks_snap(rdtp) & 0xfff,
1805                rdtp->dynticks_nesting, rdtp->dynticks_nmi_nesting,
1806                rdp->softirq_snap, kstat_softirqs_cpu(RCU_SOFTIRQ, cpu),
1807                READ_ONCE(rcu_state.n_force_qs) - rcu_state.n_force_qs_gpstart,
1808                fast_no_hz);
1809 }
1810
1811 /* Terminate the stall-info list. */
1812 static void print_cpu_stall_info_end(void)
1813 {
1814         pr_err("\t");
1815 }
1816
1817 /* Zero ->ticks_this_gp for all flavors of RCU. */
1818 static void zero_cpu_stall_ticks(struct rcu_data *rdp)
1819 {
1820         rdp->ticks_this_gp = 0;
1821         rdp->softirq_snap = kstat_softirqs_cpu(RCU_SOFTIRQ, smp_processor_id());
1822 }
1823
1824 /* Increment ->ticks_this_gp for all flavors of RCU. */
1825 static void increment_cpu_stall_ticks(void)
1826 {
1827         struct rcu_state *rsp;
1828
1829         for_each_rcu_flavor(rsp)
1830                 raw_cpu_inc(rcu_data.ticks_this_gp);
1831 }
1832
1833 #ifdef CONFIG_RCU_NOCB_CPU
1834
1835 /*
1836  * Offload callback processing from the boot-time-specified set of CPUs
1837  * specified by rcu_nocb_mask.  For each CPU in the set, there is a
1838  * kthread created that pulls the callbacks from the corresponding CPU,
1839  * waits for a grace period to elapse, and invokes the callbacks.
1840  * The no-CBs CPUs do a wake_up() on their kthread when they insert
1841  * a callback into any empty list, unless the rcu_nocb_poll boot parameter
1842  * has been specified, in which case each kthread actively polls its
1843  * CPU.  (Which isn't so great for energy efficiency, but which does
1844  * reduce RCU's overhead on that CPU.)
1845  *
1846  * This is intended to be used in conjunction with Frederic Weisbecker's
1847  * adaptive-idle work, which would seriously reduce OS jitter on CPUs
1848  * running CPU-bound user-mode computations.
1849  *
1850  * Offloading of callback processing could also in theory be used as
1851  * an energy-efficiency measure because CPUs with no RCU callbacks
1852  * queued are more aggressive about entering dyntick-idle mode.
1853  */
1854
1855
1856 /* Parse the boot-time rcu_nocb_mask CPU list from the kernel parameters. */
1857 static int __init rcu_nocb_setup(char *str)
1858 {
1859         alloc_bootmem_cpumask_var(&rcu_nocb_mask);
1860         cpulist_parse(str, rcu_nocb_mask);
1861         return 1;
1862 }
1863 __setup("rcu_nocbs=", rcu_nocb_setup);
1864
1865 static int __init parse_rcu_nocb_poll(char *arg)
1866 {
1867         rcu_nocb_poll = true;
1868         return 0;
1869 }
1870 early_param("rcu_nocb_poll", parse_rcu_nocb_poll);
1871
1872 /*
1873  * Wake up any no-CBs CPUs' kthreads that were waiting on the just-ended
1874  * grace period.
1875  */
1876 static void rcu_nocb_gp_cleanup(struct swait_queue_head *sq)
1877 {
1878         swake_up_all(sq);
1879 }
1880
1881 static struct swait_queue_head *rcu_nocb_gp_get(struct rcu_node *rnp)
1882 {
1883         return &rnp->nocb_gp_wq[rcu_seq_ctr(rnp->gp_seq) & 0x1];
1884 }
1885
1886 static void rcu_init_one_nocb(struct rcu_node *rnp)
1887 {
1888         init_swait_queue_head(&rnp->nocb_gp_wq[0]);
1889         init_swait_queue_head(&rnp->nocb_gp_wq[1]);
1890 }
1891
1892 /* Is the specified CPU a no-CBs CPU? */
1893 bool rcu_is_nocb_cpu(int cpu)
1894 {
1895         if (cpumask_available(rcu_nocb_mask))
1896                 return cpumask_test_cpu(cpu, rcu_nocb_mask);
1897         return false;
1898 }
1899
1900 /*
1901  * Kick the leader kthread for this NOCB group.  Caller holds ->nocb_lock
1902  * and this function releases it.
1903  */
1904 static void __wake_nocb_leader(struct rcu_data *rdp, bool force,
1905                                unsigned long flags)
1906         __releases(rdp->nocb_lock)
1907 {
1908         struct rcu_data *rdp_leader = rdp->nocb_leader;
1909
1910         lockdep_assert_held(&rdp->nocb_lock);
1911         if (!READ_ONCE(rdp_leader->nocb_kthread)) {
1912                 raw_spin_unlock_irqrestore(&rdp->nocb_lock, flags);
1913                 return;
1914         }
1915         if (rdp_leader->nocb_leader_sleep || force) {
1916                 /* Prior smp_mb__after_atomic() orders against prior enqueue. */
1917                 WRITE_ONCE(rdp_leader->nocb_leader_sleep, false);
1918                 del_timer(&rdp->nocb_timer);
1919                 raw_spin_unlock_irqrestore(&rdp->nocb_lock, flags);
1920                 smp_mb(); /* ->nocb_leader_sleep before swake_up_one(). */
1921                 swake_up_one(&rdp_leader->nocb_wq);
1922         } else {
1923                 raw_spin_unlock_irqrestore(&rdp->nocb_lock, flags);
1924         }
1925 }
1926
1927 /*
1928  * Kick the leader kthread for this NOCB group, but caller has not
1929  * acquired locks.
1930  */
1931 static void wake_nocb_leader(struct rcu_data *rdp, bool force)
1932 {
1933         unsigned long flags;
1934
1935         raw_spin_lock_irqsave(&rdp->nocb_lock, flags);
1936         __wake_nocb_leader(rdp, force, flags);
1937 }
1938
1939 /*
1940  * Arrange to wake the leader kthread for this NOCB group at some
1941  * future time when it is safe to do so.
1942  */
1943 static void wake_nocb_leader_defer(struct rcu_data *rdp, int waketype,
1944                                    const char *reason)
1945 {
1946         unsigned long flags;
1947
1948         raw_spin_lock_irqsave(&rdp->nocb_lock, flags);
1949         if (rdp->nocb_defer_wakeup == RCU_NOCB_WAKE_NOT)
1950                 mod_timer(&rdp->nocb_timer, jiffies + 1);
1951         WRITE_ONCE(rdp->nocb_defer_wakeup, waketype);
1952         trace_rcu_nocb_wake(rcu_state.name, rdp->cpu, reason);
1953         raw_spin_unlock_irqrestore(&rdp->nocb_lock, flags);
1954 }
1955
1956 /*
1957  * Does the specified CPU need an RCU callback for the specified flavor
1958  * of rcu_barrier()?
1959  */
1960 static bool rcu_nocb_cpu_needs_barrier(int cpu)
1961 {
1962         struct rcu_data *rdp = per_cpu_ptr(&rcu_data, cpu);
1963         unsigned long ret;
1964 #ifdef CONFIG_PROVE_RCU
1965         struct rcu_head *rhp;
1966 #endif /* #ifdef CONFIG_PROVE_RCU */
1967
1968         /*
1969          * Check count of all no-CBs callbacks awaiting invocation.
1970          * There needs to be a barrier before this function is called,
1971          * but associated with a prior determination that no more
1972          * callbacks would be posted.  In the worst case, the first
1973          * barrier in _rcu_barrier() suffices (but the caller cannot
1974          * necessarily rely on this, not a substitute for the caller
1975          * getting the concurrency design right!).  There must also be
1976          * a barrier between the following load an posting of a callback
1977          * (if a callback is in fact needed).  This is associated with an
1978          * atomic_inc() in the caller.
1979          */
1980         ret = atomic_long_read(&rdp->nocb_q_count);
1981
1982 #ifdef CONFIG_PROVE_RCU
1983         rhp = READ_ONCE(rdp->nocb_head);
1984         if (!rhp)
1985                 rhp = READ_ONCE(rdp->nocb_gp_head);
1986         if (!rhp)
1987                 rhp = READ_ONCE(rdp->nocb_follower_head);
1988
1989         /* Having no rcuo kthread but CBs after scheduler starts is bad! */
1990         if (!READ_ONCE(rdp->nocb_kthread) && rhp &&
1991             rcu_scheduler_fully_active) {
1992                 /* RCU callback enqueued before CPU first came online??? */
1993                 pr_err("RCU: Never-onlined no-CBs CPU %d has CB %p\n",
1994                        cpu, rhp->func);
1995                 WARN_ON_ONCE(1);
1996         }
1997 #endif /* #ifdef CONFIG_PROVE_RCU */
1998
1999         return !!ret;
2000 }
2001
2002 /*
2003  * Enqueue the specified string of rcu_head structures onto the specified
2004  * CPU's no-CBs lists.  The CPU is specified by rdp, the head of the
2005  * string by rhp, and the tail of the string by rhtp.  The non-lazy/lazy
2006  * counts are supplied by rhcount and rhcount_lazy.
2007  *
2008  * If warranted, also wake up the kthread servicing this CPUs queues.
2009  */
2010 static void __call_rcu_nocb_enqueue(struct rcu_data *rdp,
2011                                     struct rcu_head *rhp,
2012                                     struct rcu_head **rhtp,
2013                                     int rhcount, int rhcount_lazy,
2014                                     unsigned long flags)
2015 {
2016         int len;
2017         struct rcu_head **old_rhpp;
2018         struct task_struct *t;
2019
2020         /* Enqueue the callback on the nocb list and update counts. */
2021         atomic_long_add(rhcount, &rdp->nocb_q_count);
2022         /* rcu_barrier() relies on ->nocb_q_count add before xchg. */
2023         old_rhpp = xchg(&rdp->nocb_tail, rhtp);
2024         WRITE_ONCE(*old_rhpp, rhp);
2025         atomic_long_add(rhcount_lazy, &rdp->nocb_q_count_lazy);
2026         smp_mb__after_atomic(); /* Store *old_rhpp before _wake test. */
2027
2028         /* If we are not being polled and there is a kthread, awaken it ... */
2029         t = READ_ONCE(rdp->nocb_kthread);
2030         if (rcu_nocb_poll || !t) {
2031                 trace_rcu_nocb_wake(rcu_state.name, rdp->cpu,
2032                                     TPS("WakeNotPoll"));
2033                 return;
2034         }
2035         len = atomic_long_read(&rdp->nocb_q_count);
2036         if (old_rhpp == &rdp->nocb_head) {
2037                 if (!irqs_disabled_flags(flags)) {
2038                         /* ... if queue was empty ... */
2039                         wake_nocb_leader(rdp, false);
2040                         trace_rcu_nocb_wake(rcu_state.name, rdp->cpu,
2041                                             TPS("WakeEmpty"));
2042                 } else {
2043                         wake_nocb_leader_defer(rdp, RCU_NOCB_WAKE,
2044                                                TPS("WakeEmptyIsDeferred"));
2045                 }
2046                 rdp->qlen_last_fqs_check = 0;
2047         } else if (len > rdp->qlen_last_fqs_check + qhimark) {
2048                 /* ... or if many callbacks queued. */
2049                 if (!irqs_disabled_flags(flags)) {
2050                         wake_nocb_leader(rdp, true);
2051                         trace_rcu_nocb_wake(rcu_state.name, rdp->cpu,
2052                                             TPS("WakeOvf"));
2053                 } else {
2054                         wake_nocb_leader_defer(rdp, RCU_NOCB_WAKE_FORCE,
2055                                                TPS("WakeOvfIsDeferred"));
2056                 }
2057                 rdp->qlen_last_fqs_check = LONG_MAX / 2;
2058         } else {
2059                 trace_rcu_nocb_wake(rcu_state.name, rdp->cpu, TPS("WakeNot"));
2060         }
2061         return;
2062 }
2063
2064 /*
2065  * This is a helper for __call_rcu(), which invokes this when the normal
2066  * callback queue is inoperable.  If this is not a no-CBs CPU, this
2067  * function returns failure back to __call_rcu(), which can complain
2068  * appropriately.
2069  *
2070  * Otherwise, this function queues the callback where the corresponding
2071  * "rcuo" kthread can find it.
2072  */
2073 static bool __call_rcu_nocb(struct rcu_data *rdp, struct rcu_head *rhp,
2074                             bool lazy, unsigned long flags)
2075 {
2076
2077         if (!rcu_is_nocb_cpu(rdp->cpu))
2078                 return false;
2079         __call_rcu_nocb_enqueue(rdp, rhp, &rhp->next, 1, lazy, flags);
2080         if (__is_kfree_rcu_offset((unsigned long)rhp->func))
2081                 trace_rcu_kfree_callback(rcu_state.name, rhp,
2082                                          (unsigned long)rhp->func,
2083                                          -atomic_long_read(&rdp->nocb_q_count_lazy),
2084                                          -atomic_long_read(&rdp->nocb_q_count));
2085         else
2086                 trace_rcu_callback(rcu_state.name, rhp,
2087                                    -atomic_long_read(&rdp->nocb_q_count_lazy),
2088                                    -atomic_long_read(&rdp->nocb_q_count));
2089
2090         /*
2091          * If called from an extended quiescent state with interrupts
2092          * disabled, invoke the RCU core in order to allow the idle-entry
2093          * deferred-wakeup check to function.
2094          */
2095         if (irqs_disabled_flags(flags) &&
2096             !rcu_is_watching() &&
2097             cpu_online(smp_processor_id()))
2098                 invoke_rcu_core();
2099
2100         return true;
2101 }
2102
2103 /*
2104  * Adopt orphaned callbacks on a no-CBs CPU, or return 0 if this is
2105  * not a no-CBs CPU.
2106  */
2107 static bool __maybe_unused rcu_nocb_adopt_orphan_cbs(struct rcu_data *my_rdp,
2108                                                      struct rcu_data *rdp,
2109                                                      unsigned long flags)
2110 {
2111         lockdep_assert_irqs_disabled();
2112         if (!rcu_is_nocb_cpu(smp_processor_id()))
2113                 return false; /* Not NOCBs CPU, caller must migrate CBs. */
2114         __call_rcu_nocb_enqueue(my_rdp, rcu_segcblist_head(&rdp->cblist),
2115                                 rcu_segcblist_tail(&rdp->cblist),
2116                                 rcu_segcblist_n_cbs(&rdp->cblist),
2117                                 rcu_segcblist_n_lazy_cbs(&rdp->cblist), flags);
2118         rcu_segcblist_init(&rdp->cblist);
2119         rcu_segcblist_disable(&rdp->cblist);
2120         return true;
2121 }
2122
2123 /*
2124  * If necessary, kick off a new grace period, and either way wait
2125  * for a subsequent grace period to complete.
2126  */
2127 static void rcu_nocb_wait_gp(struct rcu_data *rdp)
2128 {
2129         unsigned long c;
2130         bool d;
2131         unsigned long flags;
2132         bool needwake;
2133         struct rcu_node *rnp = rdp->mynode;
2134
2135         local_irq_save(flags);
2136         c = rcu_seq_snap(&rcu_state.gp_seq);
2137         if (!rdp->gpwrap && ULONG_CMP_GE(rdp->gp_seq_needed, c)) {
2138                 local_irq_restore(flags);
2139         } else {
2140                 raw_spin_lock_rcu_node(rnp); /* irqs already disabled. */
2141                 needwake = rcu_start_this_gp(rnp, rdp, c);
2142                 raw_spin_unlock_irqrestore_rcu_node(rnp, flags);
2143                 if (needwake)
2144                         rcu_gp_kthread_wake();
2145         }
2146
2147         /*
2148          * Wait for the grace period.  Do so interruptibly to avoid messing
2149          * up the load average.
2150          */
2151         trace_rcu_this_gp(rnp, rdp, c, TPS("StartWait"));
2152         for (;;) {
2153                 swait_event_interruptible_exclusive(
2154                         rnp->nocb_gp_wq[rcu_seq_ctr(c) & 0x1],
2155                         (d = rcu_seq_done(&rnp->gp_seq, c)));
2156                 if (likely(d))
2157                         break;
2158                 WARN_ON(signal_pending(current));
2159                 trace_rcu_this_gp(rnp, rdp, c, TPS("ResumeWait"));
2160         }
2161         trace_rcu_this_gp(rnp, rdp, c, TPS("EndWait"));
2162         smp_mb(); /* Ensure that CB invocation happens after GP end. */
2163 }
2164
2165 /*
2166  * Leaders come here to wait for additional callbacks to show up.
2167  * This function does not return until callbacks appear.
2168  */
2169 static void nocb_leader_wait(struct rcu_data *my_rdp)
2170 {
2171         bool firsttime = true;
2172         unsigned long flags;
2173         bool gotcbs;
2174         struct rcu_data *rdp;
2175         struct rcu_head **tail;
2176
2177 wait_again:
2178
2179         /* Wait for callbacks to appear. */
2180         if (!rcu_nocb_poll) {
2181                 trace_rcu_nocb_wake(rcu_state.name, my_rdp->cpu, TPS("Sleep"));
2182                 swait_event_interruptible_exclusive(my_rdp->nocb_wq,
2183                                 !READ_ONCE(my_rdp->nocb_leader_sleep));
2184                 raw_spin_lock_irqsave(&my_rdp->nocb_lock, flags);
2185                 my_rdp->nocb_leader_sleep = true;
2186                 WRITE_ONCE(my_rdp->nocb_defer_wakeup, RCU_NOCB_WAKE_NOT);
2187                 del_timer(&my_rdp->nocb_timer);
2188                 raw_spin_unlock_irqrestore(&my_rdp->nocb_lock, flags);
2189         } else if (firsttime) {
2190                 firsttime = false; /* Don't drown trace log with "Poll"! */
2191                 trace_rcu_nocb_wake(rcu_state.name, my_rdp->cpu, TPS("Poll"));
2192         }
2193
2194         /*
2195          * Each pass through the following loop checks a follower for CBs.
2196          * We are our own first follower.  Any CBs found are moved to
2197          * nocb_gp_head, where they await a grace period.
2198          */
2199         gotcbs = false;
2200         smp_mb(); /* wakeup and _sleep before ->nocb_head reads. */
2201         for (rdp = my_rdp; rdp; rdp = rdp->nocb_next_follower) {
2202                 rdp->nocb_gp_head = READ_ONCE(rdp->nocb_head);
2203                 if (!rdp->nocb_gp_head)
2204                         continue;  /* No CBs here, try next follower. */
2205
2206                 /* Move callbacks to wait-for-GP list, which is empty. */
2207                 WRITE_ONCE(rdp->nocb_head, NULL);
2208                 rdp->nocb_gp_tail = xchg(&rdp->nocb_tail, &rdp->nocb_head);
2209                 gotcbs = true;
2210         }
2211
2212         /* No callbacks?  Sleep a bit if polling, and go retry.  */
2213         if (unlikely(!gotcbs)) {
2214                 WARN_ON(signal_pending(current));
2215                 if (rcu_nocb_poll) {
2216                         schedule_timeout_interruptible(1);
2217                 } else {
2218                         trace_rcu_nocb_wake(rcu_state.name, my_rdp->cpu,
2219                                             TPS("WokeEmpty"));
2220                 }
2221                 goto wait_again;
2222         }
2223
2224         /* Wait for one grace period. */
2225         rcu_nocb_wait_gp(my_rdp);
2226
2227         /* Each pass through the following loop wakes a follower, if needed. */
2228         for (rdp = my_rdp; rdp; rdp = rdp->nocb_next_follower) {
2229                 if (!rcu_nocb_poll &&
2230                     READ_ONCE(rdp->nocb_head) &&
2231                     READ_ONCE(my_rdp->nocb_leader_sleep)) {
2232                         raw_spin_lock_irqsave(&my_rdp->nocb_lock, flags);
2233                         my_rdp->nocb_leader_sleep = false;/* No need to sleep.*/
2234                         raw_spin_unlock_irqrestore(&my_rdp->nocb_lock, flags);
2235                 }
2236                 if (!rdp->nocb_gp_head)
2237                         continue; /* No CBs, so no need to wake follower. */
2238
2239                 /* Append callbacks to follower's "done" list. */
2240                 raw_spin_lock_irqsave(&rdp->nocb_lock, flags);
2241                 tail = rdp->nocb_follower_tail;
2242                 rdp->nocb_follower_tail = rdp->nocb_gp_tail;
2243                 *tail = rdp->nocb_gp_head;
2244                 raw_spin_unlock_irqrestore(&rdp->nocb_lock, flags);
2245                 if (rdp != my_rdp && tail == &rdp->nocb_follower_head) {
2246                         /* List was empty, so wake up the follower.  */
2247                         swake_up_one(&rdp->nocb_wq);
2248                 }
2249         }
2250
2251         /* If we (the leader) don't have CBs, go wait some more. */
2252         if (!my_rdp->nocb_follower_head)
2253                 goto wait_again;
2254 }
2255
2256 /*
2257  * Followers come here to wait for additional callbacks to show up.
2258  * This function does not return until callbacks appear.
2259  */
2260 static void nocb_follower_wait(struct rcu_data *rdp)
2261 {
2262         for (;;) {
2263                 trace_rcu_nocb_wake(rcu_state.name, rdp->cpu, TPS("FollowerSleep"));
2264                 swait_event_interruptible_exclusive(rdp->nocb_wq,
2265                                          READ_ONCE(rdp->nocb_follower_head));
2266                 if (smp_load_acquire(&rdp->nocb_follower_head)) {
2267                         /* ^^^ Ensure CB invocation follows _head test. */
2268                         return;
2269                 }
2270                 WARN_ON(signal_pending(current));
2271                 trace_rcu_nocb_wake(rcu_state.name, rdp->cpu, TPS("WokeEmpty"));
2272         }
2273 }
2274
2275 /*
2276  * Per-rcu_data kthread, but only for no-CBs CPUs.  Each kthread invokes
2277  * callbacks queued by the corresponding no-CBs CPU, however, there is
2278  * an optional leader-follower relationship so that the grace-period
2279  * kthreads don't have to do quite so many wakeups.
2280  */
2281 static int rcu_nocb_kthread(void *arg)
2282 {
2283         int c, cl;
2284         unsigned long flags;
2285         struct rcu_head *list;
2286         struct rcu_head *next;
2287         struct rcu_head **tail;
2288         struct rcu_data *rdp = arg;
2289
2290         /* Each pass through this loop invokes one batch of callbacks */
2291         for (;;) {
2292                 /* Wait for callbacks. */
2293                 if (rdp->nocb_leader == rdp)
2294                         nocb_leader_wait(rdp);
2295                 else
2296                         nocb_follower_wait(rdp);
2297
2298                 /* Pull the ready-to-invoke callbacks onto local list. */
2299                 raw_spin_lock_irqsave(&rdp->nocb_lock, flags);
2300                 list = rdp->nocb_follower_head;
2301                 rdp->nocb_follower_head = NULL;
2302                 tail = rdp->nocb_follower_tail;
2303                 rdp->nocb_follower_tail = &rdp->nocb_follower_head;
2304                 raw_spin_unlock_irqrestore(&rdp->nocb_lock, flags);
2305                 BUG_ON(!list);
2306                 trace_rcu_nocb_wake(rcu_state.name, rdp->cpu, TPS("WokeNonEmpty"));
2307
2308                 /* Each pass through the following loop invokes a callback. */
2309                 trace_rcu_batch_start(rcu_state.name,
2310                                       atomic_long_read(&rdp->nocb_q_count_lazy),
2311                                       atomic_long_read(&rdp->nocb_q_count), -1);
2312                 c = cl = 0;
2313                 while (list) {
2314                         next = list->next;
2315                         /* Wait for enqueuing to complete, if needed. */
2316                         while (next == NULL && &list->next != tail) {
2317                                 trace_rcu_nocb_wake(rcu_state.name, rdp->cpu,
2318                                                     TPS("WaitQueue"));
2319                                 schedule_timeout_interruptible(1);
2320                                 trace_rcu_nocb_wake(rcu_state.name, rdp->cpu,
2321                                                     TPS("WokeQueue"));
2322                                 next = list->next;
2323                         }
2324                         debug_rcu_head_unqueue(list);
2325                         local_bh_disable();
2326                         if (__rcu_reclaim(rcu_state.name, list))
2327                                 cl++;
2328                         c++;
2329                         local_bh_enable();
2330                         cond_resched_tasks_rcu_qs();
2331                         list = next;
2332                 }
2333                 trace_rcu_batch_end(rcu_state.name, c, !!list, 0, 0, 1);
2334                 smp_mb__before_atomic();  /* _add after CB invocation. */
2335                 atomic_long_add(-c, &rdp->nocb_q_count);
2336                 atomic_long_add(-cl, &rdp->nocb_q_count_lazy);
2337         }
2338         return 0;
2339 }
2340
2341 /* Is a deferred wakeup of rcu_nocb_kthread() required? */
2342 static int rcu_nocb_need_deferred_wakeup(struct rcu_data *rdp)
2343 {
2344         return READ_ONCE(rdp->nocb_defer_wakeup);
2345 }
2346
2347 /* Do a deferred wakeup of rcu_nocb_kthread(). */
2348 static void do_nocb_deferred_wakeup_common(struct rcu_data *rdp)
2349 {
2350         unsigned long flags;
2351         int ndw;
2352
2353         raw_spin_lock_irqsave(&rdp->nocb_lock, flags);
2354         if (!rcu_nocb_need_deferred_wakeup(rdp)) {
2355                 raw_spin_unlock_irqrestore(&rdp->nocb_lock, flags);
2356                 return;
2357         }
2358         ndw = READ_ONCE(rdp->nocb_defer_wakeup);
2359         WRITE_ONCE(rdp->nocb_defer_wakeup, RCU_NOCB_WAKE_NOT);
2360         __wake_nocb_leader(rdp, ndw == RCU_NOCB_WAKE_FORCE, flags);
2361         trace_rcu_nocb_wake(rcu_state.name, rdp->cpu, TPS("DeferredWake"));
2362 }
2363
2364 /* Do a deferred wakeup of rcu_nocb_kthread() from a timer handler. */
2365 static void do_nocb_deferred_wakeup_timer(struct timer_list *t)
2366 {
2367         struct rcu_data *rdp = from_timer(rdp, t, nocb_timer);
2368
2369         do_nocb_deferred_wakeup_common(rdp);
2370 }
2371
2372 /*
2373  * Do a deferred wakeup of rcu_nocb_kthread() from fastpath.
2374  * This means we do an inexact common-case check.  Note that if
2375  * we miss, ->nocb_timer will eventually clean things up.
2376  */
2377 static void do_nocb_deferred_wakeup(struct rcu_data *rdp)
2378 {
2379         if (rcu_nocb_need_deferred_wakeup(rdp))
2380                 do_nocb_deferred_wakeup_common(rdp);
2381 }
2382
2383 void __init rcu_init_nohz(void)
2384 {
2385         int cpu;
2386         bool need_rcu_nocb_mask = false;
2387         struct rcu_state *rsp;
2388
2389 #if defined(CONFIG_NO_HZ_FULL)
2390         if (tick_nohz_full_running && cpumask_weight(tick_nohz_full_mask))
2391                 need_rcu_nocb_mask = true;
2392 #endif /* #if defined(CONFIG_NO_HZ_FULL) */
2393
2394         if (!cpumask_available(rcu_nocb_mask) && need_rcu_nocb_mask) {
2395                 if (!zalloc_cpumask_var(&rcu_nocb_mask, GFP_KERNEL)) {
2396                         pr_info("rcu_nocb_mask allocation failed, callback offloading disabled.\n");
2397                         return;
2398                 }
2399         }
2400         if (!cpumask_available(rcu_nocb_mask))
2401                 return;
2402
2403 #if defined(CONFIG_NO_HZ_FULL)
2404         if (tick_nohz_full_running)
2405                 cpumask_or(rcu_nocb_mask, rcu_nocb_mask, tick_nohz_full_mask);
2406 #endif /* #if defined(CONFIG_NO_HZ_FULL) */
2407
2408         if (!cpumask_subset(rcu_nocb_mask, cpu_possible_mask)) {
2409                 pr_info("\tNote: kernel parameter 'rcu_nocbs=', 'nohz_full', or 'isolcpus=' contains nonexistent CPUs.\n");
2410                 cpumask_and(rcu_nocb_mask, cpu_possible_mask,
2411                             rcu_nocb_mask);
2412         }
2413         if (cpumask_empty(rcu_nocb_mask))
2414                 pr_info("\tOffload RCU callbacks from CPUs: (none).\n");
2415         else
2416                 pr_info("\tOffload RCU callbacks from CPUs: %*pbl.\n",
2417                         cpumask_pr_args(rcu_nocb_mask));
2418         if (rcu_nocb_poll)
2419                 pr_info("\tPoll for callbacks from no-CBs CPUs.\n");
2420
2421         for_each_rcu_flavor(rsp) {
2422                 for_each_cpu(cpu, rcu_nocb_mask)
2423                         init_nocb_callback_list(per_cpu_ptr(&rcu_data, cpu));
2424                 rcu_organize_nocb_kthreads();
2425         }
2426 }
2427
2428 /* Initialize per-rcu_data variables for no-CBs CPUs. */
2429 static void __init rcu_boot_init_nocb_percpu_data(struct rcu_data *rdp)
2430 {
2431         rdp->nocb_tail = &rdp->nocb_head;
2432         init_swait_queue_head(&rdp->nocb_wq);
2433         rdp->nocb_follower_tail = &rdp->nocb_follower_head;
2434         raw_spin_lock_init(&rdp->nocb_lock);
2435         timer_setup(&rdp->nocb_timer, do_nocb_deferred_wakeup_timer, 0);
2436 }
2437
2438 /*
2439  * If the specified CPU is a no-CBs CPU that does not already have its
2440  * rcuo kthread for the specified RCU flavor, spawn it.  If the CPUs are
2441  * brought online out of order, this can require re-organizing the
2442  * leader-follower relationships.
2443  */
2444 static void rcu_spawn_one_nocb_kthread(int cpu)
2445 {
2446         struct rcu_data *rdp;
2447         struct rcu_data *rdp_last;
2448         struct rcu_data *rdp_old_leader;
2449         struct rcu_data *rdp_spawn = per_cpu_ptr(&rcu_data, cpu);
2450         struct task_struct *t;
2451
2452         /*
2453          * If this isn't a no-CBs CPU or if it already has an rcuo kthread,
2454          * then nothing to do.
2455          */
2456         if (!rcu_is_nocb_cpu(cpu) || rdp_spawn->nocb_kthread)
2457                 return;
2458
2459         /* If we didn't spawn the leader first, reorganize! */
2460         rdp_old_leader = rdp_spawn->nocb_leader;
2461         if (rdp_old_leader != rdp_spawn && !rdp_old_leader->nocb_kthread) {
2462                 rdp_last = NULL;
2463                 rdp = rdp_old_leader;
2464                 do {
2465                         rdp->nocb_leader = rdp_spawn;
2466                         if (rdp_last && rdp != rdp_spawn)
2467                                 rdp_last->nocb_next_follower = rdp;
2468                         if (rdp == rdp_spawn) {
2469                                 rdp = rdp->nocb_next_follower;
2470                         } else {
2471                                 rdp_last = rdp;
2472                                 rdp = rdp->nocb_next_follower;
2473                                 rdp_last->nocb_next_follower = NULL;
2474                         }
2475                 } while (rdp);
2476                 rdp_spawn->nocb_next_follower = rdp_old_leader;
2477         }
2478
2479         /* Spawn the kthread for this CPU and RCU flavor. */
2480         t = kthread_run(rcu_nocb_kthread, rdp_spawn,
2481                         "rcuo%c/%d", rcu_state.abbr, cpu);
2482         BUG_ON(IS_ERR(t));
2483         WRITE_ONCE(rdp_spawn->nocb_kthread, t);
2484 }
2485
2486 /*
2487  * If the specified CPU is a no-CBs CPU that does not already have its
2488  * rcuo kthreads, spawn them.
2489  */
2490 static void rcu_spawn_all_nocb_kthreads(int cpu)
2491 {
2492         struct rcu_state *rsp;
2493
2494         if (rcu_scheduler_fully_active)
2495                 for_each_rcu_flavor(rsp)
2496                         rcu_spawn_one_nocb_kthread(cpu);
2497 }
2498
2499 /*
2500  * Once the scheduler is running, spawn rcuo kthreads for all online
2501  * no-CBs CPUs.  This assumes that the early_initcall()s happen before
2502  * non-boot CPUs come online -- if this changes, we will need to add
2503  * some mutual exclusion.
2504  */
2505 static void __init rcu_spawn_nocb_kthreads(void)
2506 {
2507         int cpu;
2508
2509         for_each_online_cpu(cpu)
2510                 rcu_spawn_all_nocb_kthreads(cpu);
2511 }
2512
2513 /* How many follower CPU IDs per leader?  Default of -1 for sqrt(nr_cpu_ids). */
2514 static int rcu_nocb_leader_stride = -1;
2515 module_param(rcu_nocb_leader_stride, int, 0444);
2516
2517 /*
2518  * Initialize leader-follower relationships for all no-CBs CPU.
2519  */
2520 static void __init rcu_organize_nocb_kthreads(void)
2521 {
2522         int cpu;
2523         int ls = rcu_nocb_leader_stride;
2524         int nl = 0;  /* Next leader. */
2525         struct rcu_data *rdp;
2526         struct rcu_data *rdp_leader = NULL;  /* Suppress misguided gcc warn. */
2527         struct rcu_data *rdp_prev = NULL;
2528
2529         if (!cpumask_available(rcu_nocb_mask))
2530                 return;
2531         if (ls == -1) {
2532                 ls = int_sqrt(nr_cpu_ids);
2533                 rcu_nocb_leader_stride = ls;
2534         }
2535
2536         /*
2537          * Each pass through this loop sets up one rcu_data structure.
2538          * Should the corresponding CPU come online in the future, then
2539          * we will spawn the needed set of rcu_nocb_kthread() kthreads.
2540          */
2541         for_each_cpu(cpu, rcu_nocb_mask) {
2542                 rdp = per_cpu_ptr(&rcu_data, cpu);
2543                 if (rdp->cpu >= nl) {
2544                         /* New leader, set up for followers & next leader. */
2545                         nl = DIV_ROUND_UP(rdp->cpu + 1, ls) * ls;
2546                         rdp->nocb_leader = rdp;
2547                         rdp_leader = rdp;
2548                 } else {
2549                         /* Another follower, link to previous leader. */
2550                         rdp->nocb_leader = rdp_leader;
2551                         rdp_prev->nocb_next_follower = rdp;
2552                 }
2553                 rdp_prev = rdp;
2554         }
2555 }
2556
2557 /* Prevent __call_rcu() from enqueuing callbacks on no-CBs CPUs */
2558 static bool init_nocb_callback_list(struct rcu_data *rdp)
2559 {
2560         if (!rcu_is_nocb_cpu(rdp->cpu))
2561                 return false;
2562
2563         /* If there are early-boot callbacks, move them to nocb lists. */
2564         if (!rcu_segcblist_empty(&rdp->cblist)) {
2565                 rdp->nocb_head = rcu_segcblist_head(&rdp->cblist);
2566                 rdp->nocb_tail = rcu_segcblist_tail(&rdp->cblist);
2567                 atomic_long_set(&rdp->nocb_q_count,
2568                                 rcu_segcblist_n_cbs(&rdp->cblist));
2569                 atomic_long_set(&rdp->nocb_q_count_lazy,
2570                                 rcu_segcblist_n_lazy_cbs(&rdp->cblist));
2571                 rcu_segcblist_init(&rdp->cblist);
2572         }
2573         rcu_segcblist_disable(&rdp->cblist);
2574         return true;
2575 }
2576
2577 #else /* #ifdef CONFIG_RCU_NOCB_CPU */
2578
2579 static bool rcu_nocb_cpu_needs_barrier(int cpu)
2580 {
2581         WARN_ON_ONCE(1); /* Should be dead code. */
2582         return false;
2583 }
2584
2585 static void rcu_nocb_gp_cleanup(struct swait_queue_head *sq)
2586 {
2587 }
2588
2589 static struct swait_queue_head *rcu_nocb_gp_get(struct rcu_node *rnp)
2590 {
2591         return NULL;
2592 }
2593
2594 static void rcu_init_one_nocb(struct rcu_node *rnp)
2595 {
2596 }
2597
2598 static bool __call_rcu_nocb(struct rcu_data *rdp, struct rcu_head *rhp,
2599                             bool lazy, unsigned long flags)
2600 {
2601         return false;
2602 }
2603
2604 static bool __maybe_unused rcu_nocb_adopt_orphan_cbs(struct rcu_data *my_rdp,
2605                                                      struct rcu_data *rdp,
2606                                                      unsigned long flags)
2607 {
2608         return false;
2609 }
2610
2611 static void __init rcu_boot_init_nocb_percpu_data(struct rcu_data *rdp)
2612 {
2613 }
2614
2615 static int rcu_nocb_need_deferred_wakeup(struct rcu_data *rdp)
2616 {
2617         return false;
2618 }
2619
2620 static void do_nocb_deferred_wakeup(struct rcu_data *rdp)
2621 {
2622 }
2623
2624 static void rcu_spawn_all_nocb_kthreads(int cpu)
2625 {
2626 }
2627
2628 static void __init rcu_spawn_nocb_kthreads(void)
2629 {
2630 }
2631
2632 static bool init_nocb_callback_list(struct rcu_data *rdp)
2633 {
2634         return false;
2635 }
2636
2637 #endif /* #else #ifdef CONFIG_RCU_NOCB_CPU */
2638
2639 /*
2640  * Is this CPU a NO_HZ_FULL CPU that should ignore RCU so that the
2641  * grace-period kthread will do force_quiescent_state() processing?
2642  * The idea is to avoid waking up RCU core processing on such a
2643  * CPU unless the grace period has extended for too long.
2644  *
2645  * This code relies on the fact that all NO_HZ_FULL CPUs are also
2646  * CONFIG_RCU_NOCB_CPU CPUs.
2647  */
2648 static bool rcu_nohz_full_cpu(void)
2649 {
2650 #ifdef CONFIG_NO_HZ_FULL
2651         if (tick_nohz_full_cpu(smp_processor_id()) &&
2652             (!rcu_gp_in_progress() ||
2653              ULONG_CMP_LT(jiffies, READ_ONCE(rcu_state.gp_start) + HZ)))
2654                 return true;
2655 #endif /* #ifdef CONFIG_NO_HZ_FULL */
2656         return false;
2657 }
2658
2659 /*
2660  * Bind the RCU grace-period kthreads to the housekeeping CPU.
2661  */
2662 static void rcu_bind_gp_kthread(void)
2663 {
2664         if (!tick_nohz_full_enabled())
2665                 return;
2666         housekeeping_affine(current, HK_FLAG_RCU);
2667 }
2668
2669 /* Record the current task on dyntick-idle entry. */
2670 static void rcu_dynticks_task_enter(void)
2671 {
2672 #if defined(CONFIG_TASKS_RCU) && defined(CONFIG_NO_HZ_FULL)
2673         WRITE_ONCE(current->rcu_tasks_idle_cpu, smp_processor_id());
2674 #endif /* #if defined(CONFIG_TASKS_RCU) && defined(CONFIG_NO_HZ_FULL) */
2675 }
2676
2677 /* Record no current task on dyntick-idle exit. */
2678 static void rcu_dynticks_task_exit(void)
2679 {
2680 #if defined(CONFIG_TASKS_RCU) && defined(CONFIG_NO_HZ_FULL)
2681         WRITE_ONCE(current->rcu_tasks_idle_cpu, -1);
2682 #endif /* #if defined(CONFIG_TASKS_RCU) && defined(CONFIG_NO_HZ_FULL) */
2683 }