rcu-tasks: Introduce ->percpu_enqueue_shift for dynamic queue selection
[linux-2.6-block.git] / kernel / rcu / tasks.h
CommitLineData
eacd6f04
PM
1/* SPDX-License-Identifier: GPL-2.0+ */
2/*
3 * Task-based RCU implementations.
4 *
5 * Copyright (C) 2020 Paul E. McKenney
6 */
7
8fd8ca38 8#ifdef CONFIG_TASKS_RCU_GENERIC
5873b8a9
PM
9
10////////////////////////////////////////////////////////////////////////
11//
12// Generic data structures.
13
14struct rcu_tasks;
15typedef void (*rcu_tasks_gp_func_t)(struct rcu_tasks *rtp);
e4fe5dd6
PM
16typedef void (*pregp_func_t)(void);
17typedef void (*pertask_func_t)(struct task_struct *t, struct list_head *hop);
9796e1ae 18typedef void (*postscan_func_t)(struct list_head *hop);
e4fe5dd6 19typedef void (*holdouts_func_t)(struct list_head *hop, bool ndrpt, bool *frptp);
af051ca4 20typedef void (*postgp_func_t)(struct rcu_tasks *rtp);
eacd6f04 21
07e10515 22/**
cafafd67 23 * struct rcu_tasks_percpu - Per-CPU component of definition for a Tasks-RCU-like mechanism.
07e10515
PM
24 * @cbs_head: Head of callback list.
25 * @cbs_tail: Tail pointer for callback list.
cafafd67
PM
26 * @cbs_pcpu_lock: Lock protecting per-CPU callback list.
27 */
28struct rcu_tasks_percpu {
29 struct rcu_head *cbs_head;
30 struct rcu_head **cbs_tail;
31 raw_spinlock_t cbs_pcpu_lock;
32};
33
34/**
35 * struct rcu_tasks - Definition for a Tasks-RCU-like mechanism.
a616aec9 36 * @cbs_wq: Wait queue allowing new callback to get kthread's attention.
cafafd67 37 * @cbs_gbl_lock: Lock protecting callback list.
07e10515 38 * @kthread_ptr: This flavor's grace-period/callback-invocation kthread.
5873b8a9 39 * @gp_func: This flavor's grace-period-wait function.
af051ca4 40 * @gp_state: Grace period's most recent state transition (debugging).
4fe192df 41 * @gp_sleep: Per-grace-period sleep to prevent CPU-bound looping.
2393a613 42 * @init_fract: Initial backoff sleep interval.
af051ca4
PM
43 * @gp_jiffies: Time of last @gp_state transition.
44 * @gp_start: Most recent grace-period start in jiffies.
238dbce3
PM
45 * @n_gps: Number of grace periods completed since boot.
46 * @n_ipis: Number of IPIs sent to encourage grace periods to end.
7e0669c3 47 * @n_ipis_fails: Number of IPI-send failures.
e4fe5dd6
PM
48 * @pregp_func: This flavor's pre-grace-period function (optional).
49 * @pertask_func: This flavor's per-task scan function (optional).
50 * @postscan_func: This flavor's post-task scan function (optional).
85b86994 51 * @holdouts_func: This flavor's holdout-list scan function (optional).
e4fe5dd6 52 * @postgp_func: This flavor's post-grace-period function (optional).
5873b8a9 53 * @call_func: This flavor's call_rcu()-equivalent function.
cafafd67 54 * @rtpcpu: This flavor's rcu_tasks_percpu structure.
7a30871b 55 * @percpu_enqueue_shift: Shift down CPU ID this much when enqueuing callbacks.
c97d12a6
PM
56 * @name: This flavor's textual name.
57 * @kname: This flavor's kthread name.
07e10515
PM
58 */
59struct rcu_tasks {
07e10515 60 struct wait_queue_head cbs_wq;
cafafd67 61 raw_spinlock_t cbs_gbl_lock;
af051ca4 62 int gp_state;
4fe192df 63 int gp_sleep;
2393a613 64 int init_fract;
af051ca4 65 unsigned long gp_jiffies;
88092d0c 66 unsigned long gp_start;
238dbce3
PM
67 unsigned long n_gps;
68 unsigned long n_ipis;
7e0669c3 69 unsigned long n_ipis_fails;
07e10515 70 struct task_struct *kthread_ptr;
5873b8a9 71 rcu_tasks_gp_func_t gp_func;
e4fe5dd6
PM
72 pregp_func_t pregp_func;
73 pertask_func_t pertask_func;
74 postscan_func_t postscan_func;
75 holdouts_func_t holdouts_func;
76 postgp_func_t postgp_func;
5873b8a9 77 call_rcu_func_t call_func;
cafafd67 78 struct rcu_tasks_percpu __percpu *rtpcpu;
7a30871b 79 int percpu_enqueue_shift;
c97d12a6
PM
80 char *name;
81 char *kname;
07e10515
PM
82};
83
cafafd67
PM
84#define DEFINE_RCU_TASKS(rt_name, gp, call, n) \
85static DEFINE_PER_CPU(struct rcu_tasks_percpu, rt_name ## __percpu) = { \
86 .cbs_pcpu_lock = __RAW_SPIN_LOCK_UNLOCKED(rt_name ## __percpu.cbs_pcpu_lock), \
87}; \
88static struct rcu_tasks rt_name = \
89{ \
90 .cbs_wq = __WAIT_QUEUE_HEAD_INITIALIZER(rt_name.cbs_wq), \
91 .cbs_gbl_lock = __RAW_SPIN_LOCK_UNLOCKED(rt_name.cbs_gbl_lock), \
92 .gp_func = gp, \
93 .call_func = call, \
94 .rtpcpu = &rt_name ## __percpu, \
95 .name = n, \
7a30871b 96 .percpu_enqueue_shift = ilog2(CONFIG_NR_CPUS), \
cafafd67 97 .kname = #rt_name, \
07e10515
PM
98}
99
eacd6f04
PM
100/* Track exiting tasks in order to allow them to be waited for. */
101DEFINE_STATIC_SRCU(tasks_rcu_exit_srcu);
102
b0afa0f0 103/* Avoid IPIing CPUs early in the grace period. */
574de876 104#define RCU_TASK_IPI_DELAY (IS_ENABLED(CONFIG_TASKS_TRACE_RCU_READ_MB) ? HZ / 2 : 0)
b0afa0f0
PM
105static int rcu_task_ipi_delay __read_mostly = RCU_TASK_IPI_DELAY;
106module_param(rcu_task_ipi_delay, int, 0644);
107
eacd6f04
PM
108/* Control stall timeouts. Disable with <= 0, otherwise jiffies till stall. */
109#define RCU_TASK_STALL_TIMEOUT (HZ * 60 * 10)
110static int rcu_task_stall_timeout __read_mostly = RCU_TASK_STALL_TIMEOUT;
111module_param(rcu_task_stall_timeout, int, 0644);
112
af051ca4
PM
113/* RCU tasks grace-period state for debugging. */
114#define RTGS_INIT 0
115#define RTGS_WAIT_WAIT_CBS 1
116#define RTGS_WAIT_GP 2
117#define RTGS_PRE_WAIT_GP 3
118#define RTGS_SCAN_TASKLIST 4
119#define RTGS_POST_SCAN_TASKLIST 5
120#define RTGS_WAIT_SCAN_HOLDOUTS 6
121#define RTGS_SCAN_HOLDOUTS 7
122#define RTGS_POST_GP 8
123#define RTGS_WAIT_READERS 9
124#define RTGS_INVOKE_CBS 10
125#define RTGS_WAIT_CBS 11
8344496e 126#ifndef CONFIG_TINY_RCU
af051ca4
PM
127static const char * const rcu_tasks_gp_state_names[] = {
128 "RTGS_INIT",
129 "RTGS_WAIT_WAIT_CBS",
130 "RTGS_WAIT_GP",
131 "RTGS_PRE_WAIT_GP",
132 "RTGS_SCAN_TASKLIST",
133 "RTGS_POST_SCAN_TASKLIST",
134 "RTGS_WAIT_SCAN_HOLDOUTS",
135 "RTGS_SCAN_HOLDOUTS",
136 "RTGS_POST_GP",
137 "RTGS_WAIT_READERS",
138 "RTGS_INVOKE_CBS",
139 "RTGS_WAIT_CBS",
140};
8344496e 141#endif /* #ifndef CONFIG_TINY_RCU */
af051ca4 142
5873b8a9
PM
143////////////////////////////////////////////////////////////////////////
144//
145// Generic code.
146
af051ca4
PM
147/* Record grace-period phase and time. */
148static void set_tasks_gp_state(struct rcu_tasks *rtp, int newstate)
149{
150 rtp->gp_state = newstate;
151 rtp->gp_jiffies = jiffies;
152}
153
8344496e 154#ifndef CONFIG_TINY_RCU
af051ca4
PM
155/* Return state name. */
156static const char *tasks_gp_state_getname(struct rcu_tasks *rtp)
157{
158 int i = data_race(rtp->gp_state); // Let KCSAN detect update races
159 int j = READ_ONCE(i); // Prevent the compiler from reading twice
160
161 if (j >= ARRAY_SIZE(rcu_tasks_gp_state_names))
162 return "???";
163 return rcu_tasks_gp_state_names[j];
164}
8344496e 165#endif /* #ifndef CONFIG_TINY_RCU */
af051ca4 166
cafafd67
PM
167// Initialize per-CPU callback lists for the specified flavor of
168// Tasks RCU.
169static void cblist_init_generic(struct rcu_tasks *rtp)
170{
171 int cpu;
172 unsigned long flags;
173
174 raw_spin_lock_irqsave(&rtp->cbs_gbl_lock, flags);
7a30871b 175 rtp->percpu_enqueue_shift = ilog2(nr_cpu_ids);
cafafd67
PM
176 for_each_possible_cpu(cpu) {
177 struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
178
179 WARN_ON_ONCE(!rtpcp);
180 if (cpu)
181 raw_spin_lock_init(&rtpcp->cbs_pcpu_lock);
182 raw_spin_lock(&rtpcp->cbs_pcpu_lock); // irqs already disabled.
183 if (!WARN_ON_ONCE(rtpcp->cbs_tail))
184 rtpcp->cbs_tail = &rtpcp->cbs_head;
185 raw_spin_unlock(&rtpcp->cbs_pcpu_lock); // irqs remain disabled.
186 }
187 raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags);
188
189}
190
5873b8a9
PM
191// Enqueue a callback for the specified flavor of Tasks RCU.
192static void call_rcu_tasks_generic(struct rcu_head *rhp, rcu_callback_t func,
193 struct rcu_tasks *rtp)
eacd6f04
PM
194{
195 unsigned long flags;
196 bool needwake;
cafafd67 197 struct rcu_tasks_percpu *rtpcp;
eacd6f04
PM
198
199 rhp->next = NULL;
200 rhp->func = func;
cafafd67 201 local_irq_save(flags);
7a30871b
PM
202 rtpcp = per_cpu_ptr(rtp->rtpcpu,
203 smp_processor_id() >> READ_ONCE(rtp->percpu_enqueue_shift));
cafafd67
PM
204 raw_spin_lock(&rtpcp->cbs_pcpu_lock);
205 if (!rtpcp->cbs_tail) {
206 raw_spin_unlock(&rtpcp->cbs_pcpu_lock); // irqs remain disabled.
207 cblist_init_generic(rtp);
208 raw_spin_lock(&rtpcp->cbs_pcpu_lock); // irqs already disabled.
209 }
210 needwake = !rtpcp->cbs_head;
211 WRITE_ONCE(*rtpcp->cbs_tail, rhp);
212 rtpcp->cbs_tail = &rhp->next;
213 raw_spin_unlock_irqrestore(&rtpcp->cbs_pcpu_lock, flags);
eacd6f04 214 /* We can't create the thread unless interrupts are enabled. */
07e10515
PM
215 if (needwake && READ_ONCE(rtp->kthread_ptr))
216 wake_up(&rtp->cbs_wq);
eacd6f04 217}
eacd6f04 218
5873b8a9
PM
219// Wait for a grace period for the specified flavor of Tasks RCU.
220static void synchronize_rcu_tasks_generic(struct rcu_tasks *rtp)
eacd6f04
PM
221{
222 /* Complain if the scheduler has not started. */
223 RCU_LOCKDEP_WARN(rcu_scheduler_active == RCU_SCHEDULER_INACTIVE,
224 "synchronize_rcu_tasks called too soon");
225
226 /* Wait for the grace period. */
5873b8a9 227 wait_rcu_gp(rtp->call_func);
eacd6f04
PM
228}
229
230/* RCU-tasks kthread that detects grace periods and invokes callbacks. */
231static int __noreturn rcu_tasks_kthread(void *arg)
232{
233 unsigned long flags;
eacd6f04
PM
234 struct rcu_head *list;
235 struct rcu_head *next;
07e10515 236 struct rcu_tasks *rtp = arg;
eacd6f04
PM
237
238 /* Run on housekeeping CPUs by default. Sysadm can move if desired. */
239 housekeeping_affine(current, HK_FLAG_RCU);
07e10515 240 WRITE_ONCE(rtp->kthread_ptr, current); // Let GPs start!
eacd6f04
PM
241
242 /*
243 * Each pass through the following loop makes one check for
244 * newly arrived callbacks, and, if there are some, waits for
245 * one RCU-tasks grace period and then invokes the callbacks.
246 * This loop is terminated by the system going down. ;-)
247 */
248 for (;;) {
cafafd67
PM
249 struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, 0); // for_each...
250
0db7c32a 251 set_tasks_gp_state(rtp, RTGS_WAIT_CBS);
eacd6f04
PM
252
253 /* Pick up any new callbacks. */
cafafd67 254 raw_spin_lock_irqsave(&rtpcp->cbs_pcpu_lock, flags);
43766c3e 255 smp_mb__after_spinlock(); // Order updates vs. GP.
cafafd67
PM
256 list = rtpcp->cbs_head;
257 rtpcp->cbs_head = NULL;
258 rtpcp->cbs_tail = &rtpcp->cbs_head;
259 raw_spin_unlock_irqrestore(&rtpcp->cbs_pcpu_lock, flags);
eacd6f04
PM
260
261 /* If there were none, wait a bit and start over. */
262 if (!list) {
07e10515 263 wait_event_interruptible(rtp->cbs_wq,
cafafd67
PM
264 READ_ONCE(rtpcp->cbs_head));
265 if (!rtpcp->cbs_head) {
eacd6f04 266 WARN_ON(signal_pending(current));
af051ca4 267 set_tasks_gp_state(rtp, RTGS_WAIT_WAIT_CBS);
ea6eed9f 268 schedule_timeout_idle(HZ/10);
eacd6f04
PM
269 }
270 continue;
271 }
272
5873b8a9 273 // Wait for one grace period.
af051ca4 274 set_tasks_gp_state(rtp, RTGS_WAIT_GP);
88092d0c 275 rtp->gp_start = jiffies;
5873b8a9 276 rtp->gp_func(rtp);
238dbce3 277 rtp->n_gps++;
eacd6f04
PM
278
279 /* Invoke the callbacks. */
af051ca4 280 set_tasks_gp_state(rtp, RTGS_INVOKE_CBS);
eacd6f04
PM
281 while (list) {
282 next = list->next;
283 local_bh_disable();
284 list->func(list);
285 local_bh_enable();
286 list = next;
287 cond_resched();
288 }
289 /* Paranoid sleep to keep this from entering a tight loop */
4fe192df 290 schedule_timeout_idle(rtp->gp_sleep);
eacd6f04
PM
291 }
292}
293
1b04fa99 294/* Spawn RCU-tasks grace-period kthread. */
5873b8a9 295static void __init rcu_spawn_tasks_kthread_generic(struct rcu_tasks *rtp)
eacd6f04
PM
296{
297 struct task_struct *t;
298
c97d12a6
PM
299 t = kthread_run(rcu_tasks_kthread, rtp, "%s_kthread", rtp->kname);
300 if (WARN_ONCE(IS_ERR(t), "%s: Could not start %s grace-period kthread, OOM is now expected behavior\n", __func__, rtp->name))
5873b8a9 301 return;
eacd6f04 302 smp_mb(); /* Ensure others see full kthread. */
eacd6f04 303}
eacd6f04 304
eacd6f04
PM
305#ifndef CONFIG_TINY_RCU
306
307/*
308 * Print any non-default Tasks RCU settings.
309 */
310static void __init rcu_tasks_bootup_oddness(void)
311{
d5f177d3 312#if defined(CONFIG_TASKS_RCU) || defined(CONFIG_TASKS_TRACE_RCU)
eacd6f04
PM
313 if (rcu_task_stall_timeout != RCU_TASK_STALL_TIMEOUT)
314 pr_info("\tTasks-RCU CPU stall warnings timeout set to %d (rcu_task_stall_timeout).\n", rcu_task_stall_timeout);
d5f177d3
PM
315#endif /* #ifdef CONFIG_TASKS_RCU */
316#ifdef CONFIG_TASKS_RCU
317 pr_info("\tTrampoline variant of Tasks RCU enabled.\n");
eacd6f04 318#endif /* #ifdef CONFIG_TASKS_RCU */
c84aad76
PM
319#ifdef CONFIG_TASKS_RUDE_RCU
320 pr_info("\tRude variant of Tasks RCU enabled.\n");
321#endif /* #ifdef CONFIG_TASKS_RUDE_RCU */
d5f177d3
PM
322#ifdef CONFIG_TASKS_TRACE_RCU
323 pr_info("\tTracing variant of Tasks RCU enabled.\n");
324#endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
eacd6f04
PM
325}
326
327#endif /* #ifndef CONFIG_TINY_RCU */
5873b8a9 328
8344496e 329#ifndef CONFIG_TINY_RCU
e21408ce
PM
330/* Dump out rcutorture-relevant state common to all RCU-tasks flavors. */
331static void show_rcu_tasks_generic_gp_kthread(struct rcu_tasks *rtp, char *s)
332{
cafafd67 333 struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, 0); // for_each...
7e0669c3 334 pr_info("%s: %s(%d) since %lu g:%lu i:%lu/%lu %c%c %s\n",
e21408ce 335 rtp->kname,
7e0669c3 336 tasks_gp_state_getname(rtp), data_race(rtp->gp_state),
af051ca4 337 jiffies - data_race(rtp->gp_jiffies),
7e0669c3
PM
338 data_race(rtp->n_gps),
339 data_race(rtp->n_ipis_fails), data_race(rtp->n_ipis),
e21408ce 340 ".k"[!!data_race(rtp->kthread_ptr)],
cafafd67 341 ".C"[!!data_race(rtpcp->cbs_head)],
e21408ce
PM
342 s);
343}
27c0f144 344#endif // #ifndef CONFIG_TINY_RCU
e21408ce 345
25246fc8
PM
346static void exit_tasks_rcu_finish_trace(struct task_struct *t);
347
348#if defined(CONFIG_TASKS_RCU) || defined(CONFIG_TASKS_TRACE_RCU)
5873b8a9 349
d01aa263
PM
350////////////////////////////////////////////////////////////////////////
351//
352// Shared code between task-list-scanning variants of Tasks RCU.
353
354/* Wait for one RCU-tasks grace period. */
355static void rcu_tasks_wait_gp(struct rcu_tasks *rtp)
356{
357 struct task_struct *g, *t;
358 unsigned long lastreport;
359 LIST_HEAD(holdouts);
360 int fract;
361
af051ca4 362 set_tasks_gp_state(rtp, RTGS_PRE_WAIT_GP);
d01aa263
PM
363 rtp->pregp_func();
364
365 /*
366 * There were callbacks, so we need to wait for an RCU-tasks
367 * grace period. Start off by scanning the task list for tasks
368 * that are not already voluntarily blocked. Mark these tasks
369 * and make a list of them in holdouts.
370 */
af051ca4 371 set_tasks_gp_state(rtp, RTGS_SCAN_TASKLIST);
d01aa263
PM
372 rcu_read_lock();
373 for_each_process_thread(g, t)
374 rtp->pertask_func(t, &holdouts);
375 rcu_read_unlock();
376
af051ca4 377 set_tasks_gp_state(rtp, RTGS_POST_SCAN_TASKLIST);
9796e1ae 378 rtp->postscan_func(&holdouts);
d01aa263
PM
379
380 /*
381 * Each pass through the following loop scans the list of holdout
382 * tasks, removing any that are no longer holdouts. When the list
383 * is empty, we are done.
384 */
385 lastreport = jiffies;
386
2393a613
PM
387 // Start off with initial wait and slowly back off to 1 HZ wait.
388 fract = rtp->init_fract;
d01aa263 389
77dc1741 390 while (!list_empty(&holdouts)) {
d01aa263
PM
391 bool firstreport;
392 bool needreport;
393 int rtst;
394
d01aa263 395 /* Slowly back off waiting for holdouts */
af051ca4 396 set_tasks_gp_state(rtp, RTGS_WAIT_SCAN_HOLDOUTS);
75dc2da5 397 schedule_timeout_idle(fract);
d01aa263 398
75dc2da5
PM
399 if (fract < HZ)
400 fract++;
d01aa263
PM
401
402 rtst = READ_ONCE(rcu_task_stall_timeout);
403 needreport = rtst > 0 && time_after(jiffies, lastreport + rtst);
404 if (needreport)
405 lastreport = jiffies;
406 firstreport = true;
407 WARN_ON(signal_pending(current));
af051ca4 408 set_tasks_gp_state(rtp, RTGS_SCAN_HOLDOUTS);
d01aa263
PM
409 rtp->holdouts_func(&holdouts, needreport, &firstreport);
410 }
411
af051ca4
PM
412 set_tasks_gp_state(rtp, RTGS_POST_GP);
413 rtp->postgp_func(rtp);
d01aa263
PM
414}
415
25246fc8
PM
416#endif /* #if defined(CONFIG_TASKS_RCU) || defined(CONFIG_TASKS_TRACE_RCU) */
417
418#ifdef CONFIG_TASKS_RCU
419
5873b8a9
PM
420////////////////////////////////////////////////////////////////////////
421//
422// Simple variant of RCU whose quiescent states are voluntary context
8af9e2c7 423// switch, cond_resched_tasks_rcu_qs(), user-space execution, and idle.
5873b8a9
PM
424// As such, grace periods can take one good long time. There are no
425// read-side primitives similar to rcu_read_lock() and rcu_read_unlock()
426// because this implementation is intended to get the system into a safe
427// state for some of the manipulations involved in tracing and the like.
428// Finally, this implementation does not support high call_rcu_tasks()
429// rates from multiple CPUs. If this is required, per-CPU callback lists
430// will be needed.
06a3ec92
PM
431//
432// The implementation uses rcu_tasks_wait_gp(), which relies on function
433// pointers in the rcu_tasks structure. The rcu_spawn_tasks_kthread()
434// function sets these function pointers up so that rcu_tasks_wait_gp()
435// invokes these functions in this order:
436//
437// rcu_tasks_pregp_step():
438// Invokes synchronize_rcu() in order to wait for all in-flight
439// t->on_rq and t->nvcsw transitions to complete. This works because
440// all such transitions are carried out with interrupts disabled.
441// rcu_tasks_pertask(), invoked on every non-idle task:
442// For every runnable non-idle task other than the current one, use
443// get_task_struct() to pin down that task, snapshot that task's
444// number of voluntary context switches, and add that task to the
445// holdout list.
446// rcu_tasks_postscan():
447// Invoke synchronize_srcu() to ensure that all tasks that were
448// in the process of exiting (and which thus might not know to
449// synchronize with this RCU Tasks grace period) have completed
450// exiting.
451// check_all_holdout_tasks(), repeatedly until holdout list is empty:
452// Scans the holdout list, attempting to identify a quiescent state
453// for each task on the list. If there is a quiescent state, the
454// corresponding task is removed from the holdout list.
455// rcu_tasks_postgp():
456// Invokes synchronize_rcu() in order to ensure that all prior
457// t->on_rq and t->nvcsw transitions are seen by all CPUs and tasks
458// to have happened before the end of this RCU Tasks grace period.
459// Again, this works because all such transitions are carried out
460// with interrupts disabled.
461//
462// For each exiting task, the exit_tasks_rcu_start() and
463// exit_tasks_rcu_finish() functions begin and end, respectively, the SRCU
464// read-side critical sections waited for by rcu_tasks_postscan().
465//
466// Pre-grace-period update-side code is ordered before the grace via the
467// ->cbs_lock and the smp_mb__after_spinlock(). Pre-grace-period read-side
468// code is ordered before the grace period via synchronize_rcu() call
469// in rcu_tasks_pregp_step() and by the scheduler's locks and interrupt
470// disabling.
5873b8a9 471
e4fe5dd6
PM
472/* Pre-grace-period preparation. */
473static void rcu_tasks_pregp_step(void)
474{
475 /*
476 * Wait for all pre-existing t->on_rq and t->nvcsw transitions
477 * to complete. Invoking synchronize_rcu() suffices because all
478 * these transitions occur with interrupts disabled. Without this
479 * synchronize_rcu(), a read-side critical section that started
480 * before the grace period might be incorrectly seen as having
481 * started after the grace period.
482 *
483 * This synchronize_rcu() also dispenses with the need for a
484 * memory barrier on the first store to t->rcu_tasks_holdout,
485 * as it forces the store to happen after the beginning of the
486 * grace period.
487 */
488 synchronize_rcu();
489}
490
491/* Per-task initial processing. */
492static void rcu_tasks_pertask(struct task_struct *t, struct list_head *hop)
493{
494 if (t != current && READ_ONCE(t->on_rq) && !is_idle_task(t)) {
495 get_task_struct(t);
496 t->rcu_tasks_nvcsw = READ_ONCE(t->nvcsw);
497 WRITE_ONCE(t->rcu_tasks_holdout, true);
498 list_add(&t->rcu_tasks_holdout_list, hop);
499 }
500}
501
502/* Processing between scanning taskslist and draining the holdout list. */
04a3c5aa 503static void rcu_tasks_postscan(struct list_head *hop)
e4fe5dd6
PM
504{
505 /*
506 * Wait for tasks that are in the process of exiting. This
507 * does only part of the job, ensuring that all tasks that were
508 * previously exiting reach the point where they have disabled
509 * preemption, allowing the later synchronize_rcu() to finish
510 * the job.
511 */
512 synchronize_srcu(&tasks_rcu_exit_srcu);
513}
514
5873b8a9
PM
515/* See if tasks are still holding out, complain if so. */
516static void check_holdout_task(struct task_struct *t,
517 bool needreport, bool *firstreport)
518{
519 int cpu;
520
521 if (!READ_ONCE(t->rcu_tasks_holdout) ||
522 t->rcu_tasks_nvcsw != READ_ONCE(t->nvcsw) ||
523 !READ_ONCE(t->on_rq) ||
524 (IS_ENABLED(CONFIG_NO_HZ_FULL) &&
525 !is_idle_task(t) && t->rcu_tasks_idle_cpu >= 0)) {
526 WRITE_ONCE(t->rcu_tasks_holdout, false);
527 list_del_init(&t->rcu_tasks_holdout_list);
528 put_task_struct(t);
529 return;
530 }
531 rcu_request_urgent_qs_task(t);
532 if (!needreport)
533 return;
534 if (*firstreport) {
535 pr_err("INFO: rcu_tasks detected stalls on tasks:\n");
536 *firstreport = false;
537 }
538 cpu = task_cpu(t);
539 pr_alert("%p: %c%c nvcsw: %lu/%lu holdout: %d idle_cpu: %d/%d\n",
540 t, ".I"[is_idle_task(t)],
541 "N."[cpu < 0 || !tick_nohz_full_cpu(cpu)],
542 t->rcu_tasks_nvcsw, t->nvcsw, t->rcu_tasks_holdout,
543 t->rcu_tasks_idle_cpu, cpu);
544 sched_show_task(t);
545}
546
e4fe5dd6
PM
547/* Scan the holdout lists for tasks no longer holding out. */
548static void check_all_holdout_tasks(struct list_head *hop,
549 bool needreport, bool *firstreport)
550{
551 struct task_struct *t, *t1;
552
553 list_for_each_entry_safe(t, t1, hop, rcu_tasks_holdout_list) {
554 check_holdout_task(t, needreport, firstreport);
555 cond_resched();
556 }
557}
558
559/* Finish off the Tasks-RCU grace period. */
af051ca4 560static void rcu_tasks_postgp(struct rcu_tasks *rtp)
e4fe5dd6
PM
561{
562 /*
563 * Because ->on_rq and ->nvcsw are not guaranteed to have a full
564 * memory barriers prior to them in the schedule() path, memory
565 * reordering on other CPUs could cause their RCU-tasks read-side
566 * critical sections to extend past the end of the grace period.
567 * However, because these ->nvcsw updates are carried out with
568 * interrupts disabled, we can use synchronize_rcu() to force the
569 * needed ordering on all such CPUs.
570 *
571 * This synchronize_rcu() also confines all ->rcu_tasks_holdout
572 * accesses to be within the grace period, avoiding the need for
573 * memory barriers for ->rcu_tasks_holdout accesses.
574 *
575 * In addition, this synchronize_rcu() waits for exiting tasks
576 * to complete their final preempt_disable() region of execution,
577 * cleaning up after the synchronize_srcu() above.
578 */
579 synchronize_rcu();
580}
581
5873b8a9 582void call_rcu_tasks(struct rcu_head *rhp, rcu_callback_t func);
c97d12a6 583DEFINE_RCU_TASKS(rcu_tasks, rcu_tasks_wait_gp, call_rcu_tasks, "RCU Tasks");
5873b8a9
PM
584
585/**
586 * call_rcu_tasks() - Queue an RCU for invocation task-based grace period
587 * @rhp: structure to be used for queueing the RCU updates.
588 * @func: actual callback function to be invoked after the grace period
589 *
590 * The callback function will be invoked some time after a full grace
591 * period elapses, in other words after all currently executing RCU
592 * read-side critical sections have completed. call_rcu_tasks() assumes
593 * that the read-side critical sections end at a voluntary context
8af9e2c7 594 * switch (not a preemption!), cond_resched_tasks_rcu_qs(), entry into idle,
5873b8a9
PM
595 * or transition to usermode execution. As such, there are no read-side
596 * primitives analogous to rcu_read_lock() and rcu_read_unlock() because
597 * this primitive is intended to determine that all tasks have passed
a616aec9 598 * through a safe state, not so much for data-structure synchronization.
5873b8a9
PM
599 *
600 * See the description of call_rcu() for more detailed information on
601 * memory ordering guarantees.
602 */
603void call_rcu_tasks(struct rcu_head *rhp, rcu_callback_t func)
604{
605 call_rcu_tasks_generic(rhp, func, &rcu_tasks);
606}
607EXPORT_SYMBOL_GPL(call_rcu_tasks);
608
609/**
610 * synchronize_rcu_tasks - wait until an rcu-tasks grace period has elapsed.
611 *
612 * Control will return to the caller some time after a full rcu-tasks
613 * grace period has elapsed, in other words after all currently
614 * executing rcu-tasks read-side critical sections have elapsed. These
615 * read-side critical sections are delimited by calls to schedule(),
616 * cond_resched_tasks_rcu_qs(), idle execution, userspace execution, calls
617 * to synchronize_rcu_tasks(), and (in theory, anyway) cond_resched().
618 *
619 * This is a very specialized primitive, intended only for a few uses in
620 * tracing and other situations requiring manipulation of function
621 * preambles and profiling hooks. The synchronize_rcu_tasks() function
622 * is not (yet) intended for heavy use from multiple CPUs.
623 *
624 * See the description of synchronize_rcu() for more detailed information
625 * on memory ordering guarantees.
626 */
627void synchronize_rcu_tasks(void)
628{
629 synchronize_rcu_tasks_generic(&rcu_tasks);
630}
631EXPORT_SYMBOL_GPL(synchronize_rcu_tasks);
632
633/**
634 * rcu_barrier_tasks - Wait for in-flight call_rcu_tasks() callbacks.
635 *
636 * Although the current implementation is guaranteed to wait, it is not
637 * obligated to, for example, if there are no pending callbacks.
638 */
639void rcu_barrier_tasks(void)
640{
641 /* There is only one callback queue, so this is easy. ;-) */
642 synchronize_rcu_tasks();
643}
644EXPORT_SYMBOL_GPL(rcu_barrier_tasks);
645
646static int __init rcu_spawn_tasks_kthread(void)
647{
cafafd67 648 cblist_init_generic(&rcu_tasks);
4fe192df 649 rcu_tasks.gp_sleep = HZ / 10;
75dc2da5 650 rcu_tasks.init_fract = HZ / 10;
e4fe5dd6
PM
651 rcu_tasks.pregp_func = rcu_tasks_pregp_step;
652 rcu_tasks.pertask_func = rcu_tasks_pertask;
653 rcu_tasks.postscan_func = rcu_tasks_postscan;
654 rcu_tasks.holdouts_func = check_all_holdout_tasks;
655 rcu_tasks.postgp_func = rcu_tasks_postgp;
5873b8a9
PM
656 rcu_spawn_tasks_kthread_generic(&rcu_tasks);
657 return 0;
658}
5873b8a9 659
27c0f144
PM
660#if !defined(CONFIG_TINY_RCU)
661void show_rcu_tasks_classic_gp_kthread(void)
e21408ce
PM
662{
663 show_rcu_tasks_generic_gp_kthread(&rcu_tasks, "");
664}
27c0f144
PM
665EXPORT_SYMBOL_GPL(show_rcu_tasks_classic_gp_kthread);
666#endif // !defined(CONFIG_TINY_RCU)
e21408ce 667
25246fc8
PM
668/* Do the srcu_read_lock() for the above synchronize_srcu(). */
669void exit_tasks_rcu_start(void) __acquires(&tasks_rcu_exit_srcu)
670{
671 preempt_disable();
672 current->rcu_tasks_idx = __srcu_read_lock(&tasks_rcu_exit_srcu);
673 preempt_enable();
674}
675
676/* Do the srcu_read_unlock() for the above synchronize_srcu(). */
677void exit_tasks_rcu_finish(void) __releases(&tasks_rcu_exit_srcu)
678{
679 struct task_struct *t = current;
680
681 preempt_disable();
682 __srcu_read_unlock(&tasks_rcu_exit_srcu, t->rcu_tasks_idx);
683 preempt_enable();
684 exit_tasks_rcu_finish_trace(t);
685}
686
e21408ce 687#else /* #ifdef CONFIG_TASKS_RCU */
25246fc8
PM
688void exit_tasks_rcu_start(void) { }
689void exit_tasks_rcu_finish(void) { exit_tasks_rcu_finish_trace(current); }
e21408ce 690#endif /* #else #ifdef CONFIG_TASKS_RCU */
c84aad76
PM
691
692#ifdef CONFIG_TASKS_RUDE_RCU
693
694////////////////////////////////////////////////////////////////////////
695//
696// "Rude" variant of Tasks RCU, inspired by Steve Rostedt's trick of
697// passing an empty function to schedule_on_each_cpu(). This approach
e4be1f44
PM
698// provides an asynchronous call_rcu_tasks_rude() API and batching of
699// concurrent calls to the synchronous synchronize_rcu_tasks_rude() API.
9fc98e31
PM
700// This invokes schedule_on_each_cpu() in order to send IPIs far and wide
701// and induces otherwise unnecessary context switches on all online CPUs,
702// whether idle or not.
703//
704// Callback handling is provided by the rcu_tasks_kthread() function.
705//
706// Ordering is provided by the scheduler's context-switch code.
c84aad76
PM
707
708// Empty function to allow workqueues to force a context switch.
709static void rcu_tasks_be_rude(struct work_struct *work)
710{
711}
712
713// Wait for one rude RCU-tasks grace period.
714static void rcu_tasks_rude_wait_gp(struct rcu_tasks *rtp)
715{
238dbce3 716 rtp->n_ipis += cpumask_weight(cpu_online_mask);
c84aad76
PM
717 schedule_on_each_cpu(rcu_tasks_be_rude);
718}
719
720void call_rcu_tasks_rude(struct rcu_head *rhp, rcu_callback_t func);
c97d12a6
PM
721DEFINE_RCU_TASKS(rcu_tasks_rude, rcu_tasks_rude_wait_gp, call_rcu_tasks_rude,
722 "RCU Tasks Rude");
c84aad76
PM
723
724/**
725 * call_rcu_tasks_rude() - Queue a callback rude task-based grace period
726 * @rhp: structure to be used for queueing the RCU updates.
727 * @func: actual callback function to be invoked after the grace period
728 *
729 * The callback function will be invoked some time after a full grace
730 * period elapses, in other words after all currently executing RCU
731 * read-side critical sections have completed. call_rcu_tasks_rude()
732 * assumes that the read-side critical sections end at context switch,
8af9e2c7 733 * cond_resched_tasks_rcu_qs(), or transition to usermode execution (as
a6517e9c
NU
734 * usermode execution is schedulable). As such, there are no read-side
735 * primitives analogous to rcu_read_lock() and rcu_read_unlock() because
736 * this primitive is intended to determine that all tasks have passed
737 * through a safe state, not so much for data-structure synchronization.
c84aad76
PM
738 *
739 * See the description of call_rcu() for more detailed information on
740 * memory ordering guarantees.
741 */
742void call_rcu_tasks_rude(struct rcu_head *rhp, rcu_callback_t func)
743{
744 call_rcu_tasks_generic(rhp, func, &rcu_tasks_rude);
745}
746EXPORT_SYMBOL_GPL(call_rcu_tasks_rude);
747
748/**
749 * synchronize_rcu_tasks_rude - wait for a rude rcu-tasks grace period
750 *
751 * Control will return to the caller some time after a rude rcu-tasks
752 * grace period has elapsed, in other words after all currently
753 * executing rcu-tasks read-side critical sections have elapsed. These
754 * read-side critical sections are delimited by calls to schedule(),
a6517e9c
NU
755 * cond_resched_tasks_rcu_qs(), userspace execution (which is a schedulable
756 * context), and (in theory, anyway) cond_resched().
c84aad76
PM
757 *
758 * This is a very specialized primitive, intended only for a few uses in
759 * tracing and other situations requiring manipulation of function preambles
760 * and profiling hooks. The synchronize_rcu_tasks_rude() function is not
761 * (yet) intended for heavy use from multiple CPUs.
762 *
763 * See the description of synchronize_rcu() for more detailed information
764 * on memory ordering guarantees.
765 */
766void synchronize_rcu_tasks_rude(void)
767{
768 synchronize_rcu_tasks_generic(&rcu_tasks_rude);
769}
770EXPORT_SYMBOL_GPL(synchronize_rcu_tasks_rude);
771
772/**
773 * rcu_barrier_tasks_rude - Wait for in-flight call_rcu_tasks_rude() callbacks.
774 *
775 * Although the current implementation is guaranteed to wait, it is not
776 * obligated to, for example, if there are no pending callbacks.
777 */
778void rcu_barrier_tasks_rude(void)
779{
780 /* There is only one callback queue, so this is easy. ;-) */
781 synchronize_rcu_tasks_rude();
782}
783EXPORT_SYMBOL_GPL(rcu_barrier_tasks_rude);
784
785static int __init rcu_spawn_tasks_rude_kthread(void)
786{
cafafd67 787 cblist_init_generic(&rcu_tasks_rude);
4fe192df 788 rcu_tasks_rude.gp_sleep = HZ / 10;
c84aad76
PM
789 rcu_spawn_tasks_kthread_generic(&rcu_tasks_rude);
790 return 0;
791}
c84aad76 792
27c0f144
PM
793#if !defined(CONFIG_TINY_RCU)
794void show_rcu_tasks_rude_gp_kthread(void)
e21408ce
PM
795{
796 show_rcu_tasks_generic_gp_kthread(&rcu_tasks_rude, "");
797}
27c0f144
PM
798EXPORT_SYMBOL_GPL(show_rcu_tasks_rude_gp_kthread);
799#endif // !defined(CONFIG_TINY_RCU)
800#endif /* #ifdef CONFIG_TASKS_RUDE_RCU */
d5f177d3
PM
801
802////////////////////////////////////////////////////////////////////////
803//
804// Tracing variant of Tasks RCU. This variant is designed to be used
805// to protect tracing hooks, including those of BPF. This variant
806// therefore:
807//
808// 1. Has explicit read-side markers to allow finite grace periods
809// in the face of in-kernel loops for PREEMPT=n builds.
810//
811// 2. Protects code in the idle loop, exception entry/exit, and
812// CPU-hotplug code paths, similar to the capabilities of SRCU.
813//
c4f113ac 814// 3. Avoids expensive read-side instructions, having overhead similar
d5f177d3
PM
815// to that of Preemptible RCU.
816//
817// There are of course downsides. The grace-period code can send IPIs to
818// CPUs, even when those CPUs are in the idle loop or in nohz_full userspace.
819// It is necessary to scan the full tasklist, much as for Tasks RCU. There
820// is a single callback queue guarded by a single lock, again, much as for
821// Tasks RCU. If needed, these downsides can be at least partially remedied.
822//
823// Perhaps most important, this variant of RCU does not affect the vanilla
824// flavors, rcu_preempt and rcu_sched. The fact that RCU Tasks Trace
825// readers can operate from idle, offline, and exception entry/exit in no
826// way allows rcu_preempt and rcu_sched readers to also do so.
a434dd10
PM
827//
828// The implementation uses rcu_tasks_wait_gp(), which relies on function
829// pointers in the rcu_tasks structure. The rcu_spawn_tasks_trace_kthread()
830// function sets these function pointers up so that rcu_tasks_wait_gp()
831// invokes these functions in this order:
832//
833// rcu_tasks_trace_pregp_step():
834// Initialize the count of readers and block CPU-hotplug operations.
835// rcu_tasks_trace_pertask(), invoked on every non-idle task:
836// Initialize per-task state and attempt to identify an immediate
837// quiescent state for that task, or, failing that, attempt to
838// set that task's .need_qs flag so that task's next outermost
839// rcu_read_unlock_trace() will report the quiescent state (in which
840// case the count of readers is incremented). If both attempts fail,
45f4b4a2
PM
841// the task is added to a "holdout" list. Note that IPIs are used
842// to invoke trc_read_check_handler() in the context of running tasks
843// in order to avoid ordering overhead on common-case shared-variable
844// accessses.
a434dd10
PM
845// rcu_tasks_trace_postscan():
846// Initialize state and attempt to identify an immediate quiescent
847// state as above (but only for idle tasks), unblock CPU-hotplug
848// operations, and wait for an RCU grace period to avoid races with
849// tasks that are in the process of exiting.
850// check_all_holdout_tasks_trace(), repeatedly until holdout list is empty:
851// Scans the holdout list, attempting to identify a quiescent state
852// for each task on the list. If there is a quiescent state, the
853// corresponding task is removed from the holdout list.
854// rcu_tasks_trace_postgp():
855// Wait for the count of readers do drop to zero, reporting any stalls.
856// Also execute full memory barriers to maintain ordering with code
857// executing after the grace period.
858//
859// The exit_tasks_rcu_finish_trace() synchronizes with exiting tasks.
860//
861// Pre-grace-period update-side code is ordered before the grace
862// period via the ->cbs_lock and barriers in rcu_tasks_kthread().
863// Pre-grace-period read-side code is ordered before the grace period by
864// atomic_dec_and_test() of the count of readers (for IPIed readers) and by
865// scheduler context-switch ordering (for locked-down non-running readers).
d5f177d3
PM
866
867// The lockdep state must be outside of #ifdef to be useful.
868#ifdef CONFIG_DEBUG_LOCK_ALLOC
869static struct lock_class_key rcu_lock_trace_key;
870struct lockdep_map rcu_trace_lock_map =
871 STATIC_LOCKDEP_MAP_INIT("rcu_read_lock_trace", &rcu_lock_trace_key);
872EXPORT_SYMBOL_GPL(rcu_trace_lock_map);
873#endif /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
874
875#ifdef CONFIG_TASKS_TRACE_RCU
876
30d8aa51
PM
877static atomic_t trc_n_readers_need_end; // Number of waited-for readers.
878static DECLARE_WAIT_QUEUE_HEAD(trc_wait); // List of holdout tasks.
d5f177d3
PM
879
880// Record outstanding IPIs to each CPU. No point in sending two...
881static DEFINE_PER_CPU(bool, trc_ipi_to_cpu);
882
40471509
PM
883// The number of detections of task quiescent state relying on
884// heavyweight readers executing explicit memory barriers.
6731da9e
PM
885static unsigned long n_heavy_reader_attempts;
886static unsigned long n_heavy_reader_updates;
887static unsigned long n_heavy_reader_ofl_updates;
40471509 888
b0afa0f0
PM
889void call_rcu_tasks_trace(struct rcu_head *rhp, rcu_callback_t func);
890DEFINE_RCU_TASKS(rcu_tasks_trace, rcu_tasks_wait_gp, call_rcu_tasks_trace,
891 "RCU Tasks Trace");
892
b38f57c1
PM
893/*
894 * This irq_work handler allows rcu_read_unlock_trace() to be invoked
895 * while the scheduler locks are held.
896 */
897static void rcu_read_unlock_iw(struct irq_work *iwp)
898{
899 wake_up(&trc_wait);
900}
901static DEFINE_IRQ_WORK(rcu_tasks_trace_iw, rcu_read_unlock_iw);
902
d5f177d3 903/* If we are the last reader, wake up the grace-period kthread. */
a5c071cc 904void rcu_read_unlock_trace_special(struct task_struct *t)
d5f177d3 905{
f8ab3fad 906 int nq = READ_ONCE(t->trc_reader_special.b.need_qs);
276c4104 907
9ae58d7b
PM
908 if (IS_ENABLED(CONFIG_TASKS_TRACE_RCU_READ_MB) &&
909 t->trc_reader_special.b.need_mb)
276c4104
PM
910 smp_mb(); // Pairs with update-side barriers.
911 // Update .need_qs before ->trc_reader_nesting for irq/NMI handlers.
912 if (nq)
913 WRITE_ONCE(t->trc_reader_special.b.need_qs, false);
a5c071cc 914 WRITE_ONCE(t->trc_reader_nesting, 0);
276c4104 915 if (nq && atomic_dec_and_test(&trc_n_readers_need_end))
b38f57c1 916 irq_work_queue(&rcu_tasks_trace_iw);
d5f177d3
PM
917}
918EXPORT_SYMBOL_GPL(rcu_read_unlock_trace_special);
919
920/* Add a task to the holdout list, if it is not already on the list. */
921static void trc_add_holdout(struct task_struct *t, struct list_head *bhp)
922{
923 if (list_empty(&t->trc_holdout_list)) {
924 get_task_struct(t);
925 list_add(&t->trc_holdout_list, bhp);
926 }
927}
928
929/* Remove a task from the holdout list, if it is in fact present. */
930static void trc_del_holdout(struct task_struct *t)
931{
932 if (!list_empty(&t->trc_holdout_list)) {
933 list_del_init(&t->trc_holdout_list);
934 put_task_struct(t);
935 }
936}
937
938/* IPI handler to check task state. */
939static void trc_read_check_handler(void *t_in)
940{
941 struct task_struct *t = current;
942 struct task_struct *texp = t_in;
943
944 // If the task is no longer running on this CPU, leave.
945 if (unlikely(texp != t)) {
d5f177d3
PM
946 goto reset_ipi; // Already on holdout list, so will check later.
947 }
948
949 // If the task is not in a read-side critical section, and
950 // if this is the last reader, awaken the grace-period kthread.
bdb0cca0 951 if (likely(!READ_ONCE(t->trc_reader_nesting))) {
d5f177d3
PM
952 WRITE_ONCE(t->trc_reader_checked, true);
953 goto reset_ipi;
954 }
ba3a86e4 955 // If we are racing with an rcu_read_unlock_trace(), try again later.
96017bf9 956 if (unlikely(READ_ONCE(t->trc_reader_nesting) < 0))
ba3a86e4 957 goto reset_ipi;
d5f177d3
PM
958 WRITE_ONCE(t->trc_reader_checked, true);
959
960 // Get here if the task is in a read-side critical section. Set
961 // its state so that it will awaken the grace-period kthread upon
962 // exit from that critical section.
96017bf9 963 atomic_inc(&trc_n_readers_need_end); // One more to wait on.
f8ab3fad 964 WARN_ON_ONCE(READ_ONCE(t->trc_reader_special.b.need_qs));
276c4104 965 WRITE_ONCE(t->trc_reader_special.b.need_qs, true);
d5f177d3
PM
966
967reset_ipi:
968 // Allow future IPIs to be sent on CPU and for task.
969 // Also order this IPI handler against any later manipulations of
970 // the intended task.
8211e922 971 smp_store_release(per_cpu_ptr(&trc_ipi_to_cpu, smp_processor_id()), false); // ^^^
d5f177d3
PM
972 smp_store_release(&texp->trc_ipi_to_cpu, -1); // ^^^
973}
974
975/* Callback function for scheduler to check locked-down task. */
9b3c4ab3 976static int trc_inspect_reader(struct task_struct *t, void *arg)
d5f177d3 977{
7d0c9c50 978 int cpu = task_cpu(t);
18f08e75 979 int nesting;
7e3b70e0 980 bool ofl = cpu_is_offline(cpu);
7d0c9c50
PM
981
982 if (task_curr(t)) {
30d8aa51 983 WARN_ON_ONCE(ofl && !is_idle_task(t));
7e3b70e0 984
7d0c9c50 985 // If no chance of heavyweight readers, do it the hard way.
7e3b70e0 986 if (!ofl && !IS_ENABLED(CONFIG_TASKS_TRACE_RCU_READ_MB))
9b3c4ab3 987 return -EINVAL;
7d0c9c50
PM
988
989 // If heavyweight readers are enabled on the remote task,
990 // we can inspect its state despite its currently running.
991 // However, we cannot safely change its state.
40471509 992 n_heavy_reader_attempts++;
7e3b70e0
PM
993 if (!ofl && // Check for "running" idle tasks on offline CPUs.
994 !rcu_dynticks_zero_in_eqs(cpu, &t->trc_reader_nesting))
9b3c4ab3 995 return -EINVAL; // No quiescent state, do it the hard way.
40471509 996 n_heavy_reader_updates++;
edf3775f
PM
997 if (ofl)
998 n_heavy_reader_ofl_updates++;
18f08e75 999 nesting = 0;
7d0c9c50 1000 } else {
bdb0cca0 1001 // The task is not running, so C-language access is safe.
18f08e75 1002 nesting = t->trc_reader_nesting;
7d0c9c50 1003 }
d5f177d3 1004
18f08e75
PM
1005 // If not exiting a read-side critical section, mark as checked
1006 // so that the grace-period kthread will remove it from the
1007 // holdout list.
1008 t->trc_reader_checked = nesting >= 0;
1009 if (nesting <= 0)
6fedc280 1010 return nesting ? -EINVAL : 0; // If in QS, done, otherwise try again later.
7d0c9c50
PM
1011
1012 // The task is in a read-side critical section, so set up its
1013 // state so that it will awaken the grace-period kthread upon exit
1014 // from that critical section.
1015 atomic_inc(&trc_n_readers_need_end); // One more to wait on.
f8ab3fad 1016 WARN_ON_ONCE(READ_ONCE(t->trc_reader_special.b.need_qs));
7d0c9c50 1017 WRITE_ONCE(t->trc_reader_special.b.need_qs, true);
9b3c4ab3 1018 return 0;
d5f177d3
PM
1019}
1020
1021/* Attempt to extract the state for the specified task. */
1022static void trc_wait_for_one_reader(struct task_struct *t,
1023 struct list_head *bhp)
1024{
1025 int cpu;
1026
1027 // If a previous IPI is still in flight, let it complete.
1028 if (smp_load_acquire(&t->trc_ipi_to_cpu) != -1) // Order IPI
1029 return;
1030
1031 // The current task had better be in a quiescent state.
1032 if (t == current) {
1033 t->trc_reader_checked = true;
bdb0cca0 1034 WARN_ON_ONCE(READ_ONCE(t->trc_reader_nesting));
d5f177d3
PM
1035 return;
1036 }
1037
1038 // Attempt to nail down the task for inspection.
1039 get_task_struct(t);
9b3c4ab3 1040 if (!task_call_func(t, trc_inspect_reader, NULL)) {
d5f177d3
PM
1041 put_task_struct(t);
1042 return;
1043 }
1044 put_task_struct(t);
1045
45f4b4a2
PM
1046 // If this task is not yet on the holdout list, then we are in
1047 // an RCU read-side critical section. Otherwise, the invocation of
d0a85858 1048 // trc_add_holdout() that added it to the list did the necessary
45f4b4a2
PM
1049 // get_task_struct(). Either way, the task cannot be freed out
1050 // from under this code.
1051
d5f177d3
PM
1052 // If currently running, send an IPI, either way, add to list.
1053 trc_add_holdout(t, bhp);
574de876
PM
1054 if (task_curr(t) &&
1055 time_after(jiffies + 1, rcu_tasks_trace.gp_start + rcu_task_ipi_delay)) {
d5f177d3
PM
1056 // The task is currently running, so try IPIing it.
1057 cpu = task_cpu(t);
1058
1059 // If there is already an IPI outstanding, let it happen.
1060 if (per_cpu(trc_ipi_to_cpu, cpu) || t->trc_ipi_to_cpu >= 0)
1061 return;
1062
d5f177d3
PM
1063 per_cpu(trc_ipi_to_cpu, cpu) = true;
1064 t->trc_ipi_to_cpu = cpu;
238dbce3 1065 rcu_tasks_trace.n_ipis++;
96017bf9 1066 if (smp_call_function_single(cpu, trc_read_check_handler, t, 0)) {
d5f177d3
PM
1067 // Just in case there is some other reason for
1068 // failure than the target CPU being offline.
46aa886c
NU
1069 WARN_ONCE(1, "%s(): smp_call_function_single() failed for CPU: %d\n",
1070 __func__, cpu);
7e0669c3 1071 rcu_tasks_trace.n_ipis_fails++;
d5f177d3 1072 per_cpu(trc_ipi_to_cpu, cpu) = false;
46aa886c 1073 t->trc_ipi_to_cpu = -1;
d5f177d3
PM
1074 }
1075 }
1076}
1077
1078/* Initialize for a new RCU-tasks-trace grace period. */
1079static void rcu_tasks_trace_pregp_step(void)
1080{
1081 int cpu;
1082
d5f177d3
PM
1083 // Allow for fast-acting IPIs.
1084 atomic_set(&trc_n_readers_need_end, 1);
1085
1086 // There shouldn't be any old IPIs, but...
1087 for_each_possible_cpu(cpu)
1088 WARN_ON_ONCE(per_cpu(trc_ipi_to_cpu, cpu));
81b4a7bc
PM
1089
1090 // Disable CPU hotplug across the tasklist scan.
1091 // This also waits for all readers in CPU-hotplug code paths.
1092 cpus_read_lock();
d5f177d3
PM
1093}
1094
1095/* Do first-round processing for the specified task. */
1096static void rcu_tasks_trace_pertask(struct task_struct *t,
1097 struct list_head *hop)
1098{
1b04fa99
URS
1099 // During early boot when there is only the one boot CPU, there
1100 // is no idle task for the other CPUs. Just return.
1101 if (unlikely(t == NULL))
1102 return;
1103
276c4104 1104 WRITE_ONCE(t->trc_reader_special.b.need_qs, false);
43766c3e 1105 WRITE_ONCE(t->trc_reader_checked, false);
d5f177d3
PM
1106 t->trc_ipi_to_cpu = -1;
1107 trc_wait_for_one_reader(t, hop);
1108}
1109
9796e1ae
PM
1110/*
1111 * Do intermediate processing between task and holdout scans and
1112 * pick up the idle tasks.
1113 */
1114static void rcu_tasks_trace_postscan(struct list_head *hop)
d5f177d3 1115{
9796e1ae
PM
1116 int cpu;
1117
1118 for_each_possible_cpu(cpu)
1119 rcu_tasks_trace_pertask(idle_task(cpu), hop);
1120
81b4a7bc
PM
1121 // Re-enable CPU hotplug now that the tasklist scan has completed.
1122 cpus_read_unlock();
1123
d5f177d3
PM
1124 // Wait for late-stage exiting tasks to finish exiting.
1125 // These might have passed the call to exit_tasks_rcu_finish().
1126 synchronize_rcu();
1127 // Any tasks that exit after this point will set ->trc_reader_checked.
1128}
1129
4593e772
PM
1130/* Show the state of a task stalling the current RCU tasks trace GP. */
1131static void show_stalled_task_trace(struct task_struct *t, bool *firstreport)
1132{
1133 int cpu;
1134
1135 if (*firstreport) {
1136 pr_err("INFO: rcu_tasks_trace detected stalls on tasks:\n");
1137 *firstreport = false;
1138 }
1139 // FIXME: This should attempt to use try_invoke_on_nonrunning_task().
1140 cpu = task_cpu(t);
1141 pr_alert("P%d: %c%c%c nesting: %d%c cpu: %d\n",
1142 t->pid,
d39ec8f3 1143 ".I"[READ_ONCE(t->trc_ipi_to_cpu) >= 0],
4593e772 1144 ".i"[is_idle_task(t)],
d39ec8f3 1145 ".N"[cpu >= 0 && tick_nohz_full_cpu(cpu)],
bdb0cca0 1146 READ_ONCE(t->trc_reader_nesting),
f8ab3fad 1147 " N"[!!READ_ONCE(t->trc_reader_special.b.need_qs)],
4593e772
PM
1148 cpu);
1149 sched_show_task(t);
1150}
1151
1152/* List stalled IPIs for RCU tasks trace. */
1153static void show_stalled_ipi_trace(void)
1154{
1155 int cpu;
1156
1157 for_each_possible_cpu(cpu)
1158 if (per_cpu(trc_ipi_to_cpu, cpu))
1159 pr_alert("\tIPI outstanding to CPU %d\n", cpu);
1160}
1161
d5f177d3
PM
1162/* Do one scan of the holdout list. */
1163static void check_all_holdout_tasks_trace(struct list_head *hop,
4593e772 1164 bool needreport, bool *firstreport)
d5f177d3
PM
1165{
1166 struct task_struct *g, *t;
1167
81b4a7bc
PM
1168 // Disable CPU hotplug across the holdout list scan.
1169 cpus_read_lock();
1170
d5f177d3
PM
1171 list_for_each_entry_safe(t, g, hop, trc_holdout_list) {
1172 // If safe and needed, try to check the current task.
1173 if (READ_ONCE(t->trc_ipi_to_cpu) == -1 &&
1174 !READ_ONCE(t->trc_reader_checked))
1175 trc_wait_for_one_reader(t, hop);
1176
1177 // If check succeeded, remove this task from the list.
f5dbc594
PM
1178 if (smp_load_acquire(&t->trc_ipi_to_cpu) == -1 &&
1179 READ_ONCE(t->trc_reader_checked))
d5f177d3 1180 trc_del_holdout(t);
4593e772
PM
1181 else if (needreport)
1182 show_stalled_task_trace(t, firstreport);
1183 }
81b4a7bc
PM
1184
1185 // Re-enable CPU hotplug now that the holdout list scan has completed.
1186 cpus_read_unlock();
1187
4593e772 1188 if (needreport) {
89401176 1189 if (*firstreport)
4593e772
PM
1190 pr_err("INFO: rcu_tasks_trace detected stalls? (Late IPI?)\n");
1191 show_stalled_ipi_trace();
d5f177d3
PM
1192 }
1193}
1194
cbe0d8d9
PM
1195static void rcu_tasks_trace_empty_fn(void *unused)
1196{
1197}
1198
d5f177d3 1199/* Wait for grace period to complete and provide ordering. */
af051ca4 1200static void rcu_tasks_trace_postgp(struct rcu_tasks *rtp)
d5f177d3 1201{
cbe0d8d9 1202 int cpu;
4593e772
PM
1203 bool firstreport;
1204 struct task_struct *g, *t;
1205 LIST_HEAD(holdouts);
1206 long ret;
1207
cbe0d8d9
PM
1208 // Wait for any lingering IPI handlers to complete. Note that
1209 // if a CPU has gone offline or transitioned to userspace in the
1210 // meantime, all IPI handlers should have been drained beforehand.
1211 // Yes, this assumes that CPUs process IPIs in order. If that ever
1212 // changes, there will need to be a recheck and/or timed wait.
1213 for_each_online_cpu(cpu)
f5dbc594 1214 if (WARN_ON_ONCE(smp_load_acquire(per_cpu_ptr(&trc_ipi_to_cpu, cpu))))
cbe0d8d9
PM
1215 smp_call_function_single(cpu, rcu_tasks_trace_empty_fn, NULL, 1);
1216
d5f177d3
PM
1217 // Remove the safety count.
1218 smp_mb__before_atomic(); // Order vs. earlier atomics
1219 atomic_dec(&trc_n_readers_need_end);
1220 smp_mb__after_atomic(); // Order vs. later atomics
1221
1222 // Wait for readers.
af051ca4 1223 set_tasks_gp_state(rtp, RTGS_WAIT_READERS);
4593e772
PM
1224 for (;;) {
1225 ret = wait_event_idle_exclusive_timeout(
1226 trc_wait,
1227 atomic_read(&trc_n_readers_need_end) == 0,
1228 READ_ONCE(rcu_task_stall_timeout));
1229 if (ret)
1230 break; // Count reached zero.
af051ca4 1231 // Stall warning time, so make a list of the offenders.
f747c7e1 1232 rcu_read_lock();
4593e772 1233 for_each_process_thread(g, t)
276c4104 1234 if (READ_ONCE(t->trc_reader_special.b.need_qs))
4593e772 1235 trc_add_holdout(t, &holdouts);
f747c7e1 1236 rcu_read_unlock();
4593e772 1237 firstreport = true;
592031cc
PM
1238 list_for_each_entry_safe(t, g, &holdouts, trc_holdout_list) {
1239 if (READ_ONCE(t->trc_reader_special.b.need_qs))
4593e772 1240 show_stalled_task_trace(t, &firstreport);
592031cc
PM
1241 trc_del_holdout(t); // Release task_struct reference.
1242 }
4593e772
PM
1243 if (firstreport)
1244 pr_err("INFO: rcu_tasks_trace detected stalls? (Counter/taskslist mismatch?)\n");
1245 show_stalled_ipi_trace();
1246 pr_err("\t%d holdouts\n", atomic_read(&trc_n_readers_need_end));
1247 }
d5f177d3 1248 smp_mb(); // Caller's code must be ordered after wakeup.
43766c3e 1249 // Pairs with pretty much every ordering primitive.
d5f177d3
PM
1250}
1251
1252/* Report any needed quiescent state for this exiting task. */
25246fc8 1253static void exit_tasks_rcu_finish_trace(struct task_struct *t)
d5f177d3
PM
1254{
1255 WRITE_ONCE(t->trc_reader_checked, true);
bdb0cca0 1256 WARN_ON_ONCE(READ_ONCE(t->trc_reader_nesting));
d5f177d3 1257 WRITE_ONCE(t->trc_reader_nesting, 0);
276c4104 1258 if (WARN_ON_ONCE(READ_ONCE(t->trc_reader_special.b.need_qs)))
a5c071cc 1259 rcu_read_unlock_trace_special(t);
d5f177d3
PM
1260}
1261
d5f177d3
PM
1262/**
1263 * call_rcu_tasks_trace() - Queue a callback trace task-based grace period
1264 * @rhp: structure to be used for queueing the RCU updates.
1265 * @func: actual callback function to be invoked after the grace period
1266 *
ed42c380
NU
1267 * The callback function will be invoked some time after a trace rcu-tasks
1268 * grace period elapses, in other words after all currently executing
1269 * trace rcu-tasks read-side critical sections have completed. These
1270 * read-side critical sections are delimited by calls to rcu_read_lock_trace()
1271 * and rcu_read_unlock_trace().
d5f177d3
PM
1272 *
1273 * See the description of call_rcu() for more detailed information on
1274 * memory ordering guarantees.
1275 */
1276void call_rcu_tasks_trace(struct rcu_head *rhp, rcu_callback_t func)
1277{
1278 call_rcu_tasks_generic(rhp, func, &rcu_tasks_trace);
1279}
1280EXPORT_SYMBOL_GPL(call_rcu_tasks_trace);
1281
1282/**
1283 * synchronize_rcu_tasks_trace - wait for a trace rcu-tasks grace period
1284 *
1285 * Control will return to the caller some time after a trace rcu-tasks
c7dcf810 1286 * grace period has elapsed, in other words after all currently executing
ed42c380 1287 * trace rcu-tasks read-side critical sections have elapsed. These read-side
c7dcf810
PM
1288 * critical sections are delimited by calls to rcu_read_lock_trace()
1289 * and rcu_read_unlock_trace().
d5f177d3
PM
1290 *
1291 * This is a very specialized primitive, intended only for a few uses in
1292 * tracing and other situations requiring manipulation of function preambles
1293 * and profiling hooks. The synchronize_rcu_tasks_trace() function is not
1294 * (yet) intended for heavy use from multiple CPUs.
1295 *
1296 * See the description of synchronize_rcu() for more detailed information
1297 * on memory ordering guarantees.
1298 */
1299void synchronize_rcu_tasks_trace(void)
1300{
1301 RCU_LOCKDEP_WARN(lock_is_held(&rcu_trace_lock_map), "Illegal synchronize_rcu_tasks_trace() in RCU Tasks Trace read-side critical section");
1302 synchronize_rcu_tasks_generic(&rcu_tasks_trace);
1303}
1304EXPORT_SYMBOL_GPL(synchronize_rcu_tasks_trace);
1305
1306/**
1307 * rcu_barrier_tasks_trace - Wait for in-flight call_rcu_tasks_trace() callbacks.
1308 *
1309 * Although the current implementation is guaranteed to wait, it is not
1310 * obligated to, for example, if there are no pending callbacks.
1311 */
1312void rcu_barrier_tasks_trace(void)
1313{
1314 /* There is only one callback queue, so this is easy. ;-) */
1315 synchronize_rcu_tasks_trace();
1316}
1317EXPORT_SYMBOL_GPL(rcu_barrier_tasks_trace);
1318
1319static int __init rcu_spawn_tasks_trace_kthread(void)
1320{
cafafd67 1321 cblist_init_generic(&rcu_tasks_trace);
2393a613 1322 if (IS_ENABLED(CONFIG_TASKS_TRACE_RCU_READ_MB)) {
4fe192df 1323 rcu_tasks_trace.gp_sleep = HZ / 10;
75dc2da5 1324 rcu_tasks_trace.init_fract = HZ / 10;
2393a613 1325 } else {
4fe192df
PM
1326 rcu_tasks_trace.gp_sleep = HZ / 200;
1327 if (rcu_tasks_trace.gp_sleep <= 0)
1328 rcu_tasks_trace.gp_sleep = 1;
75dc2da5 1329 rcu_tasks_trace.init_fract = HZ / 200;
2393a613
PM
1330 if (rcu_tasks_trace.init_fract <= 0)
1331 rcu_tasks_trace.init_fract = 1;
1332 }
d5f177d3
PM
1333 rcu_tasks_trace.pregp_func = rcu_tasks_trace_pregp_step;
1334 rcu_tasks_trace.pertask_func = rcu_tasks_trace_pertask;
1335 rcu_tasks_trace.postscan_func = rcu_tasks_trace_postscan;
1336 rcu_tasks_trace.holdouts_func = check_all_holdout_tasks_trace;
1337 rcu_tasks_trace.postgp_func = rcu_tasks_trace_postgp;
1338 rcu_spawn_tasks_kthread_generic(&rcu_tasks_trace);
1339 return 0;
1340}
d5f177d3 1341
27c0f144
PM
1342#if !defined(CONFIG_TINY_RCU)
1343void show_rcu_tasks_trace_gp_kthread(void)
e21408ce 1344{
40471509 1345 char buf[64];
e21408ce 1346
edf3775f
PM
1347 sprintf(buf, "N%d h:%lu/%lu/%lu", atomic_read(&trc_n_readers_need_end),
1348 data_race(n_heavy_reader_ofl_updates),
40471509
PM
1349 data_race(n_heavy_reader_updates),
1350 data_race(n_heavy_reader_attempts));
e21408ce
PM
1351 show_rcu_tasks_generic_gp_kthread(&rcu_tasks_trace, buf);
1352}
27c0f144
PM
1353EXPORT_SYMBOL_GPL(show_rcu_tasks_trace_gp_kthread);
1354#endif // !defined(CONFIG_TINY_RCU)
e21408ce 1355
d5f177d3 1356#else /* #ifdef CONFIG_TASKS_TRACE_RCU */
25246fc8 1357static void exit_tasks_rcu_finish_trace(struct task_struct *t) { }
d5f177d3 1358#endif /* #else #ifdef CONFIG_TASKS_TRACE_RCU */
8fd8ca38 1359
8344496e 1360#ifndef CONFIG_TINY_RCU
e21408ce
PM
1361void show_rcu_tasks_gp_kthreads(void)
1362{
1363 show_rcu_tasks_classic_gp_kthread();
1364 show_rcu_tasks_rude_gp_kthread();
1365 show_rcu_tasks_trace_gp_kthread();
1366}
8344496e 1367#endif /* #ifndef CONFIG_TINY_RCU */
e21408ce 1368
bfba7ed0
URS
1369#ifdef CONFIG_PROVE_RCU
1370struct rcu_tasks_test_desc {
1371 struct rcu_head rh;
1372 const char *name;
1373 bool notrun;
1374};
1375
1376static struct rcu_tasks_test_desc tests[] = {
1377 {
1378 .name = "call_rcu_tasks()",
1379 /* If not defined, the test is skipped. */
1380 .notrun = !IS_ENABLED(CONFIG_TASKS_RCU),
1381 },
1382 {
1383 .name = "call_rcu_tasks_rude()",
1384 /* If not defined, the test is skipped. */
1385 .notrun = !IS_ENABLED(CONFIG_TASKS_RUDE_RCU),
1386 },
1387 {
1388 .name = "call_rcu_tasks_trace()",
1389 /* If not defined, the test is skipped. */
1390 .notrun = !IS_ENABLED(CONFIG_TASKS_TRACE_RCU)
1391 }
1392};
1393
1394static void test_rcu_tasks_callback(struct rcu_head *rhp)
1395{
1396 struct rcu_tasks_test_desc *rttd =
1397 container_of(rhp, struct rcu_tasks_test_desc, rh);
1398
1399 pr_info("Callback from %s invoked.\n", rttd->name);
1400
1401 rttd->notrun = true;
1402}
1403
1404static void rcu_tasks_initiate_self_tests(void)
1405{
1406 pr_info("Running RCU-tasks wait API self tests\n");
1407#ifdef CONFIG_TASKS_RCU
1408 synchronize_rcu_tasks();
1409 call_rcu_tasks(&tests[0].rh, test_rcu_tasks_callback);
1410#endif
1411
1412#ifdef CONFIG_TASKS_RUDE_RCU
1413 synchronize_rcu_tasks_rude();
1414 call_rcu_tasks_rude(&tests[1].rh, test_rcu_tasks_callback);
1415#endif
1416
1417#ifdef CONFIG_TASKS_TRACE_RCU
1418 synchronize_rcu_tasks_trace();
1419 call_rcu_tasks_trace(&tests[2].rh, test_rcu_tasks_callback);
1420#endif
1421}
1422
1423static int rcu_tasks_verify_self_tests(void)
1424{
1425 int ret = 0;
1426 int i;
1427
1428 for (i = 0; i < ARRAY_SIZE(tests); i++) {
1429 if (!tests[i].notrun) { // still hanging.
1430 pr_err("%s has been failed.\n", tests[i].name);
1431 ret = -1;
1432 }
1433 }
1434
1435 if (ret)
1436 WARN_ON(1);
1437
1438 return ret;
1439}
1440late_initcall(rcu_tasks_verify_self_tests);
1441#else /* #ifdef CONFIG_PROVE_RCU */
1442static void rcu_tasks_initiate_self_tests(void) { }
1443#endif /* #else #ifdef CONFIG_PROVE_RCU */
1444
1b04fa99
URS
1445void __init rcu_init_tasks_generic(void)
1446{
1447#ifdef CONFIG_TASKS_RCU
1448 rcu_spawn_tasks_kthread();
1449#endif
1450
1451#ifdef CONFIG_TASKS_RUDE_RCU
1452 rcu_spawn_tasks_rude_kthread();
1453#endif
1454
1455#ifdef CONFIG_TASKS_TRACE_RCU
1456 rcu_spawn_tasks_trace_kthread();
1457#endif
bfba7ed0
URS
1458
1459 // Run the self-tests.
1460 rcu_tasks_initiate_self_tests();
1b04fa99
URS
1461}
1462
8fd8ca38
PM
1463#else /* #ifdef CONFIG_TASKS_RCU_GENERIC */
1464static inline void rcu_tasks_bootup_oddness(void) {}
1465#endif /* #else #ifdef CONFIG_TASKS_RCU_GENERIC */