xref: /linux/kernel/rcu/tasks.h (revision 83684c4e4d62cb02b2e4d0d18963d1035439278e)
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  * @lazy_timer: Timer to unlazify callbacks.
29  * @urgent_gp: Number of additional non-lazy grace periods.
30  * @rtp_n_lock_retries: Rough lock-contention statistic.
31  * @rtp_work: Work queue for invoking callbacks.
32  * @rtp_irq_work: IRQ work queue for deferred wakeups.
33  * @barrier_q_head: RCU callback for barrier operation.
34  * @rtp_blkd_tasks: List of tasks blocked as readers.
35  * @rtp_exit_list: List of tasks in the latter portion of do_exit().
36  * @cpu: CPU number corresponding to this entry.
37  * @index: Index of this CPU in rtpcp_array of the rcu_tasks structure.
38  * @rtpp: Pointer to the rcu_tasks structure.
39  */
40 struct rcu_tasks_percpu {
41 	struct rcu_segcblist cblist;
42 	raw_spinlock_t __private lock;
43 	unsigned long rtp_jiffies;
44 	unsigned long rtp_n_lock_retries;
45 	struct timer_list lazy_timer;
46 	unsigned int urgent_gp;
47 	struct work_struct rtp_work;
48 	struct irq_work rtp_irq_work;
49 	struct rcu_head barrier_q_head;
50 	struct list_head rtp_blkd_tasks;
51 	struct list_head rtp_exit_list;
52 	int cpu;
53 	int index;
54 	struct rcu_tasks *rtpp;
55 };
56 
57 /**
58  * struct rcu_tasks - Definition for a Tasks-RCU-like mechanism.
59  * @cbs_wait: RCU wait allowing a new callback to get kthread's attention.
60  * @cbs_gbl_lock: Lock protecting callback list.
61  * @tasks_gp_mutex: Mutex protecting grace period, needed during mid-boot dead zone.
62  * @gp_func: This flavor's grace-period-wait function.
63  * @gp_state: Grace period's most recent state transition (debugging).
64  * @gp_sleep: Per-grace-period sleep to prevent CPU-bound looping.
65  * @init_fract: Initial backoff sleep interval.
66  * @gp_jiffies: Time of last @gp_state transition.
67  * @gp_start: Most recent grace-period start in jiffies.
68  * @tasks_gp_seq: Number of grace periods completed since boot in upper bits.
69  * @n_ipis: Number of IPIs sent to encourage grace periods to end.
70  * @kthread_ptr: This flavor's grace-period/callback-invocation kthread.
71  * @lazy_jiffies: Number of jiffies to allow callbacks to be lazy.
72  * @pregp_func: This flavor's pre-grace-period function (optional).
73  * @pertask_func: This flavor's per-task scan function (optional).
74  * @postscan_func: This flavor's post-task scan function (optional).
75  * @holdouts_func: This flavor's holdout-list scan function (optional).
76  * @postgp_func: This flavor's post-grace-period function (optional).
77  * @call_func: This flavor's call_rcu()-equivalent function.
78  * @wait_state: Task state for synchronous grace-period waits (default TASK_UNINTERRUPTIBLE).
79  * @rtpcpu: This flavor's rcu_tasks_percpu structure.
80  * @rtpcp_array: Array of pointers to rcu_tasks_percpu structure of CPUs in cpu_possible_mask.
81  * @percpu_enqueue_shift: Shift down CPU ID this much when enqueuing callbacks.
82  * @percpu_enqueue_lim: Number of per-CPU callback queues in use for enqueuing.
83  * @percpu_dequeue_lim: Number of per-CPU callback queues in use for dequeuing.
84  * @percpu_dequeue_gpseq: RCU grace-period number to propagate enqueue limit to dequeuers.
85  * @barrier_q_mutex: Serialize barrier operations.
86  * @barrier_q_count: Number of queues being waited on.
87  * @barrier_q_completion: Barrier wait/wakeup mechanism.
88  * @barrier_q_seq: Sequence number for barrier operations.
89  * @barrier_q_start: Most recent barrier start in jiffies.
90  * @name: This flavor's textual name.
91  * @kname: This flavor's kthread name.
92  */
93 struct rcu_tasks {
94 	struct rcuwait cbs_wait;
95 	raw_spinlock_t cbs_gbl_lock;
96 	struct mutex tasks_gp_mutex;
97 	int gp_state;
98 	int gp_sleep;
99 	int init_fract;
100 	unsigned long gp_jiffies;
101 	unsigned long gp_start;
102 	unsigned long tasks_gp_seq;
103 	unsigned long n_ipis;
104 	struct task_struct *kthread_ptr;
105 	unsigned long lazy_jiffies;
106 	rcu_tasks_gp_func_t gp_func;
107 	pregp_func_t pregp_func;
108 	pertask_func_t pertask_func;
109 	postscan_func_t postscan_func;
110 	holdouts_func_t holdouts_func;
111 	postgp_func_t postgp_func;
112 	call_rcu_func_t call_func;
113 	unsigned int wait_state;
114 	struct rcu_tasks_percpu __percpu *rtpcpu;
115 	struct rcu_tasks_percpu **rtpcp_array;
116 	int percpu_enqueue_shift;
117 	int percpu_enqueue_lim;
118 	int percpu_dequeue_lim;
119 	unsigned long percpu_dequeue_gpseq;
120 	struct mutex barrier_q_mutex;
121 	atomic_t barrier_q_count;
122 	struct completion barrier_q_completion;
123 	unsigned long barrier_q_seq;
124 	unsigned long barrier_q_start;
125 	char *name;
126 	char *kname;
127 };
128 
129 static void call_rcu_tasks_iw_wakeup(struct irq_work *iwp);
130 
131 #define DEFINE_RCU_TASKS(rt_name, gp, call, n)						\
132 static DEFINE_PER_CPU(struct rcu_tasks_percpu, rt_name ## __percpu) = {			\
133 	.lock = __RAW_SPIN_LOCK_UNLOCKED(rt_name ## __percpu.cbs_pcpu_lock),		\
134 	.rtp_irq_work = IRQ_WORK_INIT_HARD(call_rcu_tasks_iw_wakeup),			\
135 };											\
136 static struct rcu_tasks rt_name =							\
137 {											\
138 	.cbs_wait = __RCUWAIT_INITIALIZER(rt_name.wait),				\
139 	.cbs_gbl_lock = __RAW_SPIN_LOCK_UNLOCKED(rt_name.cbs_gbl_lock),			\
140 	.tasks_gp_mutex = __MUTEX_INITIALIZER(rt_name.tasks_gp_mutex),			\
141 	.gp_func = gp,									\
142 	.call_func = call,								\
143 	.wait_state = TASK_UNINTERRUPTIBLE,						\
144 	.rtpcpu = &rt_name ## __percpu,							\
145 	.lazy_jiffies = DIV_ROUND_UP(HZ, 4),						\
146 	.name = n,									\
147 	.percpu_enqueue_shift = order_base_2(CONFIG_NR_CPUS),				\
148 	.percpu_enqueue_lim = 1,							\
149 	.percpu_dequeue_lim = 1,							\
150 	.barrier_q_mutex = __MUTEX_INITIALIZER(rt_name.barrier_q_mutex),		\
151 	.barrier_q_seq = (0UL - 50UL) << RCU_SEQ_CTR_SHIFT,				\
152 	.kname = #rt_name,								\
153 }
154 
155 #ifdef CONFIG_TASKS_RCU
156 
157 /* Report delay of scan exiting tasklist in rcu_tasks_postscan(). */
158 static void tasks_rcu_exit_stall(struct timer_list *unused);
159 static DEFINE_TIMER(tasks_rcu_exit_stall_timer, tasks_rcu_exit_stall);
160 #endif
161 
162 /* Control stall timeouts.  Disable with <= 0, otherwise jiffies till stall. */
163 #define RCU_TASK_BOOT_STALL_TIMEOUT (HZ * 30)
164 #define RCU_TASK_STALL_TIMEOUT (HZ * 60 * 10)
165 static int rcu_task_stall_timeout __read_mostly = RCU_TASK_STALL_TIMEOUT;
166 module_param(rcu_task_stall_timeout, int, 0644);
167 #define RCU_TASK_STALL_INFO (HZ * 10)
168 static int rcu_task_stall_info __read_mostly = RCU_TASK_STALL_INFO;
169 module_param(rcu_task_stall_info, int, 0644);
170 static int rcu_task_stall_info_mult __read_mostly = 3;
171 module_param(rcu_task_stall_info_mult, int, 0444);
172 
173 static int rcu_task_enqueue_lim __read_mostly = -1;
174 module_param(rcu_task_enqueue_lim, int, 0444);
175 
176 static bool rcu_task_cb_adjust;
177 static int rcu_task_contend_lim __read_mostly = 100;
178 module_param(rcu_task_contend_lim, int, 0444);
179 static int rcu_task_collapse_lim __read_mostly = 10;
180 module_param(rcu_task_collapse_lim, int, 0444);
181 static int rcu_task_lazy_lim __read_mostly = 32;
182 module_param(rcu_task_lazy_lim, int, 0444);
183 
184 static int rcu_task_cpu_ids;
185 
186 /* RCU tasks grace-period state for debugging. */
187 #define RTGS_INIT		 0
188 #define RTGS_WAIT_WAIT_CBS	 1
189 #define RTGS_WAIT_GP		 2
190 #define RTGS_PRE_WAIT_GP	 3
191 #define RTGS_SCAN_TASKLIST	 4
192 #define RTGS_POST_SCAN_TASKLIST	 5
193 #define RTGS_WAIT_SCAN_HOLDOUTS	 6
194 #define RTGS_SCAN_HOLDOUTS	 7
195 #define RTGS_POST_GP		 8
196 #define RTGS_WAIT_READERS	 9
197 #define RTGS_INVOKE_CBS		10
198 #define RTGS_WAIT_CBS		11
199 #ifndef CONFIG_TINY_RCU
200 static const char * const rcu_tasks_gp_state_names[] = {
201 	"RTGS_INIT",
202 	"RTGS_WAIT_WAIT_CBS",
203 	"RTGS_WAIT_GP",
204 	"RTGS_PRE_WAIT_GP",
205 	"RTGS_SCAN_TASKLIST",
206 	"RTGS_POST_SCAN_TASKLIST",
207 	"RTGS_WAIT_SCAN_HOLDOUTS",
208 	"RTGS_SCAN_HOLDOUTS",
209 	"RTGS_POST_GP",
210 	"RTGS_WAIT_READERS",
211 	"RTGS_INVOKE_CBS",
212 	"RTGS_WAIT_CBS",
213 };
214 #endif /* #ifndef CONFIG_TINY_RCU */
215 
216 ////////////////////////////////////////////////////////////////////////
217 //
218 // Generic code.
219 
220 static void rcu_tasks_invoke_cbs_wq(struct work_struct *wp);
221 
222 /* Record grace-period phase and time. */
set_tasks_gp_state(struct rcu_tasks * rtp,int newstate)223 static void set_tasks_gp_state(struct rcu_tasks *rtp, int newstate)
224 {
225 	rtp->gp_state = newstate;
226 	rtp->gp_jiffies = jiffies;
227 }
228 
229 #ifndef CONFIG_TINY_RCU
230 /* Return state name. */
tasks_gp_state_getname(struct rcu_tasks * rtp)231 static const char *tasks_gp_state_getname(struct rcu_tasks *rtp)
232 {
233 	int i = data_race(rtp->gp_state); // Let KCSAN detect update races
234 	int j = READ_ONCE(i); // Prevent the compiler from reading twice
235 
236 	if (j >= ARRAY_SIZE(rcu_tasks_gp_state_names))
237 		return "???";
238 	return rcu_tasks_gp_state_names[j];
239 }
240 #endif /* #ifndef CONFIG_TINY_RCU */
241 
242 // Initialize per-CPU callback lists for the specified flavor of
243 // Tasks RCU.  Do not enqueue callbacks before this function is invoked.
cblist_init_generic(struct rcu_tasks * rtp)244 static void cblist_init_generic(struct rcu_tasks *rtp)
245 {
246 	int cpu;
247 	int lim;
248 	int shift;
249 	int maxcpu;
250 	int index = 0;
251 
252 	if (rcu_task_enqueue_lim < 0) {
253 		rcu_task_enqueue_lim = 1;
254 		rcu_task_cb_adjust = true;
255 	} else if (rcu_task_enqueue_lim == 0) {
256 		rcu_task_enqueue_lim = 1;
257 	}
258 	lim = rcu_task_enqueue_lim;
259 
260 	rtp->rtpcp_array = kzalloc_objs(struct rcu_tasks_percpu *,
261 					num_possible_cpus());
262 	BUG_ON(!rtp->rtpcp_array);
263 
264 	for_each_possible_cpu(cpu) {
265 		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
266 
267 		WARN_ON_ONCE(!rtpcp);
268 		if (cpu)
269 			raw_spin_lock_init(&ACCESS_PRIVATE(rtpcp, lock));
270 		if (rcu_segcblist_empty(&rtpcp->cblist))
271 			rcu_segcblist_init(&rtpcp->cblist);
272 		INIT_WORK(&rtpcp->rtp_work, rcu_tasks_invoke_cbs_wq);
273 		rtpcp->cpu = cpu;
274 		rtpcp->rtpp = rtp;
275 		rtpcp->index = index;
276 		rtp->rtpcp_array[index] = rtpcp;
277 		index++;
278 		if (!rtpcp->rtp_blkd_tasks.next)
279 			INIT_LIST_HEAD(&rtpcp->rtp_blkd_tasks);
280 		if (!rtpcp->rtp_exit_list.next)
281 			INIT_LIST_HEAD(&rtpcp->rtp_exit_list);
282 		rtpcp->barrier_q_head.next = &rtpcp->barrier_q_head;
283 		maxcpu = cpu;
284 	}
285 
286 	rcu_task_cpu_ids = maxcpu + 1;
287 	if (lim > rcu_task_cpu_ids)
288 		lim = rcu_task_cpu_ids;
289 	shift = ilog2(rcu_task_cpu_ids / lim);
290 	if (((rcu_task_cpu_ids - 1) >> shift) >= lim)
291 		shift++;
292 	rtp->percpu_enqueue_shift = shift;
293 	rtp->percpu_dequeue_lim = lim;
294 	rtp->percpu_enqueue_lim = lim;
295 
296 	pr_info("%s: Setting shift to %d and lim to %d rcu_task_cb_adjust=%d rcu_task_cpu_ids=%d.\n",
297 			rtp->name, data_race(rtp->percpu_enqueue_shift), data_race(rtp->percpu_enqueue_lim),
298 			rcu_task_cb_adjust, rcu_task_cpu_ids);
299 }
300 
301 // Compute wakeup time for lazy callback timer.
rcu_tasks_lazy_time(struct rcu_tasks * rtp)302 static unsigned long rcu_tasks_lazy_time(struct rcu_tasks *rtp)
303 {
304 	return jiffies + rtp->lazy_jiffies;
305 }
306 
307 // Timer handler that unlazifies lazy callbacks.
call_rcu_tasks_generic_timer(struct timer_list * tlp)308 static void call_rcu_tasks_generic_timer(struct timer_list *tlp)
309 {
310 	unsigned long flags;
311 	bool needwake = false;
312 	struct rcu_tasks *rtp;
313 	struct rcu_tasks_percpu *rtpcp = timer_container_of(rtpcp, tlp,
314 						            lazy_timer);
315 
316 	rtp = rtpcp->rtpp;
317 	raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
318 	if (!rcu_segcblist_empty(&rtpcp->cblist) && rtp->lazy_jiffies) {
319 		if (!rtpcp->urgent_gp)
320 			rtpcp->urgent_gp = 1;
321 		needwake = true;
322 		mod_timer(&rtpcp->lazy_timer, rcu_tasks_lazy_time(rtp));
323 	}
324 	raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
325 	if (needwake)
326 		rcuwait_wake_up(&rtp->cbs_wait);
327 }
328 
329 // IRQ-work handler that does deferred wakeup for call_rcu_tasks_generic().
call_rcu_tasks_iw_wakeup(struct irq_work * iwp)330 static void call_rcu_tasks_iw_wakeup(struct irq_work *iwp)
331 {
332 	struct rcu_tasks *rtp;
333 	struct rcu_tasks_percpu *rtpcp = container_of(iwp, struct rcu_tasks_percpu, rtp_irq_work);
334 
335 	rtp = rtpcp->rtpp;
336 	rcuwait_wake_up(&rtp->cbs_wait);
337 }
338 
339 // Enqueue a callback for the specified flavor of Tasks RCU.
call_rcu_tasks_generic(struct rcu_head * rhp,rcu_callback_t func,struct rcu_tasks * rtp)340 static void call_rcu_tasks_generic(struct rcu_head *rhp, rcu_callback_t func,
341 				   struct rcu_tasks *rtp)
342 {
343 	int chosen_cpu;
344 	unsigned long flags;
345 	bool havekthread = smp_load_acquire(&rtp->kthread_ptr);
346 	int ideal_cpu;
347 	unsigned long j;
348 	bool needadjust = false;
349 	bool needwake;
350 	struct rcu_tasks_percpu *rtpcp;
351 
352 	rhp->next = NULL;
353 	rhp->func = func;
354 	local_irq_save(flags);
355 	rcu_read_lock();
356 	ideal_cpu = smp_processor_id() >> READ_ONCE(rtp->percpu_enqueue_shift);
357 	chosen_cpu = cpumask_next(ideal_cpu - 1, cpu_possible_mask);
358 	WARN_ON_ONCE(chosen_cpu >= rcu_task_cpu_ids);
359 	rtpcp = per_cpu_ptr(rtp->rtpcpu, chosen_cpu);
360 	if (!raw_spin_trylock_rcu_node(rtpcp)) { // irqs already disabled.
361 		raw_spin_lock_rcu_node(rtpcp); // irqs already disabled.
362 		j = jiffies;
363 		if (rtpcp->rtp_jiffies != j) {
364 			rtpcp->rtp_jiffies = j;
365 			rtpcp->rtp_n_lock_retries = 0;
366 		}
367 		if (rcu_task_cb_adjust && ++rtpcp->rtp_n_lock_retries > rcu_task_contend_lim &&
368 		    READ_ONCE(rtp->percpu_enqueue_lim) != rcu_task_cpu_ids)
369 			needadjust = true;  // Defer adjustment to avoid deadlock.
370 	}
371 	// Queuing callbacks before initialization not yet supported.
372 	if (WARN_ON_ONCE(!rcu_segcblist_is_enabled(&rtpcp->cblist)))
373 		rcu_segcblist_init(&rtpcp->cblist);
374 	needwake = (!havekthread && rcu_segcblist_empty(&rtpcp->cblist)) ||
375 		   (func == wakeme_after_rcu) ||
376 		   (rcu_segcblist_n_cbs(&rtpcp->cblist) == rcu_task_lazy_lim);
377 	if (havekthread && !needwake && !timer_pending(&rtpcp->lazy_timer)) {
378 		if (rtp->lazy_jiffies)
379 			mod_timer(&rtpcp->lazy_timer, rcu_tasks_lazy_time(rtp));
380 		else
381 			needwake = rcu_segcblist_empty(&rtpcp->cblist);
382 	}
383 	if (needwake)
384 		rtpcp->urgent_gp = 3;
385 	rcu_segcblist_enqueue(&rtpcp->cblist, rhp);
386 	raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
387 	if (unlikely(needadjust)) {
388 		raw_spin_lock_irqsave(&rtp->cbs_gbl_lock, flags);
389 		if (rtp->percpu_enqueue_lim != rcu_task_cpu_ids) {
390 			WRITE_ONCE(rtp->percpu_enqueue_shift, 0);
391 			WRITE_ONCE(rtp->percpu_dequeue_lim, rcu_task_cpu_ids);
392 			smp_store_release(&rtp->percpu_enqueue_lim, rcu_task_cpu_ids);
393 			pr_info("Switching %s to per-CPU callback queuing.\n", rtp->name);
394 		}
395 		raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags);
396 	}
397 	rcu_read_unlock();
398 	// We can't create the kthread with interrupts disabled because a
399 	// scheduler spinlock might be held, so kthread creation is deferred
400 	// until core_initcall() time.  Similarly, wakeups are deferred using
401 	// irq_work in order to avoid potential scheduler-lock-deadlock
402 	// lockdep splats.
403 	if (needwake && READ_ONCE(rtp->kthread_ptr))
404 		irq_work_queue(&rtpcp->rtp_irq_work);
405 }
406 
407 // RCU callback function for rcu_barrier_tasks_generic().
rcu_barrier_tasks_generic_cb(struct rcu_head * rhp)408 static void rcu_barrier_tasks_generic_cb(struct rcu_head *rhp)
409 {
410 	struct rcu_tasks *rtp;
411 	struct rcu_tasks_percpu *rtpcp;
412 
413 	rhp->next = rhp; // Mark the callback as having been invoked.
414 	rtpcp = container_of(rhp, struct rcu_tasks_percpu, barrier_q_head);
415 	rtp = rtpcp->rtpp;
416 	if (atomic_dec_and_test(&rtp->barrier_q_count))
417 		complete(&rtp->barrier_q_completion);
418 }
419 
420 // Wait for all in-flight callbacks for the specified RCU Tasks flavor.
421 // Operates in a manner similar to rcu_barrier().
rcu_barrier_tasks_generic(struct rcu_tasks * rtp)422 static void __maybe_unused rcu_barrier_tasks_generic(struct rcu_tasks *rtp)
423 {
424 	int cpu;
425 	unsigned long flags;
426 	struct rcu_tasks_percpu *rtpcp;
427 	unsigned long s = rcu_seq_snap(&rtp->barrier_q_seq);
428 
429 	mutex_lock(&rtp->barrier_q_mutex);
430 	if (rcu_seq_done(&rtp->barrier_q_seq, s)) {
431 		smp_mb();
432 		mutex_unlock(&rtp->barrier_q_mutex);
433 		return;
434 	}
435 	rtp->barrier_q_start = jiffies;
436 	rcu_seq_start(&rtp->barrier_q_seq);
437 	init_completion(&rtp->barrier_q_completion);
438 	atomic_set(&rtp->barrier_q_count, 2);
439 	for_each_possible_cpu(cpu) {
440 		if (cpu >= smp_load_acquire(&rtp->percpu_dequeue_lim))
441 			break;
442 		rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
443 		rtpcp->barrier_q_head.func = rcu_barrier_tasks_generic_cb;
444 		raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
445 		if (rcu_segcblist_entrain(&rtpcp->cblist, &rtpcp->barrier_q_head))
446 			atomic_inc(&rtp->barrier_q_count);
447 		raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
448 	}
449 	if (atomic_sub_and_test(2, &rtp->barrier_q_count))
450 		complete(&rtp->barrier_q_completion);
451 	wait_for_completion(&rtp->barrier_q_completion);
452 	rcu_seq_end(&rtp->barrier_q_seq);
453 	mutex_unlock(&rtp->barrier_q_mutex);
454 }
455 
456 // Advance callbacks and indicate whether either a grace period or
457 // callback invocation is needed.
rcu_tasks_need_gpcb(struct rcu_tasks * rtp)458 static int rcu_tasks_need_gpcb(struct rcu_tasks *rtp)
459 {
460 	int cpu;
461 	int dequeue_limit;
462 	unsigned long flags;
463 	bool gpdone = poll_state_synchronize_rcu(rtp->percpu_dequeue_gpseq);
464 	long n;
465 	long ncbs = 0;
466 	long ncbsnz = 0;
467 	int needgpcb = 0;
468 
469 	dequeue_limit = smp_load_acquire(&rtp->percpu_dequeue_lim);
470 	for (cpu = 0; cpu < dequeue_limit; cpu++) {
471 		if (!cpu_possible(cpu))
472 			continue;
473 		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
474 
475 		/* Advance and accelerate any new callbacks. */
476 		if (!rcu_segcblist_n_cbs(&rtpcp->cblist))
477 			continue;
478 		raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
479 		// Should we shrink down to a single callback queue?
480 		n = rcu_segcblist_n_cbs(&rtpcp->cblist);
481 		if (n) {
482 			ncbs += n;
483 			if (cpu > 0)
484 				ncbsnz += n;
485 		}
486 		srcu_segcblist_advance(&rtpcp->cblist, rcu_seq_current(&rtp->tasks_gp_seq));
487 		(void)srcu_segcblist_accelerate(&rtpcp->cblist, rcu_seq_snap(&rtp->tasks_gp_seq));
488 		if (rtpcp->urgent_gp > 0 && rcu_segcblist_pend_cbs(&rtpcp->cblist)) {
489 			if (rtp->lazy_jiffies)
490 				rtpcp->urgent_gp--;
491 			needgpcb |= 0x3;
492 		} else if (rcu_segcblist_empty(&rtpcp->cblist)) {
493 			rtpcp->urgent_gp = 0;
494 		}
495 		if (rcu_segcblist_ready_cbs(&rtpcp->cblist))
496 			needgpcb |= 0x1;
497 		raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
498 	}
499 
500 	// Shrink down to a single callback queue if appropriate.
501 	// This is done in two stages: (1) If there are no more than
502 	// rcu_task_collapse_lim callbacks on CPU 0 and none on any other
503 	// CPU, limit enqueueing to CPU 0.  (2) After an RCU grace period,
504 	// if there has not been an increase in callbacks, limit dequeuing
505 	// to CPU 0.  Note the matching RCU read-side critical section in
506 	// call_rcu_tasks_generic().
507 	if (rcu_task_cb_adjust && ncbs <= rcu_task_collapse_lim) {
508 		raw_spin_lock_irqsave(&rtp->cbs_gbl_lock, flags);
509 		if (rtp->percpu_enqueue_lim > 1) {
510 			WRITE_ONCE(rtp->percpu_enqueue_shift, order_base_2(rcu_task_cpu_ids));
511 			smp_store_release(&rtp->percpu_enqueue_lim, 1);
512 			rtp->percpu_dequeue_gpseq = get_state_synchronize_rcu();
513 			gpdone = false;
514 			pr_info("Starting switch %s to CPU-0 callback queuing.\n", rtp->name);
515 		}
516 		raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags);
517 	}
518 	if (rcu_task_cb_adjust && !ncbsnz && gpdone) {
519 		raw_spin_lock_irqsave(&rtp->cbs_gbl_lock, flags);
520 		if (rtp->percpu_enqueue_lim < rtp->percpu_dequeue_lim) {
521 			WRITE_ONCE(rtp->percpu_dequeue_lim, 1);
522 			pr_info("Completing switch %s to CPU-0 callback queuing.\n", rtp->name);
523 		}
524 		if (rtp->percpu_dequeue_lim == 1) {
525 			for (cpu = rtp->percpu_dequeue_lim; cpu < rcu_task_cpu_ids; cpu++) {
526 				if (!cpu_possible(cpu))
527 					continue;
528 				struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
529 
530 				WARN_ON_ONCE(rcu_segcblist_n_cbs(&rtpcp->cblist));
531 			}
532 		}
533 		raw_spin_unlock_irqrestore(&rtp->cbs_gbl_lock, flags);
534 	}
535 
536 	return needgpcb;
537 }
538 
539 // Advance callbacks and invoke any that are ready.
rcu_tasks_invoke_cbs(struct rcu_tasks * rtp,struct rcu_tasks_percpu * rtpcp)540 static void rcu_tasks_invoke_cbs(struct rcu_tasks *rtp, struct rcu_tasks_percpu *rtpcp)
541 {
542 	int cpuwq;
543 	unsigned long flags;
544 	int len;
545 	int index;
546 	struct rcu_head *rhp;
547 	struct rcu_cblist rcl = RCU_CBLIST_INITIALIZER(rcl);
548 	struct rcu_tasks_percpu *rtpcp_next;
549 
550 	index = rtpcp->index * 2 + 1;
551 	if (index < num_possible_cpus()) {
552 		rtpcp_next = rtp->rtpcp_array[index];
553 		if (rtpcp_next->cpu < smp_load_acquire(&rtp->percpu_dequeue_lim)) {
554 			cpuwq = rcu_cpu_beenfullyonline(rtpcp_next->cpu) ? rtpcp_next->cpu : WORK_CPU_UNBOUND;
555 			queue_work_on(cpuwq, system_percpu_wq, &rtpcp_next->rtp_work);
556 			index++;
557 			if (index < num_possible_cpus()) {
558 				rtpcp_next = rtp->rtpcp_array[index];
559 				if (rtpcp_next->cpu < smp_load_acquire(&rtp->percpu_dequeue_lim)) {
560 					cpuwq = rcu_cpu_beenfullyonline(rtpcp_next->cpu) ? rtpcp_next->cpu : WORK_CPU_UNBOUND;
561 					queue_work_on(cpuwq, system_percpu_wq, &rtpcp_next->rtp_work);
562 				}
563 			}
564 		}
565 	}
566 
567 	if (rcu_segcblist_empty(&rtpcp->cblist))
568 		return;
569 	raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
570 	srcu_segcblist_advance(&rtpcp->cblist, rcu_seq_current(&rtp->tasks_gp_seq));
571 	rcu_segcblist_extract_done_cbs(&rtpcp->cblist, &rcl);
572 	raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
573 	len = rcl.len;
574 	for (rhp = rcu_cblist_dequeue(&rcl); rhp; rhp = rcu_cblist_dequeue(&rcl)) {
575 		debug_rcu_head_callback(rhp);
576 		local_bh_disable();
577 		rhp->func(rhp);
578 		local_bh_enable();
579 		cond_resched();
580 	}
581 	raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
582 	rcu_segcblist_add_len(&rtpcp->cblist, -len);
583 	(void)srcu_segcblist_accelerate(&rtpcp->cblist, rcu_seq_snap(&rtp->tasks_gp_seq));
584 	raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
585 }
586 
587 // Workqueue flood to advance callbacks and invoke any that are ready.
rcu_tasks_invoke_cbs_wq(struct work_struct * wp)588 static void rcu_tasks_invoke_cbs_wq(struct work_struct *wp)
589 {
590 	struct rcu_tasks *rtp;
591 	struct rcu_tasks_percpu *rtpcp = container_of(wp, struct rcu_tasks_percpu, rtp_work);
592 
593 	rtp = rtpcp->rtpp;
594 	rcu_tasks_invoke_cbs(rtp, rtpcp);
595 }
596 
597 // Wait for one grace period.
rcu_tasks_one_gp(struct rcu_tasks * rtp,bool midboot)598 static void rcu_tasks_one_gp(struct rcu_tasks *rtp, bool midboot)
599 {
600 	int needgpcb;
601 
602 	mutex_lock(&rtp->tasks_gp_mutex);
603 
604 	// If there were none, wait a bit and start over.
605 	if (unlikely(midboot)) {
606 		needgpcb = 0x2;
607 	} else {
608 		mutex_unlock(&rtp->tasks_gp_mutex);
609 		set_tasks_gp_state(rtp, RTGS_WAIT_CBS);
610 		rcuwait_wait_event(&rtp->cbs_wait,
611 				   (needgpcb = rcu_tasks_need_gpcb(rtp)),
612 				   TASK_IDLE);
613 		mutex_lock(&rtp->tasks_gp_mutex);
614 	}
615 
616 	if (needgpcb & 0x2) {
617 		// Wait for one grace period.
618 		set_tasks_gp_state(rtp, RTGS_WAIT_GP);
619 		rtp->gp_start = jiffies;
620 		rcu_seq_start(&rtp->tasks_gp_seq);
621 		rtp->gp_func(rtp);
622 		rcu_seq_end(&rtp->tasks_gp_seq);
623 	}
624 
625 	// Invoke callbacks.
626 	set_tasks_gp_state(rtp, RTGS_INVOKE_CBS);
627 	rcu_tasks_invoke_cbs(rtp, per_cpu_ptr(rtp->rtpcpu, 0));
628 	mutex_unlock(&rtp->tasks_gp_mutex);
629 }
630 
631 // RCU-tasks kthread that detects grace periods and invokes callbacks.
rcu_tasks_kthread(void * arg)632 static int __noreturn rcu_tasks_kthread(void *arg)
633 {
634 	int cpu;
635 	struct rcu_tasks *rtp = arg;
636 
637 	for_each_possible_cpu(cpu) {
638 		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
639 
640 		timer_setup(&rtpcp->lazy_timer, call_rcu_tasks_generic_timer, 0);
641 		rtpcp->urgent_gp = 1;
642 	}
643 
644 	/* Run on housekeeping CPUs by default.  Sysadm can move if desired. */
645 	housekeeping_affine(current, HK_TYPE_RCU);
646 	smp_store_release(&rtp->kthread_ptr, current); // Let GPs start!
647 
648 	/*
649 	 * Each pass through the following loop makes one check for
650 	 * newly arrived callbacks, and, if there are some, waits for
651 	 * one RCU-tasks grace period and then invokes the callbacks.
652 	 * This loop is terminated by the system going down.  ;-)
653 	 */
654 	for (;;) {
655 		// Wait for one grace period and invoke any callbacks
656 		// that are ready.
657 		rcu_tasks_one_gp(rtp, false);
658 
659 		// Paranoid sleep to keep this from entering a tight loop.
660 		schedule_timeout_idle(rtp->gp_sleep);
661 	}
662 }
663 
664 // Wait for a grace period for the specified flavor of Tasks RCU.
synchronize_rcu_tasks_generic(struct rcu_tasks * rtp)665 static void synchronize_rcu_tasks_generic(struct rcu_tasks *rtp)
666 {
667 	/* Complain if the scheduler has not started.  */
668 	if (WARN_ONCE(rcu_scheduler_active == RCU_SCHEDULER_INACTIVE,
669 			 "synchronize_%s() called too soon", rtp->name))
670 		return;
671 
672 	// If the grace-period kthread is running, use it.
673 	if (READ_ONCE(rtp->kthread_ptr)) {
674 		wait_rcu_gp_state(rtp->wait_state, rtp->call_func);
675 		return;
676 	}
677 	rcu_tasks_one_gp(rtp, true);
678 }
679 
680 /* Spawn RCU-tasks grace-period kthread. */
rcu_spawn_tasks_kthread_generic(struct rcu_tasks * rtp)681 static void __init rcu_spawn_tasks_kthread_generic(struct rcu_tasks *rtp)
682 {
683 	struct task_struct *t;
684 
685 	t = kthread_run(rcu_tasks_kthread, rtp, "%s_kthread", rtp->kname);
686 	if (WARN_ONCE(IS_ERR(t), "%s: Could not start %s grace-period kthread, OOM is now expected behavior\n", __func__, rtp->name))
687 		return;
688 }
689 
690 #ifndef CONFIG_TINY_RCU
691 
692 /*
693  * Print any non-default Tasks RCU settings.
694  */
rcu_tasks_bootup_oddness(void)695 static void __init rcu_tasks_bootup_oddness(void)
696 {
697 #if defined(CONFIG_TASKS_RCU) || defined(CONFIG_TASKS_TRACE_RCU)
698 	int rtsimc;
699 
700 	if (rcu_task_stall_timeout != RCU_TASK_STALL_TIMEOUT)
701 		pr_info("\tTasks-RCU CPU stall warnings timeout set to %d (rcu_task_stall_timeout).\n", rcu_task_stall_timeout);
702 	rtsimc = clamp(rcu_task_stall_info_mult, 1, 10);
703 	if (rtsimc != rcu_task_stall_info_mult) {
704 		pr_info("\tTasks-RCU CPU stall info multiplier clamped to %d (rcu_task_stall_info_mult).\n", rtsimc);
705 		rcu_task_stall_info_mult = rtsimc;
706 	}
707 #endif /* #ifdef CONFIG_TASKS_RCU */
708 #ifdef CONFIG_TASKS_RCU
709 	pr_info("\tTrampoline variant of Tasks RCU enabled.\n");
710 #endif /* #ifdef CONFIG_TASKS_RCU */
711 #ifdef CONFIG_TASKS_RUDE_RCU
712 	pr_info("\tRude variant of Tasks RCU enabled.\n");
713 #endif /* #ifdef CONFIG_TASKS_RUDE_RCU */
714 #ifdef CONFIG_TASKS_TRACE_RCU
715 	pr_info("\tTracing variant of Tasks RCU enabled.\n");
716 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
717 }
718 
719 /* Dump out rcutorture-relevant state common to all RCU-tasks flavors. */
show_rcu_tasks_generic_gp_kthread(struct rcu_tasks * rtp,char * s)720 static void show_rcu_tasks_generic_gp_kthread(struct rcu_tasks *rtp, char *s)
721 {
722 	int cpu;
723 	bool havecbs = false;
724 	bool haveurgent = false;
725 	bool haveurgentcbs = false;
726 	bool havependtimer = false;
727 
728 	for_each_possible_cpu(cpu) {
729 		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
730 
731 		if (!data_race(rcu_segcblist_empty(&rtpcp->cblist)))
732 			havecbs = true;
733 		if (data_race(rtpcp->urgent_gp))
734 			haveurgent = true;
735 		if (!data_race(rcu_segcblist_empty(&rtpcp->cblist)) && data_race(rtpcp->urgent_gp))
736 			haveurgentcbs = true;
737 		if (data_race(timer_pending(&rtpcp->lazy_timer)))
738 			havependtimer = true;
739 		if (havecbs && haveurgent && haveurgentcbs && havependtimer)
740 			break;
741 	}
742 	pr_info("%s: %s(%d) since %lu g:%lu i:%lu %c%c%c%c%c l:%lu %s\n",
743 		rtp->kname,
744 		tasks_gp_state_getname(rtp), data_race(rtp->gp_state),
745 		jiffies - data_race(rtp->gp_jiffies),
746 		data_race(rcu_seq_current(&rtp->tasks_gp_seq)),
747 		data_race(rtp->n_ipis),
748 		".k"[!!data_race(rtp->kthread_ptr)],
749 		".C"[havecbs],
750 		".u"[haveurgent],
751 		".U"[haveurgentcbs],
752 		".P"[havependtimer],
753 		rtp->lazy_jiffies,
754 		s);
755 }
756 
757 /* Dump out more rcutorture-relevant state common to all RCU-tasks flavors. */
rcu_tasks_torture_stats_print_generic(struct rcu_tasks * rtp,char * tt,char * tf,char * tst)758 static void rcu_tasks_torture_stats_print_generic(struct rcu_tasks *rtp, char *tt,
759 						  char *tf, char *tst)
760 {
761 	cpumask_var_t cm;
762 	int cpu;
763 	bool gotcb = false;
764 	unsigned long j = jiffies;
765 
766 	pr_alert("%s%s Tasks%s RCU g%ld gp_start %lu gp_jiffies %lu gp_state %d (%s).\n",
767 		 tt, tf, tst, data_race(rtp->tasks_gp_seq),
768 		 j - data_race(rtp->gp_start), j - data_race(rtp->gp_jiffies),
769 		 data_race(rtp->gp_state), tasks_gp_state_getname(rtp));
770 	pr_alert("\tEnqueue shift %d limit %d Dequeue limit %d gpseq %lu.\n",
771 		 data_race(rtp->percpu_enqueue_shift),
772 		 data_race(rtp->percpu_enqueue_lim),
773 		 data_race(rtp->percpu_dequeue_lim),
774 		 data_race(rtp->percpu_dequeue_gpseq));
775 	(void)zalloc_cpumask_var(&cm, GFP_KERNEL);
776 	pr_alert("\tCallback counts:");
777 	for_each_possible_cpu(cpu) {
778 		long n;
779 		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rtp->rtpcpu, cpu);
780 
781 		if (cpumask_available(cm) && !rcu_barrier_cb_is_done(&rtpcp->barrier_q_head))
782 			cpumask_set_cpu(cpu, cm);
783 		n = rcu_segcblist_n_cbs(&rtpcp->cblist);
784 		if (!n)
785 			continue;
786 		pr_cont(" %d:%ld", cpu, n);
787 		gotcb = true;
788 	}
789 	if (gotcb)
790 		pr_cont(".\n");
791 	else
792 		pr_cont(" (none).\n");
793 	pr_alert("\tBarrier seq %lu start %lu count %d holdout CPUs ",
794 		 data_race(rtp->barrier_q_seq), j - data_race(rtp->barrier_q_start),
795 		 atomic_read(&rtp->barrier_q_count));
796 	if (cpumask_available(cm) && !cpumask_empty(cm))
797 		pr_cont(" %*pbl.\n", cpumask_pr_args(cm));
798 	else
799 		pr_cont("(none).\n");
800 	free_cpumask_var(cm);
801 }
802 
803 #endif // #ifndef CONFIG_TINY_RCU
804 
805 #if defined(CONFIG_TASKS_RCU)
806 
807 ////////////////////////////////////////////////////////////////////////
808 //
809 // Shared code between task-list-scanning variants of Tasks RCU.
810 
811 /* Wait for one RCU-tasks grace period. */
rcu_tasks_wait_gp(struct rcu_tasks * rtp)812 static void rcu_tasks_wait_gp(struct rcu_tasks *rtp)
813 {
814 	struct task_struct *g;
815 	int fract;
816 	LIST_HEAD(holdouts);
817 	unsigned long j;
818 	unsigned long lastinfo;
819 	unsigned long lastreport;
820 	bool reported = false;
821 	int rtsi;
822 	struct task_struct *t;
823 
824 	set_tasks_gp_state(rtp, RTGS_PRE_WAIT_GP);
825 	rtp->pregp_func(&holdouts);
826 
827 	/*
828 	 * There were callbacks, so we need to wait for an RCU-tasks
829 	 * grace period.  Start off by scanning the task list for tasks
830 	 * that are not already voluntarily blocked.  Mark these tasks
831 	 * and make a list of them in holdouts.
832 	 */
833 	set_tasks_gp_state(rtp, RTGS_SCAN_TASKLIST);
834 	if (rtp->pertask_func) {
835 		rcu_read_lock();
836 		for_each_process_thread(g, t)
837 			rtp->pertask_func(t, &holdouts);
838 		rcu_read_unlock();
839 	}
840 
841 	set_tasks_gp_state(rtp, RTGS_POST_SCAN_TASKLIST);
842 	rtp->postscan_func(&holdouts);
843 
844 	/*
845 	 * Each pass through the following loop scans the list of holdout
846 	 * tasks, removing any that are no longer holdouts.  When the list
847 	 * is empty, we are done.
848 	 */
849 	lastreport = jiffies;
850 	lastinfo = lastreport;
851 	rtsi = READ_ONCE(rcu_task_stall_info);
852 
853 	// Start off with initial wait and slowly back off to 1 HZ wait.
854 	fract = rtp->init_fract;
855 
856 	while (!list_empty(&holdouts)) {
857 		ktime_t exp;
858 		bool firstreport;
859 		bool needreport;
860 		int rtst;
861 
862 		// Slowly back off waiting for holdouts
863 		set_tasks_gp_state(rtp, RTGS_WAIT_SCAN_HOLDOUTS);
864 		if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
865 			schedule_timeout_idle(fract);
866 		} else {
867 			exp = jiffies_to_nsecs(fract);
868 			__set_current_state(TASK_IDLE);
869 			schedule_hrtimeout_range(&exp, jiffies_to_nsecs(HZ / 2), HRTIMER_MODE_REL_HARD);
870 		}
871 
872 		if (fract < HZ)
873 			fract++;
874 
875 		rtst = READ_ONCE(rcu_task_stall_timeout);
876 		needreport = rtst > 0 && time_after(jiffies, lastreport + rtst);
877 		if (needreport) {
878 			lastreport = jiffies;
879 			reported = true;
880 		}
881 		firstreport = true;
882 		WARN_ON(signal_pending(current));
883 		set_tasks_gp_state(rtp, RTGS_SCAN_HOLDOUTS);
884 		rtp->holdouts_func(&holdouts, needreport, &firstreport);
885 
886 		// Print pre-stall informational messages if needed.
887 		j = jiffies;
888 		if (rtsi > 0 && !reported && time_after(j, lastinfo + rtsi)) {
889 			lastinfo = j;
890 			rtsi = rtsi * rcu_task_stall_info_mult;
891 			pr_info("%s: %s grace period number %lu (since boot) is %lu jiffies old.\n",
892 				__func__, rtp->kname, rtp->tasks_gp_seq, j - rtp->gp_start);
893 		}
894 	}
895 
896 	set_tasks_gp_state(rtp, RTGS_POST_GP);
897 	rtp->postgp_func(rtp);
898 }
899 
900 #endif /* #if defined(CONFIG_TASKS_RCU) */
901 
902 #ifdef CONFIG_TASKS_RCU
903 
904 ////////////////////////////////////////////////////////////////////////
905 //
906 // Simple variant of RCU whose quiescent states are voluntary context
907 // switch, cond_resched_tasks_rcu_qs(), user-space execution, and idle.
908 // As such, grace periods can take one good long time.  There are no
909 // read-side primitives similar to rcu_read_lock() and rcu_read_unlock()
910 // because this implementation is intended to get the system into a safe
911 // state for some of the manipulations involved in tracing and the like.
912 // Finally, this implementation does not support high call_rcu_tasks()
913 // rates from multiple CPUs.  If this is required, per-CPU callback lists
914 // will be needed.
915 //
916 // The implementation uses rcu_tasks_wait_gp(), which relies on function
917 // pointers in the rcu_tasks structure.  The rcu_spawn_tasks_kthread()
918 // function sets these function pointers up so that rcu_tasks_wait_gp()
919 // invokes these functions in this order:
920 //
921 // rcu_tasks_pregp_step():
922 //	Invokes synchronize_rcu() in order to wait for all in-flight
923 //	t->on_rq and t->nvcsw transitions to complete.	This works because
924 //	all such transitions are carried out with interrupts disabled.
925 // rcu_tasks_pertask(), invoked on every non-idle task:
926 //	For every runnable non-idle task other than the current one, use
927 //	get_task_struct() to pin down that task, snapshot that task's
928 //	number of voluntary context switches, and add that task to the
929 //	holdout list.
930 // rcu_tasks_postscan():
931 //	Gather per-CPU lists of tasks in do_exit() to ensure that all
932 //	tasks that were in the process of exiting (and which thus might
933 //	not know to synchronize with this RCU Tasks grace period) have
934 //	completed exiting.  The synchronize_rcu() in rcu_tasks_postgp()
935 //	will take care of any tasks stuck in the non-preemptible region
936 //	of do_exit() following its call to exit_tasks_rcu_finish().
937 // check_all_holdout_tasks(), repeatedly until holdout list is empty:
938 //	Scans the holdout list, attempting to identify a quiescent state
939 //	for each task on the list.  If there is a quiescent state, the
940 //	corresponding task is removed from the holdout list.
941 // rcu_tasks_postgp():
942 //	Invokes synchronize_rcu() in order to ensure that all prior
943 //	t->on_rq and t->nvcsw transitions are seen by all CPUs and tasks
944 //	to have happened before the end of this RCU Tasks grace period.
945 //	Again, this works because all such transitions are carried out
946 //	with interrupts disabled.
947 //
948 // For each exiting task, the exit_tasks_rcu_start() and
949 // exit_tasks_rcu_finish() functions add and remove, respectively, the
950 // current task to a per-CPU list of tasks that rcu_tasks_postscan() must
951 // wait on.  This is necessary because rcu_tasks_postscan() must wait on
952 // tasks that have already been removed from the global list of tasks.
953 //
954 // Pre-grace-period update-side code is ordered before the grace
955 // via the raw_spin_lock.*rcu_node().  Pre-grace-period read-side code
956 // is ordered before the grace period via synchronize_rcu() call in
957 // rcu_tasks_pregp_step() and by the scheduler's locks and interrupt
958 // disabling.
959 
960 /* Pre-grace-period preparation. */
rcu_tasks_pregp_step(struct list_head * hop)961 static void rcu_tasks_pregp_step(struct list_head *hop)
962 {
963 	/*
964 	 * Wait for all pre-existing t->on_rq and t->nvcsw transitions
965 	 * to complete.  Invoking synchronize_rcu() suffices because all
966 	 * these transitions occur with interrupts disabled.  Without this
967 	 * synchronize_rcu(), a read-side critical section that started
968 	 * before the grace period might be incorrectly seen as having
969 	 * started after the grace period.
970 	 *
971 	 * This synchronize_rcu() also dispenses with the need for a
972 	 * memory barrier on the first store to t->rcu_tasks_holdout,
973 	 * as it forces the store to happen after the beginning of the
974 	 * grace period.
975 	 */
976 	synchronize_rcu();
977 }
978 
979 /* Check for quiescent states since the pregp's synchronize_rcu() */
rcu_tasks_is_holdout(struct task_struct * t)980 static bool rcu_tasks_is_holdout(struct task_struct *t)
981 {
982 	int cpu;
983 
984 	/* Has the task been seen voluntarily sleeping? */
985 	if (!READ_ONCE(t->on_rq))
986 		return false;
987 
988 	/*
989 	 * t->on_rq && !t->se.sched_delayed *could* be considered sleeping but
990 	 * since it is a spurious state (it will transition into the
991 	 * traditional blocked state or get woken up without outside
992 	 * dependencies), not considering it such should only affect timing.
993 	 *
994 	 * Be conservative for now and not include it.
995 	 */
996 
997 	/*
998 	 * Idle tasks (or idle injection) within the idle loop are RCU-tasks
999 	 * quiescent states. But CPU boot code performed by the idle task
1000 	 * isn't a quiescent state.
1001 	 */
1002 	if (is_idle_task(t))
1003 		return false;
1004 
1005 	cpu = task_cpu(t);
1006 
1007 	/* Idle tasks on offline CPUs are RCU-tasks quiescent states. */
1008 	if (t == idle_task(cpu) && !rcu_cpu_online(cpu))
1009 		return false;
1010 
1011 	return true;
1012 }
1013 
1014 /* Per-task initial processing. */
rcu_tasks_pertask(struct task_struct * t,struct list_head * hop)1015 static void rcu_tasks_pertask(struct task_struct *t, struct list_head *hop)
1016 {
1017 	if (t != current && rcu_tasks_is_holdout(t)) {
1018 		get_task_struct(t);
1019 		t->rcu_tasks_nvcsw = READ_ONCE(t->nvcsw);
1020 		WRITE_ONCE(t->rcu_tasks_holdout, true);
1021 		list_add(&t->rcu_tasks_holdout_list, hop);
1022 	}
1023 }
1024 
1025 void call_rcu_tasks(struct rcu_head *rhp, rcu_callback_t func);
1026 DEFINE_RCU_TASKS(rcu_tasks, rcu_tasks_wait_gp, call_rcu_tasks, "RCU Tasks");
1027 
1028 /* Processing between scanning taskslist and draining the holdout list. */
rcu_tasks_postscan(struct list_head * hop)1029 static void rcu_tasks_postscan(struct list_head *hop)
1030 {
1031 	int cpu;
1032 	int rtsi = READ_ONCE(rcu_task_stall_info);
1033 
1034 	if (!IS_ENABLED(CONFIG_TINY_RCU)) {
1035 		tasks_rcu_exit_stall_timer.expires = jiffies + rtsi;
1036 		add_timer(&tasks_rcu_exit_stall_timer);
1037 	}
1038 
1039 	/*
1040 	 * Exiting tasks may escape the tasklist scan. Those are vulnerable
1041 	 * until their final schedule() with TASK_DEAD state. To cope with
1042 	 * this, divide the fragile exit path part in two intersecting
1043 	 * read side critical sections:
1044 	 *
1045 	 * 1) A task_struct list addition before calling exit_notify(),
1046 	 *    which may remove the task from the tasklist, with the
1047 	 *    removal after the final preempt_disable() call in do_exit().
1048 	 *
1049 	 * 2) An _RCU_ read side starting with the final preempt_disable()
1050 	 *    call in do_exit() and ending with the final call to schedule()
1051 	 *    with TASK_DEAD state.
1052 	 *
1053 	 * This handles the part 1). And postgp will handle part 2) with a
1054 	 * call to synchronize_rcu().
1055 	 */
1056 
1057 	for_each_possible_cpu(cpu) {
1058 		unsigned long j = jiffies + 1;
1059 		struct rcu_tasks_percpu *rtpcp = per_cpu_ptr(rcu_tasks.rtpcpu, cpu);
1060 		struct task_struct *t;
1061 		struct task_struct *t1;
1062 		struct list_head tmp;
1063 
1064 		raw_spin_lock_irq_rcu_node(rtpcp);
1065 		list_for_each_entry_safe(t, t1, &rtpcp->rtp_exit_list, rcu_tasks_exit_list) {
1066 			if (list_empty(&t->rcu_tasks_holdout_list))
1067 				rcu_tasks_pertask(t, hop);
1068 
1069 			// RT kernels need frequent pauses, otherwise
1070 			// pause at least once per pair of jiffies.
1071 			if (!IS_ENABLED(CONFIG_PREEMPT_RT) && time_before(jiffies, j))
1072 				continue;
1073 
1074 			// Keep our place in the list while pausing.
1075 			// Nothing else traverses this list, so adding a
1076 			// bare list_head is OK.
1077 			list_add(&tmp, &t->rcu_tasks_exit_list);
1078 			raw_spin_unlock_irq_rcu_node(rtpcp);
1079 			cond_resched(); // For CONFIG_PREEMPT=n kernels
1080 			raw_spin_lock_irq_rcu_node(rtpcp);
1081 			t1 = list_entry(tmp.next, struct task_struct, rcu_tasks_exit_list);
1082 			list_del(&tmp);
1083 			j = jiffies + 1;
1084 		}
1085 		raw_spin_unlock_irq_rcu_node(rtpcp);
1086 	}
1087 
1088 	if (!IS_ENABLED(CONFIG_TINY_RCU))
1089 		timer_delete_sync(&tasks_rcu_exit_stall_timer);
1090 }
1091 
1092 /* See if tasks are still holding out, complain if so. */
check_holdout_task(struct task_struct * t,bool needreport,bool * firstreport)1093 static void check_holdout_task(struct task_struct *t,
1094 			       bool needreport, bool *firstreport)
1095 {
1096 	int cpu;
1097 
1098 	if (!READ_ONCE(t->rcu_tasks_holdout) ||
1099 	    t->rcu_tasks_nvcsw != READ_ONCE(t->nvcsw) ||
1100 	    !rcu_tasks_is_holdout(t) ||
1101 	    (IS_ENABLED(CONFIG_NO_HZ_FULL) &&
1102 	     !is_idle_task(t) && READ_ONCE(t->rcu_tasks_idle_cpu) >= 0)) {
1103 		WRITE_ONCE(t->rcu_tasks_holdout, false);
1104 		list_del_init(&t->rcu_tasks_holdout_list);
1105 		put_task_struct(t);
1106 		return;
1107 	}
1108 	rcu_request_urgent_qs_task(t);
1109 	if (!needreport)
1110 		return;
1111 	if (*firstreport) {
1112 		pr_err("INFO: rcu_tasks detected stalls on tasks:\n");
1113 		*firstreport = false;
1114 	}
1115 	cpu = task_cpu(t);
1116 	pr_alert("%p: %c%c nvcsw: %lu/%lu holdout: %d idle_cpu: %d/%d\n",
1117 		 t, ".I"[is_idle_task(t)],
1118 		 "N."[cpu < 0 || !tick_nohz_full_cpu(cpu)],
1119 		 t->rcu_tasks_nvcsw, t->nvcsw, t->rcu_tasks_holdout,
1120 		 data_race(t->rcu_tasks_idle_cpu), cpu);
1121 	sched_show_task(t);
1122 }
1123 
1124 /* Scan the holdout lists for tasks no longer holding out. */
check_all_holdout_tasks(struct list_head * hop,bool needreport,bool * firstreport)1125 static void check_all_holdout_tasks(struct list_head *hop,
1126 				    bool needreport, bool *firstreport)
1127 {
1128 	struct task_struct *t, *t1;
1129 
1130 	list_for_each_entry_safe(t, t1, hop, rcu_tasks_holdout_list) {
1131 		check_holdout_task(t, needreport, firstreport);
1132 		cond_resched();
1133 	}
1134 }
1135 
1136 /* Finish off the Tasks-RCU grace period. */
rcu_tasks_postgp(struct rcu_tasks * rtp)1137 static void rcu_tasks_postgp(struct rcu_tasks *rtp)
1138 {
1139 	/*
1140 	 * Because ->on_rq and ->nvcsw are not guaranteed to have a full
1141 	 * memory barriers prior to them in the schedule() path, memory
1142 	 * reordering on other CPUs could cause their RCU-tasks read-side
1143 	 * critical sections to extend past the end of the grace period.
1144 	 * However, because these ->nvcsw updates are carried out with
1145 	 * interrupts disabled, we can use synchronize_rcu() to force the
1146 	 * needed ordering on all such CPUs.
1147 	 *
1148 	 * This synchronize_rcu() also confines all ->rcu_tasks_holdout
1149 	 * accesses to be within the grace period, avoiding the need for
1150 	 * memory barriers for ->rcu_tasks_holdout accesses.
1151 	 *
1152 	 * In addition, this synchronize_rcu() waits for exiting tasks
1153 	 * to complete their final preempt_disable() region of execution,
1154 	 * enforcing the whole region before tasklist removal until
1155 	 * the final schedule() with TASK_DEAD state to be an RCU TASKS
1156 	 * read side critical section.
1157 	 */
1158 	synchronize_rcu();
1159 }
1160 
tasks_rcu_exit_stall(struct timer_list * unused)1161 static void tasks_rcu_exit_stall(struct timer_list *unused)
1162 {
1163 #ifndef CONFIG_TINY_RCU
1164 	int rtsi;
1165 
1166 	rtsi = READ_ONCE(rcu_task_stall_info);
1167 	pr_info("%s: %s grace period number %lu (since boot) gp_state: %s is %lu jiffies old.\n",
1168 		__func__, rcu_tasks.kname, rcu_tasks.tasks_gp_seq,
1169 		tasks_gp_state_getname(&rcu_tasks), jiffies - rcu_tasks.gp_jiffies);
1170 	pr_info("Please check any exiting tasks stuck between calls to exit_tasks_rcu_start() and exit_tasks_rcu_finish()\n");
1171 	tasks_rcu_exit_stall_timer.expires = jiffies + rtsi;
1172 	add_timer(&tasks_rcu_exit_stall_timer);
1173 #endif // #ifndef CONFIG_TINY_RCU
1174 }
1175 
1176 /**
1177  * call_rcu_tasks() - Queue an RCU for invocation task-based grace period
1178  * @rhp: structure to be used for queueing the RCU updates.
1179  * @func: actual callback function to be invoked after the grace period
1180  *
1181  * The callback function will be invoked some time after a full grace
1182  * period elapses, in other words after all currently executing rcu-tasks
1183  * read-side critical sections have completed. call_rcu_tasks() assumes
1184  * that the read-side critical sections end at a voluntary context
1185  * switch (not a preemption!), cond_resched_tasks_rcu_qs(), entry into idle,
1186  * or transition to usermode execution.  As such, there are no read-side
1187  * primitives analogous to rcu_read_lock() and rcu_read_unlock() because
1188  * this primitive is intended to determine that all tasks have passed
1189  * through a safe state, not so much for data-structure synchronization.
1190  *
1191  * See the description of call_rcu() for more detailed information on
1192  * memory ordering guarantees.
1193  */
call_rcu_tasks(struct rcu_head * rhp,rcu_callback_t func)1194 void call_rcu_tasks(struct rcu_head *rhp, rcu_callback_t func)
1195 {
1196 	call_rcu_tasks_generic(rhp, func, &rcu_tasks);
1197 }
1198 EXPORT_SYMBOL_GPL(call_rcu_tasks);
1199 
1200 /**
1201  * synchronize_rcu_tasks - wait until an rcu-tasks grace period has elapsed.
1202  *
1203  * Control will return to the caller some time after a full rcu-tasks
1204  * grace period has elapsed, in other words after all currently
1205  * executing rcu-tasks read-side critical sections have elapsed.  These
1206  * read-side critical sections are delimited by calls to schedule(),
1207  * cond_resched_tasks_rcu_qs(), idle execution, userspace execution, calls
1208  * to synchronize_rcu_tasks(), and (in theory, anyway) cond_resched().
1209  *
1210  * This is a very specialized primitive, intended only for a few uses in
1211  * tracing and other situations requiring manipulation of function
1212  * preambles and profiling hooks.  The synchronize_rcu_tasks() function
1213  * is not (yet) intended for heavy use from multiple CPUs.
1214  *
1215  * See the description of synchronize_rcu() for more detailed information
1216  * on memory ordering guarantees.
1217  */
synchronize_rcu_tasks(void)1218 void synchronize_rcu_tasks(void)
1219 {
1220 	synchronize_rcu_tasks_generic(&rcu_tasks);
1221 }
1222 EXPORT_SYMBOL_GPL(synchronize_rcu_tasks);
1223 
1224 /**
1225  * rcu_barrier_tasks - Wait for in-flight call_rcu_tasks() callbacks.
1226  *
1227  * Although the current implementation is guaranteed to wait, it is not
1228  * obligated to, for example, if there are no pending callbacks.
1229  */
rcu_barrier_tasks(void)1230 void rcu_barrier_tasks(void)
1231 {
1232 	rcu_barrier_tasks_generic(&rcu_tasks);
1233 }
1234 EXPORT_SYMBOL_GPL(rcu_barrier_tasks);
1235 
1236 static int rcu_tasks_lazy_ms = -1;
1237 module_param(rcu_tasks_lazy_ms, int, 0444);
1238 
rcu_spawn_tasks_kthread(void)1239 static int __init rcu_spawn_tasks_kthread(void)
1240 {
1241 	rcu_tasks.gp_sleep = HZ / 10;
1242 	rcu_tasks.init_fract = HZ / 10;
1243 	if (rcu_tasks_lazy_ms >= 0)
1244 		rcu_tasks.lazy_jiffies = msecs_to_jiffies(rcu_tasks_lazy_ms);
1245 	rcu_tasks.pregp_func = rcu_tasks_pregp_step;
1246 	rcu_tasks.pertask_func = rcu_tasks_pertask;
1247 	rcu_tasks.postscan_func = rcu_tasks_postscan;
1248 	rcu_tasks.holdouts_func = check_all_holdout_tasks;
1249 	rcu_tasks.postgp_func = rcu_tasks_postgp;
1250 	rcu_tasks.wait_state = TASK_IDLE;
1251 	rcu_spawn_tasks_kthread_generic(&rcu_tasks);
1252 	return 0;
1253 }
1254 
1255 #if !defined(CONFIG_TINY_RCU)
show_rcu_tasks_classic_gp_kthread(void)1256 void show_rcu_tasks_classic_gp_kthread(void)
1257 {
1258 	show_rcu_tasks_generic_gp_kthread(&rcu_tasks, "");
1259 }
1260 EXPORT_SYMBOL_GPL(show_rcu_tasks_classic_gp_kthread);
1261 
rcu_tasks_torture_stats_print(char * tt,char * tf)1262 void rcu_tasks_torture_stats_print(char *tt, char *tf)
1263 {
1264 	rcu_tasks_torture_stats_print_generic(&rcu_tasks, tt, tf, "");
1265 }
1266 EXPORT_SYMBOL_GPL(rcu_tasks_torture_stats_print);
1267 #endif // !defined(CONFIG_TINY_RCU)
1268 
get_rcu_tasks_gp_kthread(void)1269 struct task_struct *get_rcu_tasks_gp_kthread(void)
1270 {
1271 	return rcu_tasks.kthread_ptr;
1272 }
1273 EXPORT_SYMBOL_GPL(get_rcu_tasks_gp_kthread);
1274 
rcu_tasks_get_gp_data(int * flags,unsigned long * gp_seq)1275 void rcu_tasks_get_gp_data(int *flags, unsigned long *gp_seq)
1276 {
1277 	*flags = 0;
1278 	*gp_seq = rcu_seq_current(&rcu_tasks.tasks_gp_seq);
1279 }
1280 EXPORT_SYMBOL_GPL(rcu_tasks_get_gp_data);
1281 
1282 /*
1283  * Protect against tasklist scan blind spot while the task is exiting and
1284  * may be removed from the tasklist.  Do this by adding the task to yet
1285  * another list.
1286  *
1287  * Note that the task will remove itself from this list, so there is no
1288  * need for get_task_struct(), except in the case where rcu_tasks_pertask()
1289  * adds it to the holdout list, in which case rcu_tasks_pertask() supplies
1290  * the needed get_task_struct().
1291  */
exit_tasks_rcu_start(void)1292 void exit_tasks_rcu_start(void)
1293 {
1294 	unsigned long flags;
1295 	struct rcu_tasks_percpu *rtpcp;
1296 	struct task_struct *t = current;
1297 
1298 	WARN_ON_ONCE(!list_empty(&t->rcu_tasks_exit_list));
1299 	preempt_disable();
1300 	rtpcp = this_cpu_ptr(rcu_tasks.rtpcpu);
1301 	t->rcu_tasks_exit_cpu = smp_processor_id();
1302 	raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
1303 	WARN_ON_ONCE(!rtpcp->rtp_exit_list.next);
1304 	list_add(&t->rcu_tasks_exit_list, &rtpcp->rtp_exit_list);
1305 	raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
1306 	preempt_enable();
1307 }
1308 
1309 /*
1310  * Remove the task from the "yet another list" because do_exit() is now
1311  * non-preemptible, allowing synchronize_rcu() to wait beyond this point.
1312  */
exit_tasks_rcu_finish(void)1313 void exit_tasks_rcu_finish(void)
1314 {
1315 	unsigned long flags;
1316 	struct rcu_tasks_percpu *rtpcp;
1317 	struct task_struct *t = current;
1318 
1319 	WARN_ON_ONCE(list_empty(&t->rcu_tasks_exit_list));
1320 	rtpcp = per_cpu_ptr(rcu_tasks.rtpcpu, t->rcu_tasks_exit_cpu);
1321 	raw_spin_lock_irqsave_rcu_node(rtpcp, flags);
1322 	list_del_init(&t->rcu_tasks_exit_list);
1323 	raw_spin_unlock_irqrestore_rcu_node(rtpcp, flags);
1324 }
1325 
1326 #else /* #ifdef CONFIG_TASKS_RCU */
exit_tasks_rcu_start(void)1327 void exit_tasks_rcu_start(void) { }
exit_tasks_rcu_finish(void)1328 void exit_tasks_rcu_finish(void) { }
1329 #endif /* #else #ifdef CONFIG_TASKS_RCU */
1330 
1331 #ifdef CONFIG_TASKS_RUDE_RCU
1332 
1333 ////////////////////////////////////////////////////////////////////////
1334 //
1335 // "Rude" variant of Tasks RCU, inspired by Steve Rostedt's
1336 // trick of passing an empty function to schedule_on_each_cpu().
1337 // This approach provides batching of concurrent calls to the synchronous
1338 // synchronize_rcu_tasks_rude() API.  This invokes schedule_on_each_cpu()
1339 // in order to send IPIs far and wide and induces otherwise unnecessary
1340 // context switches on all online CPUs, whether idle or not.
1341 //
1342 // Callback handling is provided by the rcu_tasks_kthread() function.
1343 //
1344 // Ordering is provided by the scheduler's context-switch code.
1345 
1346 // Empty function to allow workqueues to force a context switch.
rcu_tasks_be_rude(struct work_struct * work)1347 static void rcu_tasks_be_rude(struct work_struct *work)
1348 {
1349 }
1350 
1351 // Wait for one rude RCU-tasks grace period.
rcu_tasks_rude_wait_gp(struct rcu_tasks * rtp)1352 static void rcu_tasks_rude_wait_gp(struct rcu_tasks *rtp)
1353 {
1354 	rtp->n_ipis += cpumask_weight(cpu_online_mask);
1355 	schedule_on_each_cpu(rcu_tasks_be_rude);
1356 }
1357 
1358 static void call_rcu_tasks_rude(struct rcu_head *rhp, rcu_callback_t func);
1359 DEFINE_RCU_TASKS(rcu_tasks_rude, rcu_tasks_rude_wait_gp, call_rcu_tasks_rude,
1360 		 "RCU Tasks Rude");
1361 
1362 /*
1363  * call_rcu_tasks_rude() - Queue a callback rude task-based grace period
1364  * @rhp: structure to be used for queueing the RCU updates.
1365  * @func: actual callback function to be invoked after the grace period
1366  *
1367  * The callback function will be invoked some time after a full grace
1368  * period elapses, in other words after all currently executing rude
1369  * rcu-tasks read-side critical sections have completed. call_rcu_tasks_rude()
1370  * assumes that the read-side critical sections end at context switch,
1371  * cond_resched_tasks_rcu_qs(), or transition to usermode execution (as
1372  * usermode execution is schedulable). As such, there are no read-side
1373  * primitives analogous to rcu_read_lock() and rcu_read_unlock() because
1374  * this primitive is intended to determine that all tasks have passed
1375  * through a safe state, not so much for data-structure synchronization.
1376  *
1377  * See the description of call_rcu() for more detailed information on
1378  * memory ordering guarantees.
1379  *
1380  * This is no longer exported, and is instead reserved for use by
1381  * synchronize_rcu_tasks_rude().
1382  */
call_rcu_tasks_rude(struct rcu_head * rhp,rcu_callback_t func)1383 static void call_rcu_tasks_rude(struct rcu_head *rhp, rcu_callback_t func)
1384 {
1385 	call_rcu_tasks_generic(rhp, func, &rcu_tasks_rude);
1386 }
1387 
1388 /**
1389  * synchronize_rcu_tasks_rude - wait for a rude rcu-tasks grace period
1390  *
1391  * Control will return to the caller some time after a rude rcu-tasks
1392  * grace period has elapsed, in other words after all currently
1393  * executing rude rcu-tasks read-side critical sections have elapsed. These
1394  * read-side critical sections are delimited by calls to schedule(),
1395  * cond_resched_tasks_rcu_qs(), userspace execution (which is a schedulable
1396  * context), and (in theory, anyway) cond_resched().
1397  *
1398  * This is a very specialized primitive, intended only for a few uses in
1399  * tracing and other situations requiring manipulation of function preambles
1400  * and profiling hooks.  The synchronize_rcu_tasks_rude() function is not
1401  * (yet) intended for heavy use from multiple CPUs.
1402  *
1403  * See the description of synchronize_rcu() for more detailed information
1404  * on memory ordering guarantees.
1405  */
synchronize_rcu_tasks_rude(void)1406 void synchronize_rcu_tasks_rude(void)
1407 {
1408 	if (!IS_ENABLED(CONFIG_ARCH_WANTS_NO_INSTR) || IS_ENABLED(CONFIG_FORCE_TASKS_RUDE_RCU))
1409 		synchronize_rcu_tasks_generic(&rcu_tasks_rude);
1410 }
1411 EXPORT_SYMBOL_GPL(synchronize_rcu_tasks_rude);
1412 
rcu_spawn_tasks_rude_kthread(void)1413 static int __init rcu_spawn_tasks_rude_kthread(void)
1414 {
1415 	rcu_tasks_rude.gp_sleep = HZ / 10;
1416 	rcu_spawn_tasks_kthread_generic(&rcu_tasks_rude);
1417 	return 0;
1418 }
1419 
1420 #if !defined(CONFIG_TINY_RCU)
show_rcu_tasks_rude_gp_kthread(void)1421 void show_rcu_tasks_rude_gp_kthread(void)
1422 {
1423 	show_rcu_tasks_generic_gp_kthread(&rcu_tasks_rude, "");
1424 }
1425 EXPORT_SYMBOL_GPL(show_rcu_tasks_rude_gp_kthread);
1426 
rcu_tasks_rude_torture_stats_print(char * tt,char * tf)1427 void rcu_tasks_rude_torture_stats_print(char *tt, char *tf)
1428 {
1429 	rcu_tasks_torture_stats_print_generic(&rcu_tasks_rude, tt, tf, "");
1430 }
1431 EXPORT_SYMBOL_GPL(rcu_tasks_rude_torture_stats_print);
1432 #endif // !defined(CONFIG_TINY_RCU)
1433 
get_rcu_tasks_rude_gp_kthread(void)1434 struct task_struct *get_rcu_tasks_rude_gp_kthread(void)
1435 {
1436 	return rcu_tasks_rude.kthread_ptr;
1437 }
1438 EXPORT_SYMBOL_GPL(get_rcu_tasks_rude_gp_kthread);
1439 
rcu_tasks_rude_get_gp_data(int * flags,unsigned long * gp_seq)1440 void rcu_tasks_rude_get_gp_data(int *flags, unsigned long *gp_seq)
1441 {
1442 	*flags = 0;
1443 	*gp_seq = rcu_seq_current(&rcu_tasks_rude.tasks_gp_seq);
1444 }
1445 EXPORT_SYMBOL_GPL(rcu_tasks_rude_get_gp_data);
1446 
1447 #endif /* #ifdef CONFIG_TASKS_RUDE_RCU */
1448 
1449 #ifndef CONFIG_TINY_RCU
show_rcu_tasks_gp_kthreads(void)1450 void show_rcu_tasks_gp_kthreads(void)
1451 {
1452 	show_rcu_tasks_classic_gp_kthread();
1453 	show_rcu_tasks_rude_gp_kthread();
1454 }
1455 #endif /* #ifndef CONFIG_TINY_RCU */
1456 
1457 #ifdef CONFIG_PROVE_RCU
1458 struct rcu_tasks_test_desc {
1459 	struct rcu_head rh;
1460 	const char *name;
1461 	bool notrun;
1462 	unsigned long runstart;
1463 	void (*gp_dbg)(void);
1464 };
1465 
1466 static struct rcu_tasks_test_desc tests[] = {
1467 	{
1468 		.name = "call_rcu_tasks()",
1469 		/* If not defined, the test is skipped. */
1470 		.notrun = IS_ENABLED(CONFIG_TASKS_RCU),
1471 		/* Dump rcu tasks status, if test failed. */
1472 		.gp_dbg = show_rcu_tasks_classic_gp_kthread
1473 	},
1474 	{
1475 		.name = "call_rcu_tasks_trace()",
1476 		/* If not defined, the test is skipped. */
1477 		.notrun = IS_ENABLED(CONFIG_TASKS_TRACE_RCU)
1478 	}
1479 };
1480 
1481 #if defined(CONFIG_TASKS_RCU) || defined(CONFIG_TASKS_TRACE_RCU)
test_rcu_tasks_callback(struct rcu_head * rhp)1482 static void test_rcu_tasks_callback(struct rcu_head *rhp)
1483 {
1484 	struct rcu_tasks_test_desc *rttd =
1485 		container_of(rhp, struct rcu_tasks_test_desc, rh);
1486 
1487 	pr_info("Callback from %s invoked.\n", rttd->name);
1488 
1489 	rttd->notrun = false;
1490 }
1491 #endif // #if defined(CONFIG_TASKS_RCU) || defined(CONFIG_TASKS_TRACE_RCU)
1492 
rcu_tasks_initiate_self_tests(void)1493 static void rcu_tasks_initiate_self_tests(void)
1494 {
1495 #ifdef CONFIG_TASKS_RCU
1496 	pr_info("Running RCU Tasks wait API self tests\n");
1497 	tests[0].runstart = jiffies;
1498 	synchronize_rcu_tasks();
1499 	call_rcu_tasks(&tests[0].rh, test_rcu_tasks_callback);
1500 #endif
1501 
1502 #ifdef CONFIG_TASKS_RUDE_RCU
1503 	pr_info("Running RCU Tasks Rude wait API self tests\n");
1504 	synchronize_rcu_tasks_rude();
1505 #endif
1506 
1507 #ifdef CONFIG_TASKS_TRACE_RCU
1508 	pr_info("Running RCU Tasks Trace wait API self tests\n");
1509 	tests[1].runstart = jiffies;
1510 	synchronize_rcu_tasks_trace();
1511 	call_rcu_tasks_trace(&tests[1].rh, test_rcu_tasks_callback);
1512 #endif
1513 }
1514 
1515 /*
1516  * Return:  0 - test passed
1517  *	    1 - test failed, but have not timed out yet
1518  *	   -1 - test failed and timed out
1519  */
rcu_tasks_verify_self_tests(void)1520 static int rcu_tasks_verify_self_tests(void)
1521 {
1522 	int ret = 0;
1523 	int i;
1524 	unsigned long bst = rcu_task_stall_timeout;
1525 
1526 	if (bst <= 0 || bst > RCU_TASK_BOOT_STALL_TIMEOUT)
1527 		bst = RCU_TASK_BOOT_STALL_TIMEOUT;
1528 	for (i = 0; i < ARRAY_SIZE(tests); i++) {
1529 		while (tests[i].notrun) {		// still hanging.
1530 			if (time_after(jiffies, tests[i].runstart + bst)) {
1531 				pr_err("%s has failed boot-time tests.\n", tests[i].name);
1532 				if (tests[i].gp_dbg)
1533 					tests[i].gp_dbg();
1534 				ret = -1;
1535 				break;
1536 			}
1537 			ret = 1;
1538 			break;
1539 		}
1540 	}
1541 	WARN_ON(ret < 0);
1542 
1543 	return ret;
1544 }
1545 
1546 /*
1547  * Repeat the rcu_tasks_verify_self_tests() call once every second until the
1548  * test passes or has timed out.
1549  */
1550 static struct delayed_work rcu_tasks_verify_work;
rcu_tasks_verify_work_fn(struct work_struct * work __maybe_unused)1551 static void rcu_tasks_verify_work_fn(struct work_struct *work __maybe_unused)
1552 {
1553 	int ret = rcu_tasks_verify_self_tests();
1554 
1555 	if (ret <= 0)
1556 		return;
1557 
1558 	/* Test fails but not timed out yet, reschedule another check */
1559 	schedule_delayed_work(&rcu_tasks_verify_work, HZ);
1560 }
1561 
rcu_tasks_verify_schedule_work(void)1562 static int rcu_tasks_verify_schedule_work(void)
1563 {
1564 	INIT_DELAYED_WORK(&rcu_tasks_verify_work, rcu_tasks_verify_work_fn);
1565 	rcu_tasks_verify_work_fn(NULL);
1566 	return 0;
1567 }
1568 late_initcall(rcu_tasks_verify_schedule_work);
1569 #else /* #ifdef CONFIG_PROVE_RCU */
rcu_tasks_initiate_self_tests(void)1570 static void rcu_tasks_initiate_self_tests(void) { }
1571 #endif /* #else #ifdef CONFIG_PROVE_RCU */
1572 
tasks_cblist_init_generic(void)1573 void __init tasks_cblist_init_generic(void)
1574 {
1575 	lockdep_assert_irqs_disabled();
1576 	WARN_ON(num_online_cpus() > 1);
1577 
1578 #ifdef CONFIG_TASKS_RCU
1579 	cblist_init_generic(&rcu_tasks);
1580 #endif
1581 
1582 #ifdef CONFIG_TASKS_RUDE_RCU
1583 	cblist_init_generic(&rcu_tasks_rude);
1584 #endif
1585 }
1586 
rcu_init_tasks_generic(void)1587 static int __init rcu_init_tasks_generic(void)
1588 {
1589 #ifdef CONFIG_TASKS_RCU
1590 	rcu_spawn_tasks_kthread();
1591 #endif
1592 
1593 #ifdef CONFIG_TASKS_RUDE_RCU
1594 	rcu_spawn_tasks_rude_kthread();
1595 #endif
1596 
1597 	// Run the self-tests.
1598 	rcu_tasks_initiate_self_tests();
1599 
1600 	return 0;
1601 }
1602 core_initcall(rcu_init_tasks_generic);
1603 
1604 #else /* #ifdef CONFIG_TASKS_RCU_GENERIC */
rcu_tasks_bootup_oddness(void)1605 static inline void rcu_tasks_bootup_oddness(void) {}
1606 #endif /* #else #ifdef CONFIG_TASKS_RCU_GENERIC */
1607 
1608 #ifdef CONFIG_TASKS_TRACE_RCU
1609 
1610 ////////////////////////////////////////////////////////////////////////
1611 //
1612 // Tracing variant of Tasks RCU.  This variant is designed to be used
1613 // to protect tracing hooks, including those of BPF.  This variant
1614 // is implemented via a straightforward mapping onto SRCU-fast.
1615 
1616 DEFINE_SRCU_FAST(rcu_tasks_trace_srcu_struct);
1617 EXPORT_SYMBOL_GPL(rcu_tasks_trace_srcu_struct);
1618 
rcu_tasks_trace_batches_completed(void)1619 unsigned long rcu_tasks_trace_batches_completed(void)
1620 {
1621 	return srcu_batches_completed(&rcu_tasks_trace_srcu_struct);
1622 }
1623 EXPORT_SYMBOL_GPL(rcu_tasks_trace_batches_completed);
1624 
1625 #endif /* #else #ifdef CONFIG_TASKS_TRACE_RCU */
1626