rcu-tasks: Stop rcu_tasks_invoke_cbs() from using never-onlined CPUs
[platform/kernel/linux-starfive.git] / kernel / rcu / tasks.h
1 /* SPDX-License-Identifier: GPL-2.0+ */
2 /*
3  * Task-based RCU implementations.
4  *
5  * Copyright (C) 2020 Paul E. McKenney
6  */
7
8 #ifdef CONFIG_TASKS_RCU_GENERIC
9 #include "rcu_segcblist.h"
10
11 ////////////////////////////////////////////////////////////////////////
12 //
13 // Generic data structures.
14
15 struct rcu_tasks;
16 typedef void (*rcu_tasks_gp_func_t)(struct rcu_tasks *rtp);
17 typedef void (*pregp_func_t)(struct list_head *hop);
18 typedef void (*pertask_func_t)(struct task_struct *t, struct list_head *hop);
19 typedef void (*postscan_func_t)(struct list_head *hop);
20 typedef void (*holdouts_func_t)(struct list_head *hop, bool ndrpt, bool *frptp);
21 typedef void (*postgp_func_t)(struct rcu_tasks *rtp);
22
23 /**
24  * struct rcu_tasks_percpu - Per-CPU component of definition for a Tasks-RCU-like mechanism.
25  * @cblist: Callback list.
26  * @lock: Lock protecting per-CPU callback list.
27  * @rtp_jiffies: Jiffies counter value for statistics.
28  * @rtp_n_lock_retries: Rough lock-contention statistic.
29  * @rtp_work: Work queue for invoking callbacks.
30  * @rtp_irq_work: IRQ work queue for deferred wakeups.
31  * @barrier_q_head: RCU callback for barrier operation.
32  * @rtp_blkd_tasks: List of tasks blocked as readers.
33  * @cpu: CPU number corresponding to this entry.
34  * @rtpp: Pointer to the rcu_tasks structure.
35  */
36 struct rcu_tasks_percpu {
37         struct rcu_segcblist cblist;
38         raw_spinlock_t __private lock;
39         unsigned long rtp_jiffies;
40         unsigned long rtp_n_lock_retries;
41         struct work_struct rtp_work;
42         struct irq_work rtp_irq_work;
43         struct rcu_head barrier_q_head;
44         struct list_head rtp_blkd_tasks;
45         int cpu;
46         struct rcu_tasks *rtpp;
47 };
48
49 /**
50  * struct rcu_tasks - Definition for a Tasks-RCU-like mechanism.
51  * @cbs_wait: RCU wait allowing a new callback to get kthread's attention.
52  * @cbs_gbl_lock: Lock protecting callback list.
53  * @tasks_gp_mutex: Mutex protecting grace period, needed during mid-boot dead zone.
54  * @kthread_ptr: This flavor's grace-period/callback-invocation kthread.
55  * @gp_func: This flavor's grace-period-wait function.
56  * @gp_state: Grace period's most recent state transition (debugging).
57  * @gp_sleep: Per-grace-period sleep to prevent CPU-bound looping.
58  * @init_fract: Initial backoff sleep interval.
59  * @gp_jiffies: Time of last @gp_state transition.
60  * @gp_start: Most recent grace-period start in jiffies.
61  * @tasks_gp_seq: Number of grace periods completed since boot.
62  * @n_ipis: Number of IPIs sent to encourage grace periods to end.
63  * @n_ipis_fails: Number of IPI-send failures.
64  * @pregp_func: This flavor's pre-grace-period function (optional).
65  * @pertask_func: This flavor's per-task scan function (optional).
66  * @postscan_func: This flavor's post-task scan function (optional).
67  * @holdouts_func: This flavor's holdout-list scan function (optional).
68  * @postgp_func: This flavor's post-grace-period function (optional).
69  * @call_func: This flavor's call_rcu()-equivalent function.
70  * @rtpcpu: This flavor's rcu_tasks_percpu structure.
71  * @percpu_enqueue_shift: Shift down CPU ID this much when enqueuing callbacks.
72  * @percpu_enqueue_lim: Number of per-CPU callback queues in use for enqueuing.
73  * @percpu_dequeue_lim: Number of per-CPU callback queues in use for dequeuing.
74  * @percpu_dequeue_gpseq: RCU grace-period number to propagate enqueue limit to dequeuers.
75  * @barrier_q_mutex: Serialize barrier operations.
76  * @barrier_q_count: Number of queues being waited on.
77  * @barrier_q_completion: Barrier wait/wakeup mechanism.
78  * @barrier_q_seq: Sequence number for barrier operations.
79  * @name: This flavor's textual name.
80  * @kname: This flavor's kthread name.
81  */
82 struct rcu_tasks {
83         struct rcuwait cbs_wait;
84         raw_spinlock_t cbs_gbl_lock;
85         struct mutex tasks_gp_mutex;
86         int gp_state;
87         int gp_sleep;
88         int init_fract;
89         unsigned long gp_jiffies;
90         unsigned long gp_start;
91         unsigned long tasks_gp_seq;
92         unsigned long n_ipis;
93         unsigned long n_ipis_fails;
94         struct task_struct *kthread_ptr;
95         rcu_tasks_gp_func_t gp_func;
96         pregp_func_t pregp_func;
97         pertask_func_t pertask_func;
98         postscan_func_t postscan_func;
99         holdouts_func_t holdouts_func;
100         postgp_func_t postgp_func;
101         call_rcu_func_t call_func;
102         struct rcu_tasks_percpu __percpu *rtpcpu;
103         int percpu_enqueue_shift;
104         int percpu_enqueue_lim;
105         int percpu_dequeue_lim;
106         unsigned long percpu_dequeue_gpseq;
107         struct mutex barrier_q_mutex;
108         atomic_t barrier_q_count;
109         struct completion barrier_q_completion;
110         unsigned long barrier_q_seq;
111         char *name;
112         char *kname;
113 };
114
115 static void call_rcu_tasks_iw_wakeup(struct irq_work *iwp);
116
117 #define DEFINE_RCU_TASKS(rt_name, gp, call, n)                                          \
118 static DEFINE_PER_CPU(struct rcu_tasks_percpu, rt_name ## __percpu) = {                 \
119         .lock = __RAW_SPIN_LOCK_UNLOCKED(rt_name ## __percpu.cbs_pcpu_lock),            \
120         .rtp_irq_work = IRQ_WORK_INIT_HARD(call_rcu_tasks_iw_wakeup),                   \
121 };                                                                                      \
122 static struct rcu_tasks rt_name =                                                       \
123 {                                                                                       \
124         .cbs_wait = __RCUWAIT_INITIALIZER(rt_name.wait),                                \
125         .cbs_gbl_lock = __RAW_SPIN_LOCK_UNLOCKED(rt_name.cbs_gbl_lock),                 \
126         .tasks_gp_mutex = __MUTEX_INITIALIZER(rt_name.tasks_gp_mutex),                  \
127         .gp_func = gp,                                                                  \
128         .call_func = call,                                                              \
129         .rtpcpu = &rt_name ## __percpu,                                                 \
130         .name = n,                                                                      \
131         .percpu_enqueue_shift = order_base_2(CONFIG_NR_CPUS),                           \
132         .percpu_enqueue_lim = 1,                                                        \
133         .percpu_dequeue_lim = 1,                                                        \
134         .barrier_q_mutex = __MUTEX_INITIALIZER(rt_name.barrier_q_mutex),                \
135         .barrier_q_seq = (0UL - 50UL) << RCU_SEQ_CTR_SHIFT,                             \
136         .kname = #rt_name,                                                              \
137 }
138
139 /* Track exiting tasks in order to allow them to be waited for. */
140 DEFINE_STATIC_SRCU(tasks_rcu_exit_srcu);
141
142 /* Avoid IPIing CPUs early in the grace period. */
143 #define RCU_TASK_IPI_DELAY (IS_ENABLED(CONFIG_TASKS_TRACE_RCU_READ_MB) ? HZ / 2 : 0)
144 static int rcu_task_ipi_delay __read_mostly = RCU_TASK_IPI_DELAY;
145 module_param(rcu_task_ipi_delay, int, 0644);
146
147 /* Control stall timeouts.  Disable with <= 0, otherwise jiffies till stall. */
148 #define RCU_TASK_BOOT_STALL_TIMEOUT (HZ * 30)
149 #define RCU_TASK_STALL_TIMEOUT (HZ * 60 * 10)
150 static int rcu_task_stall_timeout __read_mostly = RCU_TASK_STALL_TIMEOUT;
151 module_param(rcu_task_stall_timeout, int, 0644);
152 #define RCU_TASK_STALL_INFO (HZ * 10)
153 static int rcu_task_stall_info __read_mostly = RCU_TASK_STALL_INFO;
154 module_param(rcu_task_stall_info, int, 0644);
155 static int rcu_task_stall_info_mult __read_mostly = 3;
156 module_param(rcu_task_stall_info_mult, int, 0444);
157
158 static int rcu_task_enqueue_lim __read_mostly = -1;
159 module_param(rcu_task_enqueue_lim, int, 0444);
160
161 static bool rcu_task_cb_adjust;
162 static int rcu_task_contend_lim __read_mostly = 100;
163 module_param(rcu_task_contend_lim, int, 0444);
164 static int rcu_task_collapse_lim __read_mostly = 10;
165 module_param(rcu_task_collapse_lim, int, 0444);
166
167 /* RCU tasks grace-period state for debugging. */
168 #define RTGS_INIT                0
169 #define RTGS_WAIT_WAIT_CBS       1
170 #define RTGS_WAIT_GP             2
171 #define RTGS_PRE_WAIT_GP         3
172 #define RTGS_SCAN_TASKLIST       4
173 #define RTGS_POST_SCAN_TASKLIST  5
174 #define RTGS_WAIT_SCAN_HOLDOUTS  6
175 #define RTGS_SCAN_HOLDOUTS       7
176 #define RTGS_POST_GP             8
177 #define RTGS_WAIT_READERS        9
178 #define RTGS_INVOKE_CBS         10
179 #define RTGS_WAIT_CBS           11
180 #ifndef CONFIG_TINY_RCU
181 static const char * const rcu_tasks_gp_state_names[] = {
182         "RTGS_INIT",
183         "RTGS_WAIT_WAIT_CBS",
184         "RTGS_WAIT_GP",
185         "RTGS_PRE_WAIT_GP",
186         "RTGS_SCAN_TASKLIST",
187         "RTGS_POST_SCAN_TASKLIST",
188         "RTGS_WAIT_SCAN_HOLDOUTS",
189         "RTGS_SCAN_HOLDOUTS",
190         "RTGS_POST_GP",
191         "RTGS_WAIT_READERS",
192         "RTGS_INVOKE_CBS",
193         "RTGS_WAIT_CBS",
194 };
195 #endif /* #ifndef CONFIG_TINY_RCU */
196
197 ////////////////////////////////////////////////////////////////////////
198 //
199 // Generic code.
200
201 static void rcu_tasks_invoke_cbs_wq(struct work_struct *wp);
202
203 /* Record grace-period phase and time. */
204 static void set_tasks_gp_state(struct rcu_tasks *rtp, int newstate)
205 {
206         rtp->gp_state = newstate;
207         rtp->gp_jiffies = jiffies;
208 }
209
210 #ifndef CONFIG_TINY_RCU
211 /* Return state name. */
212 static const char *tasks_gp_state_getname(struct rcu_tasks *rtp)
213 {
214         int i = data_race(rtp->gp_state); // Let KCSAN detect update races
215         int j = READ_ONCE(i); // Prevent the compiler from reading twice
216
217         if (j >= ARRAY_SIZE(rcu_tasks_gp_state_names))
218                 return "???";
219         return rcu_tasks_gp_state_names[j];
220 }
221 #endif /* #ifndef CONFIG_TINY_RCU */
222
223 // Initialize per-CPU callback lists for the specified flavor of
224 // Tasks RCU.
225 static void cblist_init_generic(struct rcu_tasks *rtp)
226 {
227         int cpu;
228         unsigned long flags;
229         int lim;
230         int shift;
231
232         raw_spin_lock_irqsave(&rtp->cbs_gbl_lock, flags);
233         if (rcu_task_enqueue_lim < 0) {
234                 rcu_task_enqueue_lim = 1;
235                 rcu_task_cb_adjust = true;
236                 pr_info("%s: Setting adjustable number of callback queues.\n", __func__);
237         } else if (rcu_task_enqueue_lim == 0) {
238                 rcu_task_enqueue_lim = 1;
239         }
240         lim = rcu_task_enqueue_lim;
241
242         if (lim > nr_cpu_ids)
243                 lim = nr_cpu_ids;
244         shift = ilog2(nr_cpu_ids / lim);
245         if (((nr_cpu_ids - 1) >> shift) >= lim)
246                 shift++;
247         WRITE_ONCE(rtp->percpu_enqueue_shift, shift);
248         WRITE_ONCE(rtp->percpu_dequeue_lim, lim);
249         smp_store_release(&rtp->percpu_enqueue_lim, lim);
250         for_each_possible_cpu(cpu) {
251                 struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
252
253                 WARN_ON_ONCE(!rtpcp);
254                 if (cpu)
255                         raw_spin_lock_init(&ACCESS_PRIVATE(rtpcp, lock));
256                 raw_spin_lock_rcu_node(rtpcp); // irqs already disabled.
257                 if (rcu_segcblist_empty(&rtpcp->cblist))
258                         rcu_segcblist_init(&rtpcp->cblist);
259                 INIT_WORK(&rtpcp->rtp_work, rcu_tasks_invoke_cbs_wq);
260                 rtpcp->cpu = cpu;
261                 rtpcp->rtpp = rtp;
262                 if (!rtpcp->rtp_blkd_tasks.next)
263                         INIT_LIST_HEAD(&rtpcp->rtp_blkd_tasks);
264                 raw_spin_unlock_rcu_node(rtpcp); // irqs remain disabled.
265         }
266         raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags);
267         pr_info("%s: Setting shift to %d and lim to %d.\n", __func__, data_race(rtp->percpu_enqueue_shift), data_race(rtp->percpu_enqueue_lim));
268 }
269
270 // IRQ-work handler that does deferred wakeup for call_rcu_tasks_generic().
271 static void call_rcu_tasks_iw_wakeup(struct irq_work *iwp)
272 {
273         struct rcu_tasks *rtp;
274         struct rcu_tasks_percpu *rtpcp = container_of(iwp, struct rcu_tasks_percpu, rtp_irq_work);
275
276         rtp = rtpcp->rtpp;
277         rcuwait_wake_up(&rtp->cbs_wait);
278 }
279
280 // Enqueue a callback for the specified flavor of Tasks RCU.
281 static void call_rcu_tasks_generic(struct rcu_head *rhp, rcu_callback_t func,
282                                    struct rcu_tasks *rtp)
283 {
284         int chosen_cpu;
285         unsigned long flags;
286         int ideal_cpu;
287         unsigned long j;
288         bool needadjust = false;
289         bool needwake;
290         struct rcu_tasks_percpu *rtpcp;
291
292         rhp->next = NULL;
293         rhp->func = func;
294         local_irq_save(flags);
295         rcu_read_lock();
296         ideal_cpu = smp_processor_id() >> READ_ONCE(rtp->percpu_enqueue_shift);
297         chosen_cpu = cpumask_next(ideal_cpu - 1, cpu_possible_mask);
298         rtpcp = per_cpu_ptr(rtp->rtpcpu, chosen_cpu);
299         if (!raw_spin_trylock_rcu_node(rtpcp)) { // irqs already disabled.
300                 raw_spin_lock_rcu_node(rtpcp); // irqs already disabled.
301                 j = jiffies;
302                 if (rtpcp->rtp_jiffies != j) {
303                         rtpcp->rtp_jiffies = j;
304                         rtpcp->rtp_n_lock_retries = 0;
305                 }
306                 if (rcu_task_cb_adjust && ++rtpcp->rtp_n_lock_retries > rcu_task_contend_lim &&
307                     READ_ONCE(rtp->percpu_enqueue_lim) != nr_cpu_ids)
308                         needadjust = true;  // Defer adjustment to avoid deadlock.
309         }
310         if (!rcu_segcblist_is_enabled(&rtpcp->cblist)) {
311                 raw_spin_unlock_rcu_node(rtpcp); // irqs remain disabled.
312                 cblist_init_generic(rtp);
313                 raw_spin_lock_rcu_node(rtpcp); // irqs already disabled.
314         }
315         needwake = rcu_segcblist_empty(&rtpcp->cblist);
316         rcu_segcblist_enqueue(&rtpcp->cblist, rhp);
317         raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
318         if (unlikely(needadjust)) {
319                 raw_spin_lock_irqsave(&rtp->cbs_gbl_lock, flags);
320                 if (rtp->percpu_enqueue_lim != nr_cpu_ids) {
321                         WRITE_ONCE(rtp->percpu_enqueue_shift, 0);
322                         WRITE_ONCE(rtp->percpu_dequeue_lim, nr_cpu_ids);
323                         smp_store_release(&rtp->percpu_enqueue_lim, nr_cpu_ids);
324                         pr_info("Switching %s to per-CPU callback queuing.\n", rtp->name);
325                 }
326                 raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags);
327         }
328         rcu_read_unlock();
329         /* We can't create the thread unless interrupts are enabled. */
330         if (needwake && READ_ONCE(rtp->kthread_ptr))
331                 irq_work_queue(&rtpcp->rtp_irq_work);
332 }
333
334 // RCU callback function for rcu_barrier_tasks_generic().
335 static void rcu_barrier_tasks_generic_cb(struct rcu_head *rhp)
336 {
337         struct rcu_tasks *rtp;
338         struct rcu_tasks_percpu *rtpcp;
339
340         rtpcp = container_of(rhp, struct rcu_tasks_percpu, barrier_q_head);
341         rtp = rtpcp->rtpp;
342         if (atomic_dec_and_test(&rtp->barrier_q_count))
343                 complete(&rtp->barrier_q_completion);
344 }
345
346 // Wait for all in-flight callbacks for the specified RCU Tasks flavor.
347 // Operates in a manner similar to rcu_barrier().
348 static void rcu_barrier_tasks_generic(struct rcu_tasks *rtp)
349 {
350         int cpu;
351         unsigned long flags;
352         struct rcu_tasks_percpu *rtpcp;
353         unsigned long s = rcu_seq_snap(&rtp->barrier_q_seq);
354
355         mutex_lock(&rtp->barrier_q_mutex);
356         if (rcu_seq_done(&rtp->barrier_q_seq, s)) {
357                 smp_mb();
358                 mutex_unlock(&rtp->barrier_q_mutex);
359                 return;
360         }
361         rcu_seq_start(&rtp->barrier_q_seq);
362         init_completion(&rtp->barrier_q_completion);
363         atomic_set(&rtp->barrier_q_count, 2);
364         for_each_possible_cpu(cpu) {
365                 if (cpu >= smp_load_acquire(&rtp->percpu_dequeue_lim))
366                         break;
367                 rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
368                 rtpcp->barrier_q_head.func = rcu_barrier_tasks_generic_cb;
369                 raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
370                 if (rcu_segcblist_entrain(&rtpcp->cblist, &rtpcp->barrier_q_head))
371                         atomic_inc(&rtp->barrier_q_count);
372                 raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
373         }
374         if (atomic_sub_and_test(2, &rtp->barrier_q_count))
375                 complete(&rtp->barrier_q_completion);
376         wait_for_completion(&rtp->barrier_q_completion);
377         rcu_seq_end(&rtp->barrier_q_seq);
378         mutex_unlock(&rtp->barrier_q_mutex);
379 }
380
381 // Advance callbacks and indicate whether either a grace period or
382 // callback invocation is needed.
383 static int rcu_tasks_need_gpcb(struct rcu_tasks *rtp)
384 {
385         int cpu;
386         unsigned long flags;
387         bool gpdone = poll_state_synchronize_rcu(rtp->percpu_dequeue_gpseq);
388         long n;
389         long ncbs = 0;
390         long ncbsnz = 0;
391         int needgpcb = 0;
392
393         for (cpu = 0; cpu < smp_load_acquire(&rtp->percpu_dequeue_lim); cpu++) {
394                 struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
395
396                 /* Advance and accelerate any new callbacks. */
397                 if (!rcu_segcblist_n_cbs(&rtpcp->cblist))
398                         continue;
399                 raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
400                 // Should we shrink down to a single callback queue?
401                 n = rcu_segcblist_n_cbs(&rtpcp->cblist);
402                 if (n) {
403                         ncbs += n;
404                         if (cpu > 0)
405                                 ncbsnz += n;
406                 }
407                 rcu_segcblist_advance(&rtpcp->cblist, rcu_seq_current(&rtp->tasks_gp_seq));
408                 (void)rcu_segcblist_accelerate(&rtpcp->cblist, rcu_seq_snap(&rtp->tasks_gp_seq));
409                 if (rcu_segcblist_pend_cbs(&rtpcp->cblist))
410                         needgpcb |= 0x3;
411                 if (!rcu_segcblist_empty(&rtpcp->cblist))
412                         needgpcb |= 0x1;
413                 raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
414         }
415
416         // Shrink down to a single callback queue if appropriate.
417         // This is done in two stages: (1) If there are no more than
418         // rcu_task_collapse_lim callbacks on CPU 0 and none on any other
419         // CPU, limit enqueueing to CPU 0.  (2) After an RCU grace period,
420         // if there has not been an increase in callbacks, limit dequeuing
421         // to CPU 0.  Note the matching RCU read-side critical section in
422         // call_rcu_tasks_generic().
423         if (rcu_task_cb_adjust && ncbs <= rcu_task_collapse_lim) {
424                 raw_spin_lock_irqsave(&rtp->cbs_gbl_lock, flags);
425                 if (rtp->percpu_enqueue_lim > 1) {
426                         WRITE_ONCE(rtp->percpu_enqueue_shift, order_base_2(nr_cpu_ids));
427                         smp_store_release(&rtp->percpu_enqueue_lim, 1);
428                         rtp->percpu_dequeue_gpseq = get_state_synchronize_rcu();
429                         gpdone = false;
430                         pr_info("Starting switch %s to CPU-0 callback queuing.\n", rtp->name);
431                 }
432                 raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags);
433         }
434         if (rcu_task_cb_adjust && !ncbsnz && gpdone) {
435                 raw_spin_lock_irqsave(&rtp->cbs_gbl_lock, flags);
436                 if (rtp->percpu_enqueue_lim < rtp->percpu_dequeue_lim) {
437                         WRITE_ONCE(rtp->percpu_dequeue_lim, 1);
438                         pr_info("Completing switch %s to CPU-0 callback queuing.\n", rtp->name);
439                 }
440                 if (rtp->percpu_dequeue_lim == 1) {
441                         for (cpu = rtp->percpu_dequeue_lim; cpu < nr_cpu_ids; cpu++) {
442                                 struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
443
444                                 WARN_ON_ONCE(rcu_segcblist_n_cbs(&rtpcp->cblist));
445                         }
446                 }
447                 raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags);
448         }
449
450         return needgpcb;
451 }
452
453 // Advance callbacks and invoke any that are ready.
454 static void rcu_tasks_invoke_cbs(struct rcu_tasks *rtp, struct rcu_tasks_percpu *rtpcp)
455 {
456         int cpu;
457         int cpunext;
458         int cpuwq;
459         unsigned long flags;
460         int len;
461         struct rcu_head *rhp;
462         struct rcu_cblist rcl = RCU_CBLIST_INITIALIZER(rcl);
463         struct rcu_tasks_percpu *rtpcp_next;
464
465         cpu = rtpcp->cpu;
466         cpunext = cpu * 2 + 1;
467         if (cpunext < smp_load_acquire(&rtp->percpu_dequeue_lim)) {
468                 rtpcp_next = per_cpu_ptr(rtp->rtpcpu, cpunext);
469                 cpuwq = rcu_cpu_beenfullyonline(cpunext) ? cpunext : WORK_CPU_UNBOUND;
470                 queue_work_on(cpuwq, system_wq, &rtpcp_next->rtp_work);
471                 cpunext++;
472                 if (cpunext < smp_load_acquire(&rtp->percpu_dequeue_lim)) {
473                         rtpcp_next = per_cpu_ptr(rtp->rtpcpu, cpunext);
474                         cpuwq = rcu_cpu_beenfullyonline(cpunext) ? cpunext : WORK_CPU_UNBOUND;
475                         queue_work_on(cpuwq, system_wq, &rtpcp_next->rtp_work);
476                 }
477         }
478
479         if (rcu_segcblist_empty(&rtpcp->cblist) || !cpu_possible(cpu))
480                 return;
481         raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
482         rcu_segcblist_advance(&rtpcp->cblist, rcu_seq_current(&rtp->tasks_gp_seq));
483         rcu_segcblist_extract_done_cbs(&rtpcp->cblist, &rcl);
484         raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
485         len = rcl.len;
486         for (rhp = rcu_cblist_dequeue(&rcl); rhp; rhp = rcu_cblist_dequeue(&rcl)) {
487                 local_bh_disable();
488                 rhp->func(rhp);
489                 local_bh_enable();
490                 cond_resched();
491         }
492         raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
493         rcu_segcblist_add_len(&rtpcp->cblist, -len);
494         (void)rcu_segcblist_accelerate(&rtpcp->cblist, rcu_seq_snap(&rtp->tasks_gp_seq));
495         raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
496 }
497
498 // Workqueue flood to advance callbacks and invoke any that are ready.
499 static void rcu_tasks_invoke_cbs_wq(struct work_struct *wp)
500 {
501         struct rcu_tasks *rtp;
502         struct rcu_tasks_percpu *rtpcp = container_of(wp, struct rcu_tasks_percpu, rtp_work);
503
504         rtp = rtpcp->rtpp;
505         rcu_tasks_invoke_cbs(rtp, rtpcp);
506 }
507
508 // Wait for one grace period.
509 static void rcu_tasks_one_gp(struct rcu_tasks *rtp, bool midboot)
510 {
511         int needgpcb;
512
513         mutex_lock(&rtp->tasks_gp_mutex);
514
515         // If there were none, wait a bit and start over.
516         if (unlikely(midboot)) {
517                 needgpcb = 0x2;
518         } else {
519                 set_tasks_gp_state(rtp, RTGS_WAIT_CBS);
520                 rcuwait_wait_event(&rtp->cbs_wait,
521                                    (needgpcb = rcu_tasks_need_gpcb(rtp)),
522                                    TASK_IDLE);
523         }
524
525         if (needgpcb & 0x2) {
526                 // Wait for one grace period.
527                 set_tasks_gp_state(rtp, RTGS_WAIT_GP);
528                 rtp->gp_start = jiffies;
529                 rcu_seq_start(&rtp->tasks_gp_seq);
530                 rtp->gp_func(rtp);
531                 rcu_seq_end(&rtp->tasks_gp_seq);
532         }
533
534         // Invoke callbacks.
535         set_tasks_gp_state(rtp, RTGS_INVOKE_CBS);
536         rcu_tasks_invoke_cbs(rtp, per_cpu_ptr(rtp->rtpcpu, 0));
537         mutex_unlock(&rtp->tasks_gp_mutex);
538 }
539
540 // RCU-tasks kthread that detects grace periods and invokes callbacks.
541 static int __noreturn rcu_tasks_kthread(void *arg)
542 {
543         struct rcu_tasks *rtp = arg;
544
545         /* Run on housekeeping CPUs by default.  Sysadm can move if desired. */
546         housekeeping_affine(current, HK_TYPE_RCU);
547         WRITE_ONCE(rtp->kthread_ptr, current); // Let GPs start!
548
549         /*
550          * Each pass through the following loop makes one check for
551          * newly arrived callbacks, and, if there are some, waits for
552          * one RCU-tasks grace period and then invokes the callbacks.
553          * This loop is terminated by the system going down.  ;-)
554          */
555         for (;;) {
556                 // Wait for one grace period and invoke any callbacks
557                 // that are ready.
558                 rcu_tasks_one_gp(rtp, false);
559
560                 // Paranoid sleep to keep this from entering a tight loop.
561                 schedule_timeout_idle(rtp->gp_sleep);
562         }
563 }
564
565 // Wait for a grace period for the specified flavor of Tasks RCU.
566 static void synchronize_rcu_tasks_generic(struct rcu_tasks *rtp)
567 {
568         /* Complain if the scheduler has not started.  */
569         if (WARN_ONCE(rcu_scheduler_active == RCU_SCHEDULER_INACTIVE,
570                          "synchronize_%s() called too soon", rtp->name))
571                 return;
572
573         // If the grace-period kthread is running, use it.
574         if (READ_ONCE(rtp->kthread_ptr)) {
575                 wait_rcu_gp(rtp->call_func);
576                 return;
577         }
578         rcu_tasks_one_gp(rtp, true);
579 }
580
581 /* Spawn RCU-tasks grace-period kthread. */
582 static void __init rcu_spawn_tasks_kthread_generic(struct rcu_tasks *rtp)
583 {
584         struct task_struct *t;
585
586         t = kthread_run(rcu_tasks_kthread, rtp, "%s_kthread", rtp->kname);
587         if (WARN_ONCE(IS_ERR(t), "%s: Could not start %s grace-period kthread, OOM is now expected behavior\n", __func__, rtp->name))
588                 return;
589         smp_mb(); /* Ensure others see full kthread. */
590 }
591
592 #ifndef CONFIG_TINY_RCU
593
594 /*
595  * Print any non-default Tasks RCU settings.
596  */
597 static void __init rcu_tasks_bootup_oddness(void)
598 {
599 #if defined(CONFIG_TASKS_RCU) || defined(CONFIG_TASKS_TRACE_RCU)
600         int rtsimc;
601
602         if (rcu_task_stall_timeout != RCU_TASK_STALL_TIMEOUT)
603                 pr_info("\tTasks-RCU CPU stall warnings timeout set to %d (rcu_task_stall_timeout).\n", rcu_task_stall_timeout);
604         rtsimc = clamp(rcu_task_stall_info_mult, 1, 10);
605         if (rtsimc != rcu_task_stall_info_mult) {
606                 pr_info("\tTasks-RCU CPU stall info multiplier clamped to %d (rcu_task_stall_info_mult).\n", rtsimc);
607                 rcu_task_stall_info_mult = rtsimc;
608         }
609 #endif /* #ifdef CONFIG_TASKS_RCU */
610 #ifdef CONFIG_TASKS_RCU
611         pr_info("\tTrampoline variant of Tasks RCU enabled.\n");
612 #endif /* #ifdef CONFIG_TASKS_RCU */
613 #ifdef CONFIG_TASKS_RUDE_RCU
614         pr_info("\tRude variant of Tasks RCU enabled.\n");
615 #endif /* #ifdef CONFIG_TASKS_RUDE_RCU */
616 #ifdef CONFIG_TASKS_TRACE_RCU
617         pr_info("\tTracing variant of Tasks RCU enabled.\n");
618 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
619 }
620
621 #endif /* #ifndef CONFIG_TINY_RCU */
622
623 #ifndef CONFIG_TINY_RCU
624 /* Dump out rcutorture-relevant state common to all RCU-tasks flavors. */
625 static void show_rcu_tasks_generic_gp_kthread(struct rcu_tasks *rtp, char *s)
626 {
627         int cpu;
628         bool havecbs = false;
629
630         for_each_possible_cpu(cpu) {
631                 struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
632
633                 if (!data_race(rcu_segcblist_empty(&rtpcp->cblist))) {
634                         havecbs = true;
635                         break;
636                 }
637         }
638         pr_info("%s: %s(%d) since %lu g:%lu i:%lu/%lu %c%c %s\n",
639                 rtp->kname,
640                 tasks_gp_state_getname(rtp), data_race(rtp->gp_state),
641                 jiffies - data_race(rtp->gp_jiffies),
642                 data_race(rcu_seq_current(&rtp->tasks_gp_seq)),
643                 data_race(rtp->n_ipis_fails), data_race(rtp->n_ipis),
644                 ".k"[!!data_race(rtp->kthread_ptr)],
645                 ".C"[havecbs],
646                 s);
647 }
648 #endif // #ifndef CONFIG_TINY_RCU
649
650 static void exit_tasks_rcu_finish_trace(struct task_struct *t);
651
652 #if defined(CONFIG_TASKS_RCU) || defined(CONFIG_TASKS_TRACE_RCU)
653
654 ////////////////////////////////////////////////////////////////////////
655 //
656 // Shared code between task-list-scanning variants of Tasks RCU.
657
658 /* Wait for one RCU-tasks grace period. */
659 static void rcu_tasks_wait_gp(struct rcu_tasks *rtp)
660 {
661         struct task_struct *g;
662         int fract;
663         LIST_HEAD(holdouts);
664         unsigned long j;
665         unsigned long lastinfo;
666         unsigned long lastreport;
667         bool reported = false;
668         int rtsi;
669         struct task_struct *t;
670
671         set_tasks_gp_state(rtp, RTGS_PRE_WAIT_GP);
672         rtp->pregp_func(&holdouts);
673
674         /*
675          * There were callbacks, so we need to wait for an RCU-tasks
676          * grace period.  Start off by scanning the task list for tasks
677          * that are not already voluntarily blocked.  Mark these tasks
678          * and make a list of them in holdouts.
679          */
680         set_tasks_gp_state(rtp, RTGS_SCAN_TASKLIST);
681         if (rtp->pertask_func) {
682                 rcu_read_lock();
683                 for_each_process_thread(g, t)
684                         rtp->pertask_func(t, &holdouts);
685                 rcu_read_unlock();
686         }
687
688         set_tasks_gp_state(rtp, RTGS_POST_SCAN_TASKLIST);
689         rtp->postscan_func(&holdouts);
690
691         /*
692          * Each pass through the following loop scans the list of holdout
693          * tasks, removing any that are no longer holdouts.  When the list
694          * is empty, we are done.
695          */
696         lastreport = jiffies;
697         lastinfo = lastreport;
698         rtsi = READ_ONCE(rcu_task_stall_info);
699
700         // Start off with initial wait and slowly back off to 1 HZ wait.
701         fract = rtp->init_fract;
702
703         while (!list_empty(&holdouts)) {
704                 ktime_t exp;
705                 bool firstreport;
706                 bool needreport;
707                 int rtst;
708
709                 // Slowly back off waiting for holdouts
710                 set_tasks_gp_state(rtp, RTGS_WAIT_SCAN_HOLDOUTS);
711                 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
712                         schedule_timeout_idle(fract);
713                 } else {
714                         exp = jiffies_to_nsecs(fract);
715                         __set_current_state(TASK_IDLE);
716                         schedule_hrtimeout_range(&exp, jiffies_to_nsecs(HZ / 2), HRTIMER_MODE_REL_HARD);
717                 }
718
719                 if (fract < HZ)
720                         fract++;
721
722                 rtst = READ_ONCE(rcu_task_stall_timeout);
723                 needreport = rtst > 0 && time_after(jiffies, lastreport + rtst);
724                 if (needreport) {
725                         lastreport = jiffies;
726                         reported = true;
727                 }
728                 firstreport = true;
729                 WARN_ON(signal_pending(current));
730                 set_tasks_gp_state(rtp, RTGS_SCAN_HOLDOUTS);
731                 rtp->holdouts_func(&holdouts, needreport, &firstreport);
732
733                 // Print pre-stall informational messages if needed.
734                 j = jiffies;
735                 if (rtsi > 0 && !reported && time_after(j, lastinfo + rtsi)) {
736                         lastinfo = j;
737                         rtsi = rtsi * rcu_task_stall_info_mult;
738                         pr_info("%s: %s grace period %lu is %lu jiffies old.\n",
739                                 __func__, rtp->kname, rtp->tasks_gp_seq, j - rtp->gp_start);
740                 }
741         }
742
743         set_tasks_gp_state(rtp, RTGS_POST_GP);
744         rtp->postgp_func(rtp);
745 }
746
747 #endif /* #if defined(CONFIG_TASKS_RCU) || defined(CONFIG_TASKS_TRACE_RCU) */
748
749 #ifdef CONFIG_TASKS_RCU
750
751 ////////////////////////////////////////////////////////////////////////
752 //
753 // Simple variant of RCU whose quiescent states are voluntary context
754 // switch, cond_resched_tasks_rcu_qs(), user-space execution, and idle.
755 // As such, grace periods can take one good long time.  There are no
756 // read-side primitives similar to rcu_read_lock() and rcu_read_unlock()
757 // because this implementation is intended to get the system into a safe
758 // state for some of the manipulations involved in tracing and the like.
759 // Finally, this implementation does not support high call_rcu_tasks()
760 // rates from multiple CPUs.  If this is required, per-CPU callback lists
761 // will be needed.
762 //
763 // The implementation uses rcu_tasks_wait_gp(), which relies on function
764 // pointers in the rcu_tasks structure.  The rcu_spawn_tasks_kthread()
765 // function sets these function pointers up so that rcu_tasks_wait_gp()
766 // invokes these functions in this order:
767 //
768 // rcu_tasks_pregp_step():
769 //      Invokes synchronize_rcu() in order to wait for all in-flight
770 //      t->on_rq and t->nvcsw transitions to complete.  This works because
771 //      all such transitions are carried out with interrupts disabled.
772 // rcu_tasks_pertask(), invoked on every non-idle task:
773 //      For every runnable non-idle task other than the current one, use
774 //      get_task_struct() to pin down that task, snapshot that task's
775 //      number of voluntary context switches, and add that task to the
776 //      holdout list.
777 // rcu_tasks_postscan():
778 //      Invoke synchronize_srcu() to ensure that all tasks that were
779 //      in the process of exiting (and which thus might not know to
780 //      synchronize with this RCU Tasks grace period) have completed
781 //      exiting.
782 // check_all_holdout_tasks(), repeatedly until holdout list is empty:
783 //      Scans the holdout list, attempting to identify a quiescent state
784 //      for each task on the list.  If there is a quiescent state, the
785 //      corresponding task is removed from the holdout list.
786 // rcu_tasks_postgp():
787 //      Invokes synchronize_rcu() in order to ensure that all prior
788 //      t->on_rq and t->nvcsw transitions are seen by all CPUs and tasks
789 //      to have happened before the end of this RCU Tasks grace period.
790 //      Again, this works because all such transitions are carried out
791 //      with interrupts disabled.
792 //
793 // For each exiting task, the exit_tasks_rcu_start() and
794 // exit_tasks_rcu_finish() functions begin and end, respectively, the SRCU
795 // read-side critical sections waited for by rcu_tasks_postscan().
796 //
797 // Pre-grace-period update-side code is ordered before the grace
798 // via the raw_spin_lock.*rcu_node().  Pre-grace-period read-side code
799 // is ordered before the grace period via synchronize_rcu() call in
800 // rcu_tasks_pregp_step() and by the scheduler's locks and interrupt
801 // disabling.
802
803 /* Pre-grace-period preparation. */
804 static void rcu_tasks_pregp_step(struct list_head *hop)
805 {
806         /*
807          * Wait for all pre-existing t->on_rq and t->nvcsw transitions
808          * to complete.  Invoking synchronize_rcu() suffices because all
809          * these transitions occur with interrupts disabled.  Without this
810          * synchronize_rcu(), a read-side critical section that started
811          * before the grace period might be incorrectly seen as having
812          * started after the grace period.
813          *
814          * This synchronize_rcu() also dispenses with the need for a
815          * memory barrier on the first store to t->rcu_tasks_holdout,
816          * as it forces the store to happen after the beginning of the
817          * grace period.
818          */
819         synchronize_rcu();
820 }
821
822 /* Per-task initial processing. */
823 static void rcu_tasks_pertask(struct task_struct *t, struct list_head *hop)
824 {
825         if (t != current && READ_ONCE(t->on_rq) && !is_idle_task(t)) {
826                 get_task_struct(t);
827                 t->rcu_tasks_nvcsw = READ_ONCE(t->nvcsw);
828                 WRITE_ONCE(t->rcu_tasks_holdout, true);
829                 list_add(&t->rcu_tasks_holdout_list, hop);
830         }
831 }
832
833 /* Processing between scanning taskslist and draining the holdout list. */
834 static void rcu_tasks_postscan(struct list_head *hop)
835 {
836         /*
837          * Exiting tasks may escape the tasklist scan. Those are vulnerable
838          * until their final schedule() with TASK_DEAD state. To cope with
839          * this, divide the fragile exit path part in two intersecting
840          * read side critical sections:
841          *
842          * 1) An _SRCU_ read side starting before calling exit_notify(),
843          *    which may remove the task from the tasklist, and ending after
844          *    the final preempt_disable() call in do_exit().
845          *
846          * 2) An _RCU_ read side starting with the final preempt_disable()
847          *    call in do_exit() and ending with the final call to schedule()
848          *    with TASK_DEAD state.
849          *
850          * This handles the part 1). And postgp will handle part 2) with a
851          * call to synchronize_rcu().
852          */
853         synchronize_srcu(&tasks_rcu_exit_srcu);
854 }
855
856 /* See if tasks are still holding out, complain if so. */
857 static void check_holdout_task(struct task_struct *t,
858                                bool needreport, bool *firstreport)
859 {
860         int cpu;
861
862         if (!READ_ONCE(t->rcu_tasks_holdout) ||
863             t->rcu_tasks_nvcsw != READ_ONCE(t->nvcsw) ||
864             !READ_ONCE(t->on_rq) ||
865             (IS_ENABLED(CONFIG_NO_HZ_FULL) &&
866              !is_idle_task(t) && t->rcu_tasks_idle_cpu >= 0)) {
867                 WRITE_ONCE(t->rcu_tasks_holdout, false);
868                 list_del_init(&t->rcu_tasks_holdout_list);
869                 put_task_struct(t);
870                 return;
871         }
872         rcu_request_urgent_qs_task(t);
873         if (!needreport)
874                 return;
875         if (*firstreport) {
876                 pr_err("INFO: rcu_tasks detected stalls on tasks:\n");
877                 *firstreport = false;
878         }
879         cpu = task_cpu(t);
880         pr_alert("%p: %c%c nvcsw: %lu/%lu holdout: %d idle_cpu: %d/%d\n",
881                  t, ".I"[is_idle_task(t)],
882                  "N."[cpu < 0 || !tick_nohz_full_cpu(cpu)],
883                  t->rcu_tasks_nvcsw, t->nvcsw, t->rcu_tasks_holdout,
884                  t->rcu_tasks_idle_cpu, cpu);
885         sched_show_task(t);
886 }
887
888 /* Scan the holdout lists for tasks no longer holding out. */
889 static void check_all_holdout_tasks(struct list_head *hop,
890                                     bool needreport, bool *firstreport)
891 {
892         struct task_struct *t, *t1;
893
894         list_for_each_entry_safe(t, t1, hop, rcu_tasks_holdout_list) {
895                 check_holdout_task(t, needreport, firstreport);
896                 cond_resched();
897         }
898 }
899
900 /* Finish off the Tasks-RCU grace period. */
901 static void rcu_tasks_postgp(struct rcu_tasks *rtp)
902 {
903         /*
904          * Because ->on_rq and ->nvcsw are not guaranteed to have a full
905          * memory barriers prior to them in the schedule() path, memory
906          * reordering on other CPUs could cause their RCU-tasks read-side
907          * critical sections to extend past the end of the grace period.
908          * However, because these ->nvcsw updates are carried out with
909          * interrupts disabled, we can use synchronize_rcu() to force the
910          * needed ordering on all such CPUs.
911          *
912          * This synchronize_rcu() also confines all ->rcu_tasks_holdout
913          * accesses to be within the grace period, avoiding the need for
914          * memory barriers for ->rcu_tasks_holdout accesses.
915          *
916          * In addition, this synchronize_rcu() waits for exiting tasks
917          * to complete their final preempt_disable() region of execution,
918          * cleaning up after synchronize_srcu(&tasks_rcu_exit_srcu),
919          * enforcing the whole region before tasklist removal until
920          * the final schedule() with TASK_DEAD state to be an RCU TASKS
921          * read side critical section.
922          */
923         synchronize_rcu();
924 }
925
926 void call_rcu_tasks(struct rcu_head *rhp, rcu_callback_t func);
927 DEFINE_RCU_TASKS(rcu_tasks, rcu_tasks_wait_gp, call_rcu_tasks, "RCU Tasks");
928
929 /**
930  * call_rcu_tasks() - Queue an RCU for invocation task-based grace period
931  * @rhp: structure to be used for queueing the RCU updates.
932  * @func: actual callback function to be invoked after the grace period
933  *
934  * The callback function will be invoked some time after a full grace
935  * period elapses, in other words after all currently executing RCU
936  * read-side critical sections have completed. call_rcu_tasks() assumes
937  * that the read-side critical sections end at a voluntary context
938  * switch (not a preemption!), cond_resched_tasks_rcu_qs(), entry into idle,
939  * or transition to usermode execution.  As such, there are no read-side
940  * primitives analogous to rcu_read_lock() and rcu_read_unlock() because
941  * this primitive is intended to determine that all tasks have passed
942  * through a safe state, not so much for data-structure synchronization.
943  *
944  * See the description of call_rcu() for more detailed information on
945  * memory ordering guarantees.
946  */
947 void call_rcu_tasks(struct rcu_head *rhp, rcu_callback_t func)
948 {
949         call_rcu_tasks_generic(rhp, func, &rcu_tasks);
950 }
951 EXPORT_SYMBOL_GPL(call_rcu_tasks);
952
953 /**
954  * synchronize_rcu_tasks - wait until an rcu-tasks grace period has elapsed.
955  *
956  * Control will return to the caller some time after a full rcu-tasks
957  * grace period has elapsed, in other words after all currently
958  * executing rcu-tasks read-side critical sections have elapsed.  These
959  * read-side critical sections are delimited by calls to schedule(),
960  * cond_resched_tasks_rcu_qs(), idle execution, userspace execution, calls
961  * to synchronize_rcu_tasks(), and (in theory, anyway) cond_resched().
962  *
963  * This is a very specialized primitive, intended only for a few uses in
964  * tracing and other situations requiring manipulation of function
965  * preambles and profiling hooks.  The synchronize_rcu_tasks() function
966  * is not (yet) intended for heavy use from multiple CPUs.
967  *
968  * See the description of synchronize_rcu() for more detailed information
969  * on memory ordering guarantees.
970  */
971 void synchronize_rcu_tasks(void)
972 {
973         synchronize_rcu_tasks_generic(&rcu_tasks);
974 }
975 EXPORT_SYMBOL_GPL(synchronize_rcu_tasks);
976
977 /**
978  * rcu_barrier_tasks - Wait for in-flight call_rcu_tasks() callbacks.
979  *
980  * Although the current implementation is guaranteed to wait, it is not
981  * obligated to, for example, if there are no pending callbacks.
982  */
983 void rcu_barrier_tasks(void)
984 {
985         rcu_barrier_tasks_generic(&rcu_tasks);
986 }
987 EXPORT_SYMBOL_GPL(rcu_barrier_tasks);
988
989 static int __init rcu_spawn_tasks_kthread(void)
990 {
991         cblist_init_generic(&rcu_tasks);
992         rcu_tasks.gp_sleep = HZ / 10;
993         rcu_tasks.init_fract = HZ / 10;
994         rcu_tasks.pregp_func = rcu_tasks_pregp_step;
995         rcu_tasks.pertask_func = rcu_tasks_pertask;
996         rcu_tasks.postscan_func = rcu_tasks_postscan;
997         rcu_tasks.holdouts_func = check_all_holdout_tasks;
998         rcu_tasks.postgp_func = rcu_tasks_postgp;
999         rcu_spawn_tasks_kthread_generic(&rcu_tasks);
1000         return 0;
1001 }
1002
1003 #if !defined(CONFIG_TINY_RCU)
1004 void show_rcu_tasks_classic_gp_kthread(void)
1005 {
1006         show_rcu_tasks_generic_gp_kthread(&rcu_tasks, "");
1007 }
1008 EXPORT_SYMBOL_GPL(show_rcu_tasks_classic_gp_kthread);
1009 #endif // !defined(CONFIG_TINY_RCU)
1010
1011 /*
1012  * Contribute to protect against tasklist scan blind spot while the
1013  * task is exiting and may be removed from the tasklist. See
1014  * corresponding synchronize_srcu() for further details.
1015  */
1016 void exit_tasks_rcu_start(void) __acquires(&tasks_rcu_exit_srcu)
1017 {
1018         current->rcu_tasks_idx = __srcu_read_lock(&tasks_rcu_exit_srcu);
1019 }
1020
1021 /*
1022  * Contribute to protect against tasklist scan blind spot while the
1023  * task is exiting and may be removed from the tasklist. See
1024  * corresponding synchronize_srcu() for further details.
1025  */
1026 void exit_tasks_rcu_stop(void) __releases(&tasks_rcu_exit_srcu)
1027 {
1028         struct task_struct *t = current;
1029
1030         __srcu_read_unlock(&tasks_rcu_exit_srcu, t->rcu_tasks_idx);
1031 }
1032
1033 /*
1034  * Contribute to protect against tasklist scan blind spot while the
1035  * task is exiting and may be removed from the tasklist. See
1036  * corresponding synchronize_srcu() for further details.
1037  */
1038 void exit_tasks_rcu_finish(void)
1039 {
1040         exit_tasks_rcu_stop();
1041         exit_tasks_rcu_finish_trace(current);
1042 }
1043
1044 #else /* #ifdef CONFIG_TASKS_RCU */
1045 void exit_tasks_rcu_start(void) { }
1046 void exit_tasks_rcu_stop(void) { }
1047 void exit_tasks_rcu_finish(void) { exit_tasks_rcu_finish_trace(current); }
1048 #endif /* #else #ifdef CONFIG_TASKS_RCU */
1049
1050 #ifdef CONFIG_TASKS_RUDE_RCU
1051
1052 ////////////////////////////////////////////////////////////////////////
1053 //
1054 // "Rude" variant of Tasks RCU, inspired by Steve Rostedt's trick of
1055 // passing an empty function to schedule_on_each_cpu().  This approach
1056 // provides an asynchronous call_rcu_tasks_rude() API and batching of
1057 // concurrent calls to the synchronous synchronize_rcu_tasks_rude() API.
1058 // This invokes schedule_on_each_cpu() in order to send IPIs far and wide
1059 // and induces otherwise unnecessary context switches on all online CPUs,
1060 // whether idle or not.
1061 //
1062 // Callback handling is provided by the rcu_tasks_kthread() function.
1063 //
1064 // Ordering is provided by the scheduler's context-switch code.
1065
1066 // Empty function to allow workqueues to force a context switch.
1067 static void rcu_tasks_be_rude(struct work_struct *work)
1068 {
1069 }
1070
1071 // Wait for one rude RCU-tasks grace period.
1072 static void rcu_tasks_rude_wait_gp(struct rcu_tasks *rtp)
1073 {
1074         rtp->n_ipis += cpumask_weight(cpu_online_mask);
1075         schedule_on_each_cpu(rcu_tasks_be_rude);
1076 }
1077
1078 void call_rcu_tasks_rude(struct rcu_head *rhp, rcu_callback_t func);
1079 DEFINE_RCU_TASKS(rcu_tasks_rude, rcu_tasks_rude_wait_gp, call_rcu_tasks_rude,
1080                  "RCU Tasks Rude");
1081
1082 /**
1083  * call_rcu_tasks_rude() - Queue a callback rude task-based grace period
1084  * @rhp: structure to be used for queueing the RCU updates.
1085  * @func: actual callback function to be invoked after the grace period
1086  *
1087  * The callback function will be invoked some time after a full grace
1088  * period elapses, in other words after all currently executing RCU
1089  * read-side critical sections have completed. call_rcu_tasks_rude()
1090  * assumes that the read-side critical sections end at context switch,
1091  * cond_resched_tasks_rcu_qs(), or transition to usermode execution (as
1092  * usermode execution is schedulable). As such, there are no read-side
1093  * primitives analogous to rcu_read_lock() and rcu_read_unlock() because
1094  * this primitive is intended to determine that all tasks have passed
1095  * through a safe state, not so much for data-structure synchronization.
1096  *
1097  * See the description of call_rcu() for more detailed information on
1098  * memory ordering guarantees.
1099  */
1100 void call_rcu_tasks_rude(struct rcu_head *rhp, rcu_callback_t func)
1101 {
1102         call_rcu_tasks_generic(rhp, func, &rcu_tasks_rude);
1103 }
1104 EXPORT_SYMBOL_GPL(call_rcu_tasks_rude);
1105
1106 /**
1107  * synchronize_rcu_tasks_rude - wait for a rude rcu-tasks grace period
1108  *
1109  * Control will return to the caller some time after a rude rcu-tasks
1110  * grace period has elapsed, in other words after all currently
1111  * executing rcu-tasks read-side critical sections have elapsed.  These
1112  * read-side critical sections are delimited by calls to schedule(),
1113  * cond_resched_tasks_rcu_qs(), userspace execution (which is a schedulable
1114  * context), and (in theory, anyway) cond_resched().
1115  *
1116  * This is a very specialized primitive, intended only for a few uses in
1117  * tracing and other situations requiring manipulation of function preambles
1118  * and profiling hooks.  The synchronize_rcu_tasks_rude() function is not
1119  * (yet) intended for heavy use from multiple CPUs.
1120  *
1121  * See the description of synchronize_rcu() for more detailed information
1122  * on memory ordering guarantees.
1123  */
1124 void synchronize_rcu_tasks_rude(void)
1125 {
1126         synchronize_rcu_tasks_generic(&rcu_tasks_rude);
1127 }
1128 EXPORT_SYMBOL_GPL(synchronize_rcu_tasks_rude);
1129
1130 /**
1131  * rcu_barrier_tasks_rude - Wait for in-flight call_rcu_tasks_rude() callbacks.
1132  *
1133  * Although the current implementation is guaranteed to wait, it is not
1134  * obligated to, for example, if there are no pending callbacks.
1135  */
1136 void rcu_barrier_tasks_rude(void)
1137 {
1138         rcu_barrier_tasks_generic(&rcu_tasks_rude);
1139 }
1140 EXPORT_SYMBOL_GPL(rcu_barrier_tasks_rude);
1141
1142 static int __init rcu_spawn_tasks_rude_kthread(void)
1143 {
1144         cblist_init_generic(&rcu_tasks_rude);
1145         rcu_tasks_rude.gp_sleep = HZ / 10;
1146         rcu_spawn_tasks_kthread_generic(&rcu_tasks_rude);
1147         return 0;
1148 }
1149
1150 #if !defined(CONFIG_TINY_RCU)
1151 void show_rcu_tasks_rude_gp_kthread(void)
1152 {
1153         show_rcu_tasks_generic_gp_kthread(&rcu_tasks_rude, "");
1154 }
1155 EXPORT_SYMBOL_GPL(show_rcu_tasks_rude_gp_kthread);
1156 #endif // !defined(CONFIG_TINY_RCU)
1157 #endif /* #ifdef CONFIG_TASKS_RUDE_RCU */
1158
1159 ////////////////////////////////////////////////////////////////////////
1160 //
1161 // Tracing variant of Tasks RCU.  This variant is designed to be used
1162 // to protect tracing hooks, including those of BPF.  This variant
1163 // therefore:
1164 //
1165 // 1.   Has explicit read-side markers to allow finite grace periods
1166 //      in the face of in-kernel loops for PREEMPT=n builds.
1167 //
1168 // 2.   Protects code in the idle loop, exception entry/exit, and
1169 //      CPU-hotplug code paths, similar to the capabilities of SRCU.
1170 //
1171 // 3.   Avoids expensive read-side instructions, having overhead similar
1172 //      to that of Preemptible RCU.
1173 //
1174 // There are of course downsides.  For example, the grace-period code
1175 // can send IPIs to CPUs, even when those CPUs are in the idle loop or
1176 // in nohz_full userspace.  If needed, these downsides can be at least
1177 // partially remedied.
1178 //
1179 // Perhaps most important, this variant of RCU does not affect the vanilla
1180 // flavors, rcu_preempt and rcu_sched.  The fact that RCU Tasks Trace
1181 // readers can operate from idle, offline, and exception entry/exit in no
1182 // way allows rcu_preempt and rcu_sched readers to also do so.
1183 //
1184 // The implementation uses rcu_tasks_wait_gp(), which relies on function
1185 // pointers in the rcu_tasks structure.  The rcu_spawn_tasks_trace_kthread()
1186 // function sets these function pointers up so that rcu_tasks_wait_gp()
1187 // invokes these functions in this order:
1188 //
1189 // rcu_tasks_trace_pregp_step():
1190 //      Disables CPU hotplug, adds all currently executing tasks to the
1191 //      holdout list, then checks the state of all tasks that blocked
1192 //      or were preempted within their current RCU Tasks Trace read-side
1193 //      critical section, adding them to the holdout list if appropriate.
1194 //      Finally, this function re-enables CPU hotplug.
1195 // The ->pertask_func() pointer is NULL, so there is no per-task processing.
1196 // rcu_tasks_trace_postscan():
1197 //      Invokes synchronize_rcu() to wait for late-stage exiting tasks
1198 //      to finish exiting.
1199 // check_all_holdout_tasks_trace(), repeatedly until holdout list is empty:
1200 //      Scans the holdout list, attempting to identify a quiescent state
1201 //      for each task on the list.  If there is a quiescent state, the
1202 //      corresponding task is removed from the holdout list.  Once this
1203 //      list is empty, the grace period has completed.
1204 // rcu_tasks_trace_postgp():
1205 //      Provides the needed full memory barrier and does debug checks.
1206 //
1207 // The exit_tasks_rcu_finish_trace() synchronizes with exiting tasks.
1208 //
1209 // Pre-grace-period update-side code is ordered before the grace period
1210 // via the ->cbs_lock and barriers in rcu_tasks_kthread().  Pre-grace-period
1211 // read-side code is ordered before the grace period by atomic operations
1212 // on .b.need_qs flag of each task involved in this process, or by scheduler
1213 // context-switch ordering (for locked-down non-running readers).
1214
1215 // The lockdep state must be outside of #ifdef to be useful.
1216 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1217 static struct lock_class_key rcu_lock_trace_key;
1218 struct lockdep_map rcu_trace_lock_map =
1219         STATIC_LOCKDEP_MAP_INIT("rcu_read_lock_trace", &rcu_lock_trace_key);
1220 EXPORT_SYMBOL_GPL(rcu_trace_lock_map);
1221 #endif /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
1222
1223 #ifdef CONFIG_TASKS_TRACE_RCU
1224
1225 // Record outstanding IPIs to each CPU.  No point in sending two...
1226 static DEFINE_PER_CPU(bool, trc_ipi_to_cpu);
1227
1228 // The number of detections of task quiescent state relying on
1229 // heavyweight readers executing explicit memory barriers.
1230 static unsigned long n_heavy_reader_attempts;
1231 static unsigned long n_heavy_reader_updates;
1232 static unsigned long n_heavy_reader_ofl_updates;
1233 static unsigned long n_trc_holdouts;
1234
1235 void call_rcu_tasks_trace(struct rcu_head *rhp, rcu_callback_t func);
1236 DEFINE_RCU_TASKS(rcu_tasks_trace, rcu_tasks_wait_gp, call_rcu_tasks_trace,
1237                  "RCU Tasks Trace");
1238
1239 /* Load from ->trc_reader_special.b.need_qs with proper ordering. */
1240 static u8 rcu_ld_need_qs(struct task_struct *t)
1241 {
1242         smp_mb(); // Enforce full grace-period ordering.
1243         return smp_load_acquire(&t->trc_reader_special.b.need_qs);
1244 }
1245
1246 /* Store to ->trc_reader_special.b.need_qs with proper ordering. */
1247 static void rcu_st_need_qs(struct task_struct *t, u8 v)
1248 {
1249         smp_store_release(&t->trc_reader_special.b.need_qs, v);
1250         smp_mb(); // Enforce full grace-period ordering.
1251 }
1252
1253 /*
1254  * Do a cmpxchg() on ->trc_reader_special.b.need_qs, allowing for
1255  * the four-byte operand-size restriction of some platforms.
1256  * Returns the old value, which is often ignored.
1257  */
1258 u8 rcu_trc_cmpxchg_need_qs(struct task_struct *t, u8 old, u8 new)
1259 {
1260         union rcu_special ret;
1261         union rcu_special trs_old = READ_ONCE(t->trc_reader_special);
1262         union rcu_special trs_new = trs_old;
1263
1264         if (trs_old.b.need_qs != old)
1265                 return trs_old.b.need_qs;
1266         trs_new.b.need_qs = new;
1267         ret.s = cmpxchg(&t->trc_reader_special.s, trs_old.s, trs_new.s);
1268         return ret.b.need_qs;
1269 }
1270 EXPORT_SYMBOL_GPL(rcu_trc_cmpxchg_need_qs);
1271
1272 /*
1273  * If we are the last reader, signal the grace-period kthread.
1274  * Also remove from the per-CPU list of blocked tasks.
1275  */
1276 void rcu_read_unlock_trace_special(struct task_struct *t)
1277 {
1278         unsigned long flags;
1279         struct rcu_tasks_percpu *rtpcp;
1280         union rcu_special trs;
1281
1282         // Open-coded full-word version of rcu_ld_need_qs().
1283         smp_mb(); // Enforce full grace-period ordering.
1284         trs = smp_load_acquire(&t->trc_reader_special);
1285
1286         if (IS_ENABLED(CONFIG_TASKS_TRACE_RCU_READ_MB) && t->trc_reader_special.b.need_mb)
1287                 smp_mb(); // Pairs with update-side barriers.
1288         // Update .need_qs before ->trc_reader_nesting for irq/NMI handlers.
1289         if (trs.b.need_qs == (TRC_NEED_QS_CHECKED | TRC_NEED_QS)) {
1290                 u8 result = rcu_trc_cmpxchg_need_qs(t, TRC_NEED_QS_CHECKED | TRC_NEED_QS,
1291                                                        TRC_NEED_QS_CHECKED);
1292
1293                 WARN_ONCE(result != trs.b.need_qs, "%s: result = %d", __func__, result);
1294         }
1295         if (trs.b.blocked) {
1296                 rtpcp = per_cpu_ptr(rcu_tasks_trace.rtpcpu, t->trc_blkd_cpu);
1297                 raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
1298                 list_del_init(&t->trc_blkd_node);
1299                 WRITE_ONCE(t->trc_reader_special.b.blocked, false);
1300                 raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
1301         }
1302         WRITE_ONCE(t->trc_reader_nesting, 0);
1303 }
1304 EXPORT_SYMBOL_GPL(rcu_read_unlock_trace_special);
1305
1306 /* Add a newly blocked reader task to its CPU's list. */
1307 void rcu_tasks_trace_qs_blkd(struct task_struct *t)
1308 {
1309         unsigned long flags;
1310         struct rcu_tasks_percpu *rtpcp;
1311
1312         local_irq_save(flags);
1313         rtpcp = this_cpu_ptr(rcu_tasks_trace.rtpcpu);
1314         raw_spin_lock_rcu_node(rtpcp); // irqs already disabled
1315         t->trc_blkd_cpu = smp_processor_id();
1316         if (!rtpcp->rtp_blkd_tasks.next)
1317                 INIT_LIST_HEAD(&rtpcp->rtp_blkd_tasks);
1318         list_add(&t->trc_blkd_node, &rtpcp->rtp_blkd_tasks);
1319         WRITE_ONCE(t->trc_reader_special.b.blocked, true);
1320         raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
1321 }
1322 EXPORT_SYMBOL_GPL(rcu_tasks_trace_qs_blkd);
1323
1324 /* Add a task to the holdout list, if it is not already on the list. */
1325 static void trc_add_holdout(struct task_struct *t, struct list_head *bhp)
1326 {
1327         if (list_empty(&t->trc_holdout_list)) {
1328                 get_task_struct(t);
1329                 list_add(&t->trc_holdout_list, bhp);
1330                 n_trc_holdouts++;
1331         }
1332 }
1333
1334 /* Remove a task from the holdout list, if it is in fact present. */
1335 static void trc_del_holdout(struct task_struct *t)
1336 {
1337         if (!list_empty(&t->trc_holdout_list)) {
1338                 list_del_init(&t->trc_holdout_list);
1339                 put_task_struct(t);
1340                 n_trc_holdouts--;
1341         }
1342 }
1343
1344 /* IPI handler to check task state. */
1345 static void trc_read_check_handler(void *t_in)
1346 {
1347         int nesting;
1348         struct task_struct *t = current;
1349         struct task_struct *texp = t_in;
1350
1351         // If the task is no longer running on this CPU, leave.
1352         if (unlikely(texp != t))
1353                 goto reset_ipi; // Already on holdout list, so will check later.
1354
1355         // If the task is not in a read-side critical section, and
1356         // if this is the last reader, awaken the grace-period kthread.
1357         nesting = READ_ONCE(t->trc_reader_nesting);
1358         if (likely(!nesting)) {
1359                 rcu_trc_cmpxchg_need_qs(t, 0, TRC_NEED_QS_CHECKED);
1360                 goto reset_ipi;
1361         }
1362         // If we are racing with an rcu_read_unlock_trace(), try again later.
1363         if (unlikely(nesting < 0))
1364                 goto reset_ipi;
1365
1366         // Get here if the task is in a read-side critical section.
1367         // Set its state so that it will update state for the grace-period
1368         // kthread upon exit from that critical section.
1369         rcu_trc_cmpxchg_need_qs(t, 0, TRC_NEED_QS | TRC_NEED_QS_CHECKED);
1370
1371 reset_ipi:
1372         // Allow future IPIs to be sent on CPU and for task.
1373         // Also order this IPI handler against any later manipulations of
1374         // the intended task.
1375         smp_store_release(per_cpu_ptr(&trc_ipi_to_cpu, smp_processor_id()), false); // ^^^
1376         smp_store_release(&texp->trc_ipi_to_cpu, -1); // ^^^
1377 }
1378
1379 /* Callback function for scheduler to check locked-down task.  */
1380 static int trc_inspect_reader(struct task_struct *t, void *bhp_in)
1381 {
1382         struct list_head *bhp = bhp_in;
1383         int cpu = task_cpu(t);
1384         int nesting;
1385         bool ofl = cpu_is_offline(cpu);
1386
1387         if (task_curr(t) && !ofl) {
1388                 // If no chance of heavyweight readers, do it the hard way.
1389                 if (!IS_ENABLED(CONFIG_TASKS_TRACE_RCU_READ_MB))
1390                         return -EINVAL;
1391
1392                 // If heavyweight readers are enabled on the remote task,
1393                 // we can inspect its state despite its currently running.
1394                 // However, we cannot safely change its state.
1395                 n_heavy_reader_attempts++;
1396                 // Check for "running" idle tasks on offline CPUs.
1397                 if (!rcu_dynticks_zero_in_eqs(cpu, &t->trc_reader_nesting))
1398                         return -EINVAL; // No quiescent state, do it the hard way.
1399                 n_heavy_reader_updates++;
1400                 nesting = 0;
1401         } else {
1402                 // The task is not running, so C-language access is safe.
1403                 nesting = t->trc_reader_nesting;
1404                 WARN_ON_ONCE(ofl && task_curr(t) && !is_idle_task(t));
1405                 if (IS_ENABLED(CONFIG_TASKS_TRACE_RCU_READ_MB) && ofl)
1406                         n_heavy_reader_ofl_updates++;
1407         }
1408
1409         // If not exiting a read-side critical section, mark as checked
1410         // so that the grace-period kthread will remove it from the
1411         // holdout list.
1412         if (!nesting) {
1413                 rcu_trc_cmpxchg_need_qs(t, 0, TRC_NEED_QS_CHECKED);
1414                 return 0;  // In QS, so done.
1415         }
1416         if (nesting < 0)
1417                 return -EINVAL; // Reader transitioning, try again later.
1418
1419         // The task is in a read-side critical section, so set up its
1420         // state so that it will update state upon exit from that critical
1421         // section.
1422         if (!rcu_trc_cmpxchg_need_qs(t, 0, TRC_NEED_QS | TRC_NEED_QS_CHECKED))
1423                 trc_add_holdout(t, bhp);
1424         return 0;
1425 }
1426
1427 /* Attempt to extract the state for the specified task. */
1428 static void trc_wait_for_one_reader(struct task_struct *t,
1429                                     struct list_head *bhp)
1430 {
1431         int cpu;
1432
1433         // If a previous IPI is still in flight, let it complete.
1434         if (smp_load_acquire(&t->trc_ipi_to_cpu) != -1) // Order IPI
1435                 return;
1436
1437         // The current task had better be in a quiescent state.
1438         if (t == current) {
1439                 rcu_trc_cmpxchg_need_qs(t, 0, TRC_NEED_QS_CHECKED);
1440                 WARN_ON_ONCE(READ_ONCE(t->trc_reader_nesting));
1441                 return;
1442         }
1443
1444         // Attempt to nail down the task for inspection.
1445         get_task_struct(t);
1446         if (!task_call_func(t, trc_inspect_reader, bhp)) {
1447                 put_task_struct(t);
1448                 return;
1449         }
1450         put_task_struct(t);
1451
1452         // If this task is not yet on the holdout list, then we are in
1453         // an RCU read-side critical section.  Otherwise, the invocation of
1454         // trc_add_holdout() that added it to the list did the necessary
1455         // get_task_struct().  Either way, the task cannot be freed out
1456         // from under this code.
1457
1458         // If currently running, send an IPI, either way, add to list.
1459         trc_add_holdout(t, bhp);
1460         if (task_curr(t) &&
1461             time_after(jiffies + 1, rcu_tasks_trace.gp_start + rcu_task_ipi_delay)) {
1462                 // The task is currently running, so try IPIing it.
1463                 cpu = task_cpu(t);
1464
1465                 // If there is already an IPI outstanding, let it happen.
1466                 if (per_cpu(trc_ipi_to_cpu, cpu) || t->trc_ipi_to_cpu >= 0)
1467                         return;
1468
1469                 per_cpu(trc_ipi_to_cpu, cpu) = true;
1470                 t->trc_ipi_to_cpu = cpu;
1471                 rcu_tasks_trace.n_ipis++;
1472                 if (smp_call_function_single(cpu, trc_read_check_handler, t, 0)) {
1473                         // Just in case there is some other reason for
1474                         // failure than the target CPU being offline.
1475                         WARN_ONCE(1, "%s():  smp_call_function_single() failed for CPU: %d\n",
1476                                   __func__, cpu);
1477                         rcu_tasks_trace.n_ipis_fails++;
1478                         per_cpu(trc_ipi_to_cpu, cpu) = false;
1479                         t->trc_ipi_to_cpu = -1;
1480                 }
1481         }
1482 }
1483
1484 /*
1485  * Initialize for first-round processing for the specified task.
1486  * Return false if task is NULL or already taken care of, true otherwise.
1487  */
1488 static bool rcu_tasks_trace_pertask_prep(struct task_struct *t, bool notself)
1489 {
1490         // During early boot when there is only the one boot CPU, there
1491         // is no idle task for the other CPUs.  Also, the grace-period
1492         // kthread is always in a quiescent state.  In addition, just return
1493         // if this task is already on the list.
1494         if (unlikely(t == NULL) || (t == current && notself) || !list_empty(&t->trc_holdout_list))
1495                 return false;
1496
1497         rcu_st_need_qs(t, 0);
1498         t->trc_ipi_to_cpu = -1;
1499         return true;
1500 }
1501
1502 /* Do first-round processing for the specified task. */
1503 static void rcu_tasks_trace_pertask(struct task_struct *t, struct list_head *hop)
1504 {
1505         if (rcu_tasks_trace_pertask_prep(t, true))
1506                 trc_wait_for_one_reader(t, hop);
1507 }
1508
1509 /* Initialize for a new RCU-tasks-trace grace period. */
1510 static void rcu_tasks_trace_pregp_step(struct list_head *hop)
1511 {
1512         LIST_HEAD(blkd_tasks);
1513         int cpu;
1514         unsigned long flags;
1515         struct rcu_tasks_percpu *rtpcp;
1516         struct task_struct *t;
1517
1518         // There shouldn't be any old IPIs, but...
1519         for_each_possible_cpu(cpu)
1520                 WARN_ON_ONCE(per_cpu(trc_ipi_to_cpu, cpu));
1521
1522         // Disable CPU hotplug across the CPU scan for the benefit of
1523         // any IPIs that might be needed.  This also waits for all readers
1524         // in CPU-hotplug code paths.
1525         cpus_read_lock();
1526
1527         // These rcu_tasks_trace_pertask_prep() calls are serialized to
1528         // allow safe access to the hop list.
1529         for_each_online_cpu(cpu) {
1530                 rcu_read_lock();
1531                 t = cpu_curr_snapshot(cpu);
1532                 if (rcu_tasks_trace_pertask_prep(t, true))
1533                         trc_add_holdout(t, hop);
1534                 rcu_read_unlock();
1535                 cond_resched_tasks_rcu_qs();
1536         }
1537
1538         // Only after all running tasks have been accounted for is it
1539         // safe to take care of the tasks that have blocked within their
1540         // current RCU tasks trace read-side critical section.
1541         for_each_possible_cpu(cpu) {
1542                 rtpcp = per_cpu_ptr(rcu_tasks_trace.rtpcpu, cpu);
1543                 raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
1544                 list_splice_init(&rtpcp->rtp_blkd_tasks, &blkd_tasks);
1545                 while (!list_empty(&blkd_tasks)) {
1546                         rcu_read_lock();
1547                         t = list_first_entry(&blkd_tasks, struct task_struct, trc_blkd_node);
1548                         list_del_init(&t->trc_blkd_node);
1549                         list_add(&t->trc_blkd_node, &rtpcp->rtp_blkd_tasks);
1550                         raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
1551                         rcu_tasks_trace_pertask(t, hop);
1552                         rcu_read_unlock();
1553                         raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
1554                 }
1555                 raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
1556                 cond_resched_tasks_rcu_qs();
1557         }
1558
1559         // Re-enable CPU hotplug now that the holdout list is populated.
1560         cpus_read_unlock();
1561 }
1562
1563 /*
1564  * Do intermediate processing between task and holdout scans.
1565  */
1566 static void rcu_tasks_trace_postscan(struct list_head *hop)
1567 {
1568         // Wait for late-stage exiting tasks to finish exiting.
1569         // These might have passed the call to exit_tasks_rcu_finish().
1570         synchronize_rcu();
1571         // Any tasks that exit after this point will set
1572         // TRC_NEED_QS_CHECKED in ->trc_reader_special.b.need_qs.
1573 }
1574
1575 /* Communicate task state back to the RCU tasks trace stall warning request. */
1576 struct trc_stall_chk_rdr {
1577         int nesting;
1578         int ipi_to_cpu;
1579         u8 needqs;
1580 };
1581
1582 static int trc_check_slow_task(struct task_struct *t, void *arg)
1583 {
1584         struct trc_stall_chk_rdr *trc_rdrp = arg;
1585
1586         if (task_curr(t) && cpu_online(task_cpu(t)))
1587                 return false; // It is running, so decline to inspect it.
1588         trc_rdrp->nesting = READ_ONCE(t->trc_reader_nesting);
1589         trc_rdrp->ipi_to_cpu = READ_ONCE(t->trc_ipi_to_cpu);
1590         trc_rdrp->needqs = rcu_ld_need_qs(t);
1591         return true;
1592 }
1593
1594 /* Show the state of a task stalling the current RCU tasks trace GP. */
1595 static void show_stalled_task_trace(struct task_struct *t, bool *firstreport)
1596 {
1597         int cpu;
1598         struct trc_stall_chk_rdr trc_rdr;
1599         bool is_idle_tsk = is_idle_task(t);
1600
1601         if (*firstreport) {
1602                 pr_err("INFO: rcu_tasks_trace detected stalls on tasks:\n");
1603                 *firstreport = false;
1604         }
1605         cpu = task_cpu(t);
1606         if (!task_call_func(t, trc_check_slow_task, &trc_rdr))
1607                 pr_alert("P%d: %c%c\n",
1608                          t->pid,
1609                          ".I"[t->trc_ipi_to_cpu >= 0],
1610                          ".i"[is_idle_tsk]);
1611         else
1612                 pr_alert("P%d: %c%c%c%c nesting: %d%c%c cpu: %d%s\n",
1613                          t->pid,
1614                          ".I"[trc_rdr.ipi_to_cpu >= 0],
1615                          ".i"[is_idle_tsk],
1616                          ".N"[cpu >= 0 && tick_nohz_full_cpu(cpu)],
1617                          ".B"[!!data_race(t->trc_reader_special.b.blocked)],
1618                          trc_rdr.nesting,
1619                          " !CN"[trc_rdr.needqs & 0x3],
1620                          " ?"[trc_rdr.needqs > 0x3],
1621                          cpu, cpu_online(cpu) ? "" : "(offline)");
1622         sched_show_task(t);
1623 }
1624
1625 /* List stalled IPIs for RCU tasks trace. */
1626 static void show_stalled_ipi_trace(void)
1627 {
1628         int cpu;
1629
1630         for_each_possible_cpu(cpu)
1631                 if (per_cpu(trc_ipi_to_cpu, cpu))
1632                         pr_alert("\tIPI outstanding to CPU %d\n", cpu);
1633 }
1634
1635 /* Do one scan of the holdout list. */
1636 static void check_all_holdout_tasks_trace(struct list_head *hop,
1637                                           bool needreport, bool *firstreport)
1638 {
1639         struct task_struct *g, *t;
1640
1641         // Disable CPU hotplug across the holdout list scan for IPIs.
1642         cpus_read_lock();
1643
1644         list_for_each_entry_safe(t, g, hop, trc_holdout_list) {
1645                 // If safe and needed, try to check the current task.
1646                 if (READ_ONCE(t->trc_ipi_to_cpu) == -1 &&
1647                     !(rcu_ld_need_qs(t) & TRC_NEED_QS_CHECKED))
1648                         trc_wait_for_one_reader(t, hop);
1649
1650                 // If check succeeded, remove this task from the list.
1651                 if (smp_load_acquire(&t->trc_ipi_to_cpu) == -1 &&
1652                     rcu_ld_need_qs(t) == TRC_NEED_QS_CHECKED)
1653                         trc_del_holdout(t);
1654                 else if (needreport)
1655                         show_stalled_task_trace(t, firstreport);
1656                 cond_resched_tasks_rcu_qs();
1657         }
1658
1659         // Re-enable CPU hotplug now that the holdout list scan has completed.
1660         cpus_read_unlock();
1661
1662         if (needreport) {
1663                 if (*firstreport)
1664                         pr_err("INFO: rcu_tasks_trace detected stalls? (Late IPI?)\n");
1665                 show_stalled_ipi_trace();
1666         }
1667 }
1668
1669 static void rcu_tasks_trace_empty_fn(void *unused)
1670 {
1671 }
1672
1673 /* Wait for grace period to complete and provide ordering. */
1674 static void rcu_tasks_trace_postgp(struct rcu_tasks *rtp)
1675 {
1676         int cpu;
1677
1678         // Wait for any lingering IPI handlers to complete.  Note that
1679         // if a CPU has gone offline or transitioned to userspace in the
1680         // meantime, all IPI handlers should have been drained beforehand.
1681         // Yes, this assumes that CPUs process IPIs in order.  If that ever
1682         // changes, there will need to be a recheck and/or timed wait.
1683         for_each_online_cpu(cpu)
1684                 if (WARN_ON_ONCE(smp_load_acquire(per_cpu_ptr(&trc_ipi_to_cpu, cpu))))
1685                         smp_call_function_single(cpu, rcu_tasks_trace_empty_fn, NULL, 1);
1686
1687         smp_mb(); // Caller's code must be ordered after wakeup.
1688                   // Pairs with pretty much every ordering primitive.
1689 }
1690
1691 /* Report any needed quiescent state for this exiting task. */
1692 static void exit_tasks_rcu_finish_trace(struct task_struct *t)
1693 {
1694         union rcu_special trs = READ_ONCE(t->trc_reader_special);
1695
1696         rcu_trc_cmpxchg_need_qs(t, 0, TRC_NEED_QS_CHECKED);
1697         WARN_ON_ONCE(READ_ONCE(t->trc_reader_nesting));
1698         if (WARN_ON_ONCE(rcu_ld_need_qs(t) & TRC_NEED_QS || trs.b.blocked))
1699                 rcu_read_unlock_trace_special(t);
1700         else
1701                 WRITE_ONCE(t->trc_reader_nesting, 0);
1702 }
1703
1704 /**
1705  * call_rcu_tasks_trace() - Queue a callback trace task-based grace period
1706  * @rhp: structure to be used for queueing the RCU updates.
1707  * @func: actual callback function to be invoked after the grace period
1708  *
1709  * The callback function will be invoked some time after a trace rcu-tasks
1710  * grace period elapses, in other words after all currently executing
1711  * trace rcu-tasks read-side critical sections have completed. These
1712  * read-side critical sections are delimited by calls to rcu_read_lock_trace()
1713  * and rcu_read_unlock_trace().
1714  *
1715  * See the description of call_rcu() for more detailed information on
1716  * memory ordering guarantees.
1717  */
1718 void call_rcu_tasks_trace(struct rcu_head *rhp, rcu_callback_t func)
1719 {
1720         call_rcu_tasks_generic(rhp, func, &rcu_tasks_trace);
1721 }
1722 EXPORT_SYMBOL_GPL(call_rcu_tasks_trace);
1723
1724 /**
1725  * synchronize_rcu_tasks_trace - wait for a trace rcu-tasks grace period
1726  *
1727  * Control will return to the caller some time after a trace rcu-tasks
1728  * grace period has elapsed, in other words after all currently executing
1729  * trace rcu-tasks read-side critical sections have elapsed. These read-side
1730  * critical sections are delimited by calls to rcu_read_lock_trace()
1731  * and rcu_read_unlock_trace().
1732  *
1733  * This is a very specialized primitive, intended only for a few uses in
1734  * tracing and other situations requiring manipulation of function preambles
1735  * and profiling hooks.  The synchronize_rcu_tasks_trace() function is not
1736  * (yet) intended for heavy use from multiple CPUs.
1737  *
1738  * See the description of synchronize_rcu() for more detailed information
1739  * on memory ordering guarantees.
1740  */
1741 void synchronize_rcu_tasks_trace(void)
1742 {
1743         RCU_LOCKDEP_WARN(lock_is_held(&rcu_trace_lock_map), "Illegal synchronize_rcu_tasks_trace() in RCU Tasks Trace read-side critical section");
1744         synchronize_rcu_tasks_generic(&rcu_tasks_trace);
1745 }
1746 EXPORT_SYMBOL_GPL(synchronize_rcu_tasks_trace);
1747
1748 /**
1749  * rcu_barrier_tasks_trace - Wait for in-flight call_rcu_tasks_trace() callbacks.
1750  *
1751  * Although the current implementation is guaranteed to wait, it is not
1752  * obligated to, for example, if there are no pending callbacks.
1753  */
1754 void rcu_barrier_tasks_trace(void)
1755 {
1756         rcu_barrier_tasks_generic(&rcu_tasks_trace);
1757 }
1758 EXPORT_SYMBOL_GPL(rcu_barrier_tasks_trace);
1759
1760 static int __init rcu_spawn_tasks_trace_kthread(void)
1761 {
1762         cblist_init_generic(&rcu_tasks_trace);
1763         if (IS_ENABLED(CONFIG_TASKS_TRACE_RCU_READ_MB)) {
1764                 rcu_tasks_trace.gp_sleep = HZ / 10;
1765                 rcu_tasks_trace.init_fract = HZ / 10;
1766         } else {
1767                 rcu_tasks_trace.gp_sleep = HZ / 200;
1768                 if (rcu_tasks_trace.gp_sleep <= 0)
1769                         rcu_tasks_trace.gp_sleep = 1;
1770                 rcu_tasks_trace.init_fract = HZ / 200;
1771                 if (rcu_tasks_trace.init_fract <= 0)
1772                         rcu_tasks_trace.init_fract = 1;
1773         }
1774         rcu_tasks_trace.pregp_func = rcu_tasks_trace_pregp_step;
1775         rcu_tasks_trace.postscan_func = rcu_tasks_trace_postscan;
1776         rcu_tasks_trace.holdouts_func = check_all_holdout_tasks_trace;
1777         rcu_tasks_trace.postgp_func = rcu_tasks_trace_postgp;
1778         rcu_spawn_tasks_kthread_generic(&rcu_tasks_trace);
1779         return 0;
1780 }
1781
1782 #if !defined(CONFIG_TINY_RCU)
1783 void show_rcu_tasks_trace_gp_kthread(void)
1784 {
1785         char buf[64];
1786
1787         sprintf(buf, "N%lu h:%lu/%lu/%lu",
1788                 data_race(n_trc_holdouts),
1789                 data_race(n_heavy_reader_ofl_updates),
1790                 data_race(n_heavy_reader_updates),
1791                 data_race(n_heavy_reader_attempts));
1792         show_rcu_tasks_generic_gp_kthread(&rcu_tasks_trace, buf);
1793 }
1794 EXPORT_SYMBOL_GPL(show_rcu_tasks_trace_gp_kthread);
1795 #endif // !defined(CONFIG_TINY_RCU)
1796
1797 #else /* #ifdef CONFIG_TASKS_TRACE_RCU */
1798 static void exit_tasks_rcu_finish_trace(struct task_struct *t) { }
1799 #endif /* #else #ifdef CONFIG_TASKS_TRACE_RCU */
1800
1801 #ifndef CONFIG_TINY_RCU
1802 void show_rcu_tasks_gp_kthreads(void)
1803 {
1804         show_rcu_tasks_classic_gp_kthread();
1805         show_rcu_tasks_rude_gp_kthread();
1806         show_rcu_tasks_trace_gp_kthread();
1807 }
1808 #endif /* #ifndef CONFIG_TINY_RCU */
1809
1810 #ifdef CONFIG_PROVE_RCU
1811 struct rcu_tasks_test_desc {
1812         struct rcu_head rh;
1813         const char *name;
1814         bool notrun;
1815         unsigned long runstart;
1816 };
1817
1818 static struct rcu_tasks_test_desc tests[] = {
1819         {
1820                 .name = "call_rcu_tasks()",
1821                 /* If not defined, the test is skipped. */
1822                 .notrun = IS_ENABLED(CONFIG_TASKS_RCU),
1823         },
1824         {
1825                 .name = "call_rcu_tasks_rude()",
1826                 /* If not defined, the test is skipped. */
1827                 .notrun = IS_ENABLED(CONFIG_TASKS_RUDE_RCU),
1828         },
1829         {
1830                 .name = "call_rcu_tasks_trace()",
1831                 /* If not defined, the test is skipped. */
1832                 .notrun = IS_ENABLED(CONFIG_TASKS_TRACE_RCU)
1833         }
1834 };
1835
1836 static void test_rcu_tasks_callback(struct rcu_head *rhp)
1837 {
1838         struct rcu_tasks_test_desc *rttd =
1839                 container_of(rhp, struct rcu_tasks_test_desc, rh);
1840
1841         pr_info("Callback from %s invoked.\n", rttd->name);
1842
1843         rttd->notrun = false;
1844 }
1845
1846 static void rcu_tasks_initiate_self_tests(void)
1847 {
1848         unsigned long j = jiffies;
1849
1850         pr_info("Running RCU-tasks wait API self tests\n");
1851 #ifdef CONFIG_TASKS_RCU
1852         tests[0].runstart = j;
1853         synchronize_rcu_tasks();
1854         call_rcu_tasks(&tests[0].rh, test_rcu_tasks_callback);
1855 #endif
1856
1857 #ifdef CONFIG_TASKS_RUDE_RCU
1858         tests[1].runstart = j;
1859         synchronize_rcu_tasks_rude();
1860         call_rcu_tasks_rude(&tests[1].rh, test_rcu_tasks_callback);
1861 #endif
1862
1863 #ifdef CONFIG_TASKS_TRACE_RCU
1864         tests[2].runstart = j;
1865         synchronize_rcu_tasks_trace();
1866         call_rcu_tasks_trace(&tests[2].rh, test_rcu_tasks_callback);
1867 #endif
1868 }
1869
1870 /*
1871  * Return:  0 - test passed
1872  *          1 - test failed, but have not timed out yet
1873  *         -1 - test failed and timed out
1874  */
1875 static int rcu_tasks_verify_self_tests(void)
1876 {
1877         int ret = 0;
1878         int i;
1879         unsigned long bst = rcu_task_stall_timeout;
1880
1881         if (bst <= 0 || bst > RCU_TASK_BOOT_STALL_TIMEOUT)
1882                 bst = RCU_TASK_BOOT_STALL_TIMEOUT;
1883         for (i = 0; i < ARRAY_SIZE(tests); i++) {
1884                 while (tests[i].notrun) {               // still hanging.
1885                         if (time_after(jiffies, tests[i].runstart + bst)) {
1886                                 pr_err("%s has failed boot-time tests.\n", tests[i].name);
1887                                 ret = -1;
1888                                 break;
1889                         }
1890                         ret = 1;
1891                         break;
1892                 }
1893         }
1894         WARN_ON(ret < 0);
1895
1896         return ret;
1897 }
1898
1899 /*
1900  * Repeat the rcu_tasks_verify_self_tests() call once every second until the
1901  * test passes or has timed out.
1902  */
1903 static struct delayed_work rcu_tasks_verify_work;
1904 static void rcu_tasks_verify_work_fn(struct work_struct *work __maybe_unused)
1905 {
1906         int ret = rcu_tasks_verify_self_tests();
1907
1908         if (ret <= 0)
1909                 return;
1910
1911         /* Test fails but not timed out yet, reschedule another check */
1912         schedule_delayed_work(&rcu_tasks_verify_work, HZ);
1913 }
1914
1915 static int rcu_tasks_verify_schedule_work(void)
1916 {
1917         INIT_DELAYED_WORK(&rcu_tasks_verify_work, rcu_tasks_verify_work_fn);
1918         rcu_tasks_verify_work_fn(NULL);
1919         return 0;
1920 }
1921 late_initcall(rcu_tasks_verify_schedule_work);
1922 #else /* #ifdef CONFIG_PROVE_RCU */
1923 static void rcu_tasks_initiate_self_tests(void) { }
1924 #endif /* #else #ifdef CONFIG_PROVE_RCU */
1925
1926 void __init rcu_init_tasks_generic(void)
1927 {
1928 #ifdef CONFIG_TASKS_RCU
1929         rcu_spawn_tasks_kthread();
1930 #endif
1931
1932 #ifdef CONFIG_TASKS_RUDE_RCU
1933         rcu_spawn_tasks_rude_kthread();
1934 #endif
1935
1936 #ifdef CONFIG_TASKS_TRACE_RCU
1937         rcu_spawn_tasks_trace_kthread();
1938 #endif
1939
1940         // Run the self-tests.
1941         rcu_tasks_initiate_self_tests();
1942 }
1943
1944 #else /* #ifdef CONFIG_TASKS_RCU_GENERIC */
1945 static inline void rcu_tasks_bootup_oddness(void) {}
1946 #endif /* #else #ifdef CONFIG_TASKS_RCU_GENERIC */