xref: /openbmc/linux/kernel/rcu/rcutorture.c (revision 1f0214a8)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Read-Copy Update module-based torture test facility
4  *
5  * Copyright (C) IBM Corporation, 2005, 2006
6  *
7  * Authors: Paul E. McKenney <paulmck@linux.ibm.com>
8  *	  Josh Triplett <josh@joshtriplett.org>
9  *
10  * See also:  Documentation/RCU/torture.rst
11  */
12 
13 #define pr_fmt(fmt) fmt
14 
15 #include <linux/types.h>
16 #include <linux/kernel.h>
17 #include <linux/init.h>
18 #include <linux/module.h>
19 #include <linux/kthread.h>
20 #include <linux/err.h>
21 #include <linux/spinlock.h>
22 #include <linux/smp.h>
23 #include <linux/rcupdate_wait.h>
24 #include <linux/interrupt.h>
25 #include <linux/sched/signal.h>
26 #include <uapi/linux/sched/types.h>
27 #include <linux/atomic.h>
28 #include <linux/bitops.h>
29 #include <linux/completion.h>
30 #include <linux/moduleparam.h>
31 #include <linux/percpu.h>
32 #include <linux/notifier.h>
33 #include <linux/reboot.h>
34 #include <linux/freezer.h>
35 #include <linux/cpu.h>
36 #include <linux/delay.h>
37 #include <linux/stat.h>
38 #include <linux/srcu.h>
39 #include <linux/slab.h>
40 #include <linux/trace_clock.h>
41 #include <asm/byteorder.h>
42 #include <linux/torture.h>
43 #include <linux/vmalloc.h>
44 #include <linux/sched/debug.h>
45 #include <linux/sched/sysctl.h>
46 #include <linux/oom.h>
47 #include <linux/tick.h>
48 #include <linux/rcupdate_trace.h>
49 #include <linux/nmi.h>
50 
51 #include "rcu.h"
52 
53 MODULE_LICENSE("GPL");
54 MODULE_AUTHOR("Paul E. McKenney <paulmck@linux.ibm.com> and Josh Triplett <josh@joshtriplett.org>");
55 
56 /* Bits for ->extendables field, extendables param, and related definitions. */
57 #define RCUTORTURE_RDR_SHIFT_1	 8	/* Put SRCU index in upper bits. */
58 #define RCUTORTURE_RDR_MASK_1	 (1 << RCUTORTURE_RDR_SHIFT_1)
59 #define RCUTORTURE_RDR_SHIFT_2	 9	/* Put SRCU index in upper bits. */
60 #define RCUTORTURE_RDR_MASK_2	 (1 << RCUTORTURE_RDR_SHIFT_2)
61 #define RCUTORTURE_RDR_BH	 0x01	/* Extend readers by disabling bh. */
62 #define RCUTORTURE_RDR_IRQ	 0x02	/*  ... disabling interrupts. */
63 #define RCUTORTURE_RDR_PREEMPT	 0x04	/*  ... disabling preemption. */
64 #define RCUTORTURE_RDR_RBH	 0x08	/*  ... rcu_read_lock_bh(). */
65 #define RCUTORTURE_RDR_SCHED	 0x10	/*  ... rcu_read_lock_sched(). */
66 #define RCUTORTURE_RDR_RCU_1	 0x20	/*  ... entering another RCU reader. */
67 #define RCUTORTURE_RDR_RCU_2	 0x40	/*  ... entering another RCU reader. */
68 #define RCUTORTURE_RDR_NBITS	 7	/* Number of bits defined above. */
69 #define RCUTORTURE_MAX_EXTEND	 \
70 	(RCUTORTURE_RDR_BH | RCUTORTURE_RDR_IRQ | RCUTORTURE_RDR_PREEMPT | \
71 	 RCUTORTURE_RDR_RBH | RCUTORTURE_RDR_SCHED)
72 #define RCUTORTURE_RDR_MAX_LOOPS 0x7	/* Maximum reader extensions. */
73 					/* Must be power of two minus one. */
74 #define RCUTORTURE_RDR_MAX_SEGS (RCUTORTURE_RDR_MAX_LOOPS + 3)
75 
76 torture_param(int, extendables, RCUTORTURE_MAX_EXTEND,
77 	      "Extend readers by disabling bh (1), irqs (2), or preempt (4)");
78 torture_param(int, fqs_duration, 0,
79 	      "Duration of fqs bursts (us), 0 to disable");
80 torture_param(int, fqs_holdoff, 0, "Holdoff time within fqs bursts (us)");
81 torture_param(int, fqs_stutter, 3, "Wait time between fqs bursts (s)");
82 torture_param(int, fwd_progress, 1, "Test grace-period forward progress");
83 torture_param(int, fwd_progress_div, 4, "Fraction of CPU stall to wait");
84 torture_param(int, fwd_progress_holdoff, 60,
85 	      "Time between forward-progress tests (s)");
86 torture_param(bool, fwd_progress_need_resched, 1,
87 	      "Hide cond_resched() behind need_resched()");
88 torture_param(bool, gp_cond, false, "Use conditional/async GP wait primitives");
89 torture_param(bool, gp_exp, false, "Use expedited GP wait primitives");
90 torture_param(bool, gp_normal, false,
91 	     "Use normal (non-expedited) GP wait primitives");
92 torture_param(bool, gp_poll, false, "Use polling GP wait primitives");
93 torture_param(bool, gp_sync, false, "Use synchronous GP wait primitives");
94 torture_param(int, irqreader, 1, "Allow RCU readers from irq handlers");
95 torture_param(int, leakpointer, 0, "Leak pointer dereferences from readers");
96 torture_param(int, n_barrier_cbs, 0,
97 	     "# of callbacks/kthreads for barrier testing");
98 torture_param(int, nfakewriters, 4, "Number of RCU fake writer threads");
99 torture_param(int, nreaders, -1, "Number of RCU reader threads");
100 torture_param(int, object_debug, 0,
101 	     "Enable debug-object double call_rcu() testing");
102 torture_param(int, onoff_holdoff, 0, "Time after boot before CPU hotplugs (s)");
103 torture_param(int, onoff_interval, 0,
104 	     "Time between CPU hotplugs (jiffies), 0=disable");
105 torture_param(int, nocbs_nthreads, 0, "Number of NOCB toggle threads, 0 to disable");
106 torture_param(int, nocbs_toggle, 1000, "Time between toggling nocb state (ms)");
107 torture_param(int, read_exit_delay, 13,
108 	      "Delay between read-then-exit episodes (s)");
109 torture_param(int, read_exit_burst, 16,
110 	      "# of read-then-exit bursts per episode, zero to disable");
111 torture_param(int, shuffle_interval, 3, "Number of seconds between shuffles");
112 torture_param(int, shutdown_secs, 0, "Shutdown time (s), <= zero to disable.");
113 torture_param(int, stall_cpu, 0, "Stall duration (s), zero to disable.");
114 torture_param(int, stall_cpu_holdoff, 10,
115 	     "Time to wait before starting stall (s).");
116 torture_param(bool, stall_no_softlockup, false,
117 	     "Avoid softlockup warning during cpu stall.");
118 torture_param(int, stall_cpu_irqsoff, 0, "Disable interrupts while stalling.");
119 torture_param(int, stall_cpu_block, 0, "Sleep while stalling.");
120 torture_param(int, stall_gp_kthread, 0,
121 	      "Grace-period kthread stall duration (s).");
122 torture_param(int, stat_interval, 60,
123 	     "Number of seconds between stats printk()s");
124 torture_param(int, stutter, 5, "Number of seconds to run/halt test");
125 torture_param(int, test_boost, 1, "Test RCU prio boost: 0=no, 1=maybe, 2=yes.");
126 torture_param(int, test_boost_duration, 4,
127 	     "Duration of each boost test, seconds.");
128 torture_param(int, test_boost_interval, 7,
129 	     "Interval between boost tests, seconds.");
130 torture_param(bool, test_no_idle_hz, true,
131 	     "Test support for tickless idle CPUs");
132 torture_param(int, verbose, 1,
133 	     "Enable verbose debugging printk()s");
134 
135 static char *torture_type = "rcu";
136 module_param(torture_type, charp, 0444);
137 MODULE_PARM_DESC(torture_type, "Type of RCU to torture (rcu, srcu, ...)");
138 
139 static int nrealnocbers;
140 static int nrealreaders;
141 static struct task_struct *writer_task;
142 static struct task_struct **fakewriter_tasks;
143 static struct task_struct **reader_tasks;
144 static struct task_struct **nocb_tasks;
145 static struct task_struct *stats_task;
146 static struct task_struct *fqs_task;
147 static struct task_struct *boost_tasks[NR_CPUS];
148 static struct task_struct *stall_task;
149 static struct task_struct **fwd_prog_tasks;
150 static struct task_struct **barrier_cbs_tasks;
151 static struct task_struct *barrier_task;
152 static struct task_struct *read_exit_task;
153 
154 #define RCU_TORTURE_PIPE_LEN 10
155 
156 // Mailbox-like structure to check RCU global memory ordering.
157 struct rcu_torture_reader_check {
158 	unsigned long rtc_myloops;
159 	int rtc_chkrdr;
160 	unsigned long rtc_chkloops;
161 	int rtc_ready;
162 	struct rcu_torture_reader_check *rtc_assigner;
163 } ____cacheline_internodealigned_in_smp;
164 
165 // Update-side data structure used to check RCU readers.
166 struct rcu_torture {
167 	struct rcu_head rtort_rcu;
168 	int rtort_pipe_count;
169 	struct list_head rtort_free;
170 	int rtort_mbtest;
171 	struct rcu_torture_reader_check *rtort_chkp;
172 };
173 
174 static LIST_HEAD(rcu_torture_freelist);
175 static struct rcu_torture __rcu *rcu_torture_current;
176 static unsigned long rcu_torture_current_version;
177 static struct rcu_torture rcu_tortures[10 * RCU_TORTURE_PIPE_LEN];
178 static DEFINE_SPINLOCK(rcu_torture_lock);
179 static DEFINE_PER_CPU(long [RCU_TORTURE_PIPE_LEN + 1], rcu_torture_count);
180 static DEFINE_PER_CPU(long [RCU_TORTURE_PIPE_LEN + 1], rcu_torture_batch);
181 static atomic_t rcu_torture_wcount[RCU_TORTURE_PIPE_LEN + 1];
182 static struct rcu_torture_reader_check *rcu_torture_reader_mbchk;
183 static atomic_t n_rcu_torture_alloc;
184 static atomic_t n_rcu_torture_alloc_fail;
185 static atomic_t n_rcu_torture_free;
186 static atomic_t n_rcu_torture_mberror;
187 static atomic_t n_rcu_torture_mbchk_fail;
188 static atomic_t n_rcu_torture_mbchk_tries;
189 static atomic_t n_rcu_torture_error;
190 static long n_rcu_torture_barrier_error;
191 static long n_rcu_torture_boost_ktrerror;
192 static long n_rcu_torture_boost_rterror;
193 static long n_rcu_torture_boost_failure;
194 static long n_rcu_torture_boosts;
195 static atomic_long_t n_rcu_torture_timers;
196 static long n_barrier_attempts;
197 static long n_barrier_successes; /* did rcu_barrier test succeed? */
198 static unsigned long n_read_exits;
199 static struct list_head rcu_torture_removed;
200 static unsigned long shutdown_jiffies;
201 static unsigned long start_gp_seq;
202 static atomic_long_t n_nocb_offload;
203 static atomic_long_t n_nocb_deoffload;
204 
205 static int rcu_torture_writer_state;
206 #define RTWS_FIXED_DELAY	0
207 #define RTWS_DELAY		1
208 #define RTWS_REPLACE		2
209 #define RTWS_DEF_FREE		3
210 #define RTWS_EXP_SYNC		4
211 #define RTWS_COND_GET		5
212 #define RTWS_COND_SYNC		6
213 #define RTWS_POLL_GET		7
214 #define RTWS_POLL_WAIT		8
215 #define RTWS_SYNC		9
216 #define RTWS_STUTTER		10
217 #define RTWS_STOPPING		11
218 static const char * const rcu_torture_writer_state_names[] = {
219 	"RTWS_FIXED_DELAY",
220 	"RTWS_DELAY",
221 	"RTWS_REPLACE",
222 	"RTWS_DEF_FREE",
223 	"RTWS_EXP_SYNC",
224 	"RTWS_COND_GET",
225 	"RTWS_COND_SYNC",
226 	"RTWS_POLL_GET",
227 	"RTWS_POLL_WAIT",
228 	"RTWS_SYNC",
229 	"RTWS_STUTTER",
230 	"RTWS_STOPPING",
231 };
232 
233 /* Record reader segment types and duration for first failing read. */
234 struct rt_read_seg {
235 	int rt_readstate;
236 	unsigned long rt_delay_jiffies;
237 	unsigned long rt_delay_ms;
238 	unsigned long rt_delay_us;
239 	bool rt_preempted;
240 };
241 static int err_segs_recorded;
242 static struct rt_read_seg err_segs[RCUTORTURE_RDR_MAX_SEGS];
243 static int rt_read_nsegs;
244 
245 static const char *rcu_torture_writer_state_getname(void)
246 {
247 	unsigned int i = READ_ONCE(rcu_torture_writer_state);
248 
249 	if (i >= ARRAY_SIZE(rcu_torture_writer_state_names))
250 		return "???";
251 	return rcu_torture_writer_state_names[i];
252 }
253 
254 #ifdef CONFIG_RCU_TRACE
255 static u64 notrace rcu_trace_clock_local(void)
256 {
257 	u64 ts = trace_clock_local();
258 
259 	(void)do_div(ts, NSEC_PER_USEC);
260 	return ts;
261 }
262 #else /* #ifdef CONFIG_RCU_TRACE */
263 static u64 notrace rcu_trace_clock_local(void)
264 {
265 	return 0ULL;
266 }
267 #endif /* #else #ifdef CONFIG_RCU_TRACE */
268 
269 /*
270  * Stop aggressive CPU-hog tests a bit before the end of the test in order
271  * to avoid interfering with test shutdown.
272  */
273 static bool shutdown_time_arrived(void)
274 {
275 	return shutdown_secs && time_after(jiffies, shutdown_jiffies - 30 * HZ);
276 }
277 
278 static unsigned long boost_starttime;	/* jiffies of next boost test start. */
279 static DEFINE_MUTEX(boost_mutex);	/* protect setting boost_starttime */
280 					/*  and boost task create/destroy. */
281 static atomic_t barrier_cbs_count;	/* Barrier callbacks registered. */
282 static bool barrier_phase;		/* Test phase. */
283 static atomic_t barrier_cbs_invoked;	/* Barrier callbacks invoked. */
284 static wait_queue_head_t *barrier_cbs_wq; /* Coordinate barrier testing. */
285 static DECLARE_WAIT_QUEUE_HEAD(barrier_wq);
286 
287 static atomic_t rcu_fwd_cb_nodelay;	/* Short rcu_torture_delay() delays. */
288 
289 /*
290  * Allocate an element from the rcu_tortures pool.
291  */
292 static struct rcu_torture *
293 rcu_torture_alloc(void)
294 {
295 	struct list_head *p;
296 
297 	spin_lock_bh(&rcu_torture_lock);
298 	if (list_empty(&rcu_torture_freelist)) {
299 		atomic_inc(&n_rcu_torture_alloc_fail);
300 		spin_unlock_bh(&rcu_torture_lock);
301 		return NULL;
302 	}
303 	atomic_inc(&n_rcu_torture_alloc);
304 	p = rcu_torture_freelist.next;
305 	list_del_init(p);
306 	spin_unlock_bh(&rcu_torture_lock);
307 	return container_of(p, struct rcu_torture, rtort_free);
308 }
309 
310 /*
311  * Free an element to the rcu_tortures pool.
312  */
313 static void
314 rcu_torture_free(struct rcu_torture *p)
315 {
316 	atomic_inc(&n_rcu_torture_free);
317 	spin_lock_bh(&rcu_torture_lock);
318 	list_add_tail(&p->rtort_free, &rcu_torture_freelist);
319 	spin_unlock_bh(&rcu_torture_lock);
320 }
321 
322 /*
323  * Operations vector for selecting different types of tests.
324  */
325 
326 struct rcu_torture_ops {
327 	int ttype;
328 	void (*init)(void);
329 	void (*cleanup)(void);
330 	int (*readlock)(void);
331 	void (*read_delay)(struct torture_random_state *rrsp,
332 			   struct rt_read_seg *rtrsp);
333 	void (*readunlock)(int idx);
334 	int (*readlock_held)(void);
335 	unsigned long (*get_gp_seq)(void);
336 	unsigned long (*gp_diff)(unsigned long new, unsigned long old);
337 	void (*deferred_free)(struct rcu_torture *p);
338 	void (*sync)(void);
339 	void (*exp_sync)(void);
340 	unsigned long (*get_gp_state)(void);
341 	unsigned long (*start_gp_poll)(void);
342 	bool (*poll_gp_state)(unsigned long oldstate);
343 	void (*cond_sync)(unsigned long oldstate);
344 	call_rcu_func_t call;
345 	void (*cb_barrier)(void);
346 	void (*fqs)(void);
347 	void (*stats)(void);
348 	void (*gp_kthread_dbg)(void);
349 	bool (*check_boost_failed)(unsigned long gp_state, int *cpup);
350 	int (*stall_dur)(void);
351 	long cbflood_max;
352 	int irq_capable;
353 	int can_boost;
354 	int extendables;
355 	int slow_gps;
356 	int no_pi_lock;
357 	const char *name;
358 };
359 
360 static struct rcu_torture_ops *cur_ops;
361 
362 /*
363  * Definitions for rcu torture testing.
364  */
365 
366 static int torture_readlock_not_held(void)
367 {
368 	return rcu_read_lock_bh_held() || rcu_read_lock_sched_held();
369 }
370 
371 static int rcu_torture_read_lock(void) __acquires(RCU)
372 {
373 	rcu_read_lock();
374 	return 0;
375 }
376 
377 static void
378 rcu_read_delay(struct torture_random_state *rrsp, struct rt_read_seg *rtrsp)
379 {
380 	unsigned long started;
381 	unsigned long completed;
382 	const unsigned long shortdelay_us = 200;
383 	unsigned long longdelay_ms = 300;
384 	unsigned long long ts;
385 
386 	/* We want a short delay sometimes to make a reader delay the grace
387 	 * period, and we want a long delay occasionally to trigger
388 	 * force_quiescent_state. */
389 
390 	if (!atomic_read(&rcu_fwd_cb_nodelay) &&
391 	    !(torture_random(rrsp) % (nrealreaders * 2000 * longdelay_ms))) {
392 		started = cur_ops->get_gp_seq();
393 		ts = rcu_trace_clock_local();
394 		if (preempt_count() & (SOFTIRQ_MASK | HARDIRQ_MASK))
395 			longdelay_ms = 5; /* Avoid triggering BH limits. */
396 		mdelay(longdelay_ms);
397 		rtrsp->rt_delay_ms = longdelay_ms;
398 		completed = cur_ops->get_gp_seq();
399 		do_trace_rcu_torture_read(cur_ops->name, NULL, ts,
400 					  started, completed);
401 	}
402 	if (!(torture_random(rrsp) % (nrealreaders * 2 * shortdelay_us))) {
403 		udelay(shortdelay_us);
404 		rtrsp->rt_delay_us = shortdelay_us;
405 	}
406 	if (!preempt_count() &&
407 	    !(torture_random(rrsp) % (nrealreaders * 500))) {
408 		torture_preempt_schedule();  /* QS only if preemptible. */
409 		rtrsp->rt_preempted = true;
410 	}
411 }
412 
413 static void rcu_torture_read_unlock(int idx) __releases(RCU)
414 {
415 	rcu_read_unlock();
416 }
417 
418 /*
419  * Update callback in the pipe.  This should be invoked after a grace period.
420  */
421 static bool
422 rcu_torture_pipe_update_one(struct rcu_torture *rp)
423 {
424 	int i;
425 	struct rcu_torture_reader_check *rtrcp = READ_ONCE(rp->rtort_chkp);
426 
427 	if (rtrcp) {
428 		WRITE_ONCE(rp->rtort_chkp, NULL);
429 		smp_store_release(&rtrcp->rtc_ready, 1); // Pair with smp_load_acquire().
430 	}
431 	i = READ_ONCE(rp->rtort_pipe_count);
432 	if (i > RCU_TORTURE_PIPE_LEN)
433 		i = RCU_TORTURE_PIPE_LEN;
434 	atomic_inc(&rcu_torture_wcount[i]);
435 	WRITE_ONCE(rp->rtort_pipe_count, i + 1);
436 	if (rp->rtort_pipe_count >= RCU_TORTURE_PIPE_LEN) {
437 		rp->rtort_mbtest = 0;
438 		return true;
439 	}
440 	return false;
441 }
442 
443 /*
444  * Update all callbacks in the pipe.  Suitable for synchronous grace-period
445  * primitives.
446  */
447 static void
448 rcu_torture_pipe_update(struct rcu_torture *old_rp)
449 {
450 	struct rcu_torture *rp;
451 	struct rcu_torture *rp1;
452 
453 	if (old_rp)
454 		list_add(&old_rp->rtort_free, &rcu_torture_removed);
455 	list_for_each_entry_safe(rp, rp1, &rcu_torture_removed, rtort_free) {
456 		if (rcu_torture_pipe_update_one(rp)) {
457 			list_del(&rp->rtort_free);
458 			rcu_torture_free(rp);
459 		}
460 	}
461 }
462 
463 static void
464 rcu_torture_cb(struct rcu_head *p)
465 {
466 	struct rcu_torture *rp = container_of(p, struct rcu_torture, rtort_rcu);
467 
468 	if (torture_must_stop_irq()) {
469 		/* Test is ending, just drop callbacks on the floor. */
470 		/* The next initialization will pick up the pieces. */
471 		return;
472 	}
473 	if (rcu_torture_pipe_update_one(rp))
474 		rcu_torture_free(rp);
475 	else
476 		cur_ops->deferred_free(rp);
477 }
478 
479 static unsigned long rcu_no_completed(void)
480 {
481 	return 0;
482 }
483 
484 static void rcu_torture_deferred_free(struct rcu_torture *p)
485 {
486 	call_rcu(&p->rtort_rcu, rcu_torture_cb);
487 }
488 
489 static void rcu_sync_torture_init(void)
490 {
491 	INIT_LIST_HEAD(&rcu_torture_removed);
492 }
493 
494 static struct rcu_torture_ops rcu_ops = {
495 	.ttype			= RCU_FLAVOR,
496 	.init			= rcu_sync_torture_init,
497 	.readlock		= rcu_torture_read_lock,
498 	.read_delay		= rcu_read_delay,
499 	.readunlock		= rcu_torture_read_unlock,
500 	.readlock_held		= torture_readlock_not_held,
501 	.get_gp_seq		= rcu_get_gp_seq,
502 	.gp_diff		= rcu_seq_diff,
503 	.deferred_free		= rcu_torture_deferred_free,
504 	.sync			= synchronize_rcu,
505 	.exp_sync		= synchronize_rcu_expedited,
506 	.get_gp_state		= get_state_synchronize_rcu,
507 	.start_gp_poll		= start_poll_synchronize_rcu,
508 	.poll_gp_state		= poll_state_synchronize_rcu,
509 	.cond_sync		= cond_synchronize_rcu,
510 	.call			= call_rcu,
511 	.cb_barrier		= rcu_barrier,
512 	.fqs			= rcu_force_quiescent_state,
513 	.stats			= NULL,
514 	.gp_kthread_dbg		= show_rcu_gp_kthreads,
515 	.check_boost_failed	= rcu_check_boost_fail,
516 	.stall_dur		= rcu_jiffies_till_stall_check,
517 	.irq_capable		= 1,
518 	.can_boost		= IS_ENABLED(CONFIG_RCU_BOOST),
519 	.extendables		= RCUTORTURE_MAX_EXTEND,
520 	.name			= "rcu"
521 };
522 
523 /*
524  * Don't even think about trying any of these in real life!!!
525  * The names includes "busted", and they really means it!
526  * The only purpose of these functions is to provide a buggy RCU
527  * implementation to make sure that rcutorture correctly emits
528  * buggy-RCU error messages.
529  */
530 static void rcu_busted_torture_deferred_free(struct rcu_torture *p)
531 {
532 	/* This is a deliberate bug for testing purposes only! */
533 	rcu_torture_cb(&p->rtort_rcu);
534 }
535 
536 static void synchronize_rcu_busted(void)
537 {
538 	/* This is a deliberate bug for testing purposes only! */
539 }
540 
541 static void
542 call_rcu_busted(struct rcu_head *head, rcu_callback_t func)
543 {
544 	/* This is a deliberate bug for testing purposes only! */
545 	func(head);
546 }
547 
548 static struct rcu_torture_ops rcu_busted_ops = {
549 	.ttype		= INVALID_RCU_FLAVOR,
550 	.init		= rcu_sync_torture_init,
551 	.readlock	= rcu_torture_read_lock,
552 	.read_delay	= rcu_read_delay,  /* just reuse rcu's version. */
553 	.readunlock	= rcu_torture_read_unlock,
554 	.readlock_held	= torture_readlock_not_held,
555 	.get_gp_seq	= rcu_no_completed,
556 	.deferred_free	= rcu_busted_torture_deferred_free,
557 	.sync		= synchronize_rcu_busted,
558 	.exp_sync	= synchronize_rcu_busted,
559 	.call		= call_rcu_busted,
560 	.cb_barrier	= NULL,
561 	.fqs		= NULL,
562 	.stats		= NULL,
563 	.irq_capable	= 1,
564 	.name		= "busted"
565 };
566 
567 /*
568  * Definitions for srcu torture testing.
569  */
570 
571 DEFINE_STATIC_SRCU(srcu_ctl);
572 static struct srcu_struct srcu_ctld;
573 static struct srcu_struct *srcu_ctlp = &srcu_ctl;
574 
575 static int srcu_torture_read_lock(void) __acquires(srcu_ctlp)
576 {
577 	return srcu_read_lock(srcu_ctlp);
578 }
579 
580 static void
581 srcu_read_delay(struct torture_random_state *rrsp, struct rt_read_seg *rtrsp)
582 {
583 	long delay;
584 	const long uspertick = 1000000 / HZ;
585 	const long longdelay = 10;
586 
587 	/* We want there to be long-running readers, but not all the time. */
588 
589 	delay = torture_random(rrsp) %
590 		(nrealreaders * 2 * longdelay * uspertick);
591 	if (!delay && in_task()) {
592 		schedule_timeout_interruptible(longdelay);
593 		rtrsp->rt_delay_jiffies = longdelay;
594 	} else {
595 		rcu_read_delay(rrsp, rtrsp);
596 	}
597 }
598 
599 static void srcu_torture_read_unlock(int idx) __releases(srcu_ctlp)
600 {
601 	srcu_read_unlock(srcu_ctlp, idx);
602 }
603 
604 static int torture_srcu_read_lock_held(void)
605 {
606 	return srcu_read_lock_held(srcu_ctlp);
607 }
608 
609 static unsigned long srcu_torture_completed(void)
610 {
611 	return srcu_batches_completed(srcu_ctlp);
612 }
613 
614 static void srcu_torture_deferred_free(struct rcu_torture *rp)
615 {
616 	call_srcu(srcu_ctlp, &rp->rtort_rcu, rcu_torture_cb);
617 }
618 
619 static void srcu_torture_synchronize(void)
620 {
621 	synchronize_srcu(srcu_ctlp);
622 }
623 
624 static unsigned long srcu_torture_get_gp_state(void)
625 {
626 	return get_state_synchronize_srcu(srcu_ctlp);
627 }
628 
629 static unsigned long srcu_torture_start_gp_poll(void)
630 {
631 	return start_poll_synchronize_srcu(srcu_ctlp);
632 }
633 
634 static bool srcu_torture_poll_gp_state(unsigned long oldstate)
635 {
636 	return poll_state_synchronize_srcu(srcu_ctlp, oldstate);
637 }
638 
639 static void srcu_torture_call(struct rcu_head *head,
640 			      rcu_callback_t func)
641 {
642 	call_srcu(srcu_ctlp, head, func);
643 }
644 
645 static void srcu_torture_barrier(void)
646 {
647 	srcu_barrier(srcu_ctlp);
648 }
649 
650 static void srcu_torture_stats(void)
651 {
652 	srcu_torture_stats_print(srcu_ctlp, torture_type, TORTURE_FLAG);
653 }
654 
655 static void srcu_torture_synchronize_expedited(void)
656 {
657 	synchronize_srcu_expedited(srcu_ctlp);
658 }
659 
660 static struct rcu_torture_ops srcu_ops = {
661 	.ttype		= SRCU_FLAVOR,
662 	.init		= rcu_sync_torture_init,
663 	.readlock	= srcu_torture_read_lock,
664 	.read_delay	= srcu_read_delay,
665 	.readunlock	= srcu_torture_read_unlock,
666 	.readlock_held	= torture_srcu_read_lock_held,
667 	.get_gp_seq	= srcu_torture_completed,
668 	.deferred_free	= srcu_torture_deferred_free,
669 	.sync		= srcu_torture_synchronize,
670 	.exp_sync	= srcu_torture_synchronize_expedited,
671 	.get_gp_state	= srcu_torture_get_gp_state,
672 	.start_gp_poll	= srcu_torture_start_gp_poll,
673 	.poll_gp_state	= srcu_torture_poll_gp_state,
674 	.call		= srcu_torture_call,
675 	.cb_barrier	= srcu_torture_barrier,
676 	.stats		= srcu_torture_stats,
677 	.cbflood_max	= 50000,
678 	.irq_capable	= 1,
679 	.no_pi_lock	= IS_ENABLED(CONFIG_TINY_SRCU),
680 	.name		= "srcu"
681 };
682 
683 static void srcu_torture_init(void)
684 {
685 	rcu_sync_torture_init();
686 	WARN_ON(init_srcu_struct(&srcu_ctld));
687 	srcu_ctlp = &srcu_ctld;
688 }
689 
690 static void srcu_torture_cleanup(void)
691 {
692 	cleanup_srcu_struct(&srcu_ctld);
693 	srcu_ctlp = &srcu_ctl; /* In case of a later rcutorture run. */
694 }
695 
696 /* As above, but dynamically allocated. */
697 static struct rcu_torture_ops srcud_ops = {
698 	.ttype		= SRCU_FLAVOR,
699 	.init		= srcu_torture_init,
700 	.cleanup	= srcu_torture_cleanup,
701 	.readlock	= srcu_torture_read_lock,
702 	.read_delay	= srcu_read_delay,
703 	.readunlock	= srcu_torture_read_unlock,
704 	.readlock_held	= torture_srcu_read_lock_held,
705 	.get_gp_seq	= srcu_torture_completed,
706 	.deferred_free	= srcu_torture_deferred_free,
707 	.sync		= srcu_torture_synchronize,
708 	.exp_sync	= srcu_torture_synchronize_expedited,
709 	.call		= srcu_torture_call,
710 	.cb_barrier	= srcu_torture_barrier,
711 	.stats		= srcu_torture_stats,
712 	.cbflood_max	= 50000,
713 	.irq_capable	= 1,
714 	.no_pi_lock	= IS_ENABLED(CONFIG_TINY_SRCU),
715 	.name		= "srcud"
716 };
717 
718 /* As above, but broken due to inappropriate reader extension. */
719 static struct rcu_torture_ops busted_srcud_ops = {
720 	.ttype		= SRCU_FLAVOR,
721 	.init		= srcu_torture_init,
722 	.cleanup	= srcu_torture_cleanup,
723 	.readlock	= srcu_torture_read_lock,
724 	.read_delay	= rcu_read_delay,
725 	.readunlock	= srcu_torture_read_unlock,
726 	.readlock_held	= torture_srcu_read_lock_held,
727 	.get_gp_seq	= srcu_torture_completed,
728 	.deferred_free	= srcu_torture_deferred_free,
729 	.sync		= srcu_torture_synchronize,
730 	.exp_sync	= srcu_torture_synchronize_expedited,
731 	.call		= srcu_torture_call,
732 	.cb_barrier	= srcu_torture_barrier,
733 	.stats		= srcu_torture_stats,
734 	.irq_capable	= 1,
735 	.no_pi_lock	= IS_ENABLED(CONFIG_TINY_SRCU),
736 	.extendables	= RCUTORTURE_MAX_EXTEND,
737 	.name		= "busted_srcud"
738 };
739 
740 /*
741  * Definitions for RCU-tasks torture testing.
742  */
743 
744 static int tasks_torture_read_lock(void)
745 {
746 	return 0;
747 }
748 
749 static void tasks_torture_read_unlock(int idx)
750 {
751 }
752 
753 static void rcu_tasks_torture_deferred_free(struct rcu_torture *p)
754 {
755 	call_rcu_tasks(&p->rtort_rcu, rcu_torture_cb);
756 }
757 
758 static void synchronize_rcu_mult_test(void)
759 {
760 	synchronize_rcu_mult(call_rcu_tasks, call_rcu);
761 }
762 
763 static struct rcu_torture_ops tasks_ops = {
764 	.ttype		= RCU_TASKS_FLAVOR,
765 	.init		= rcu_sync_torture_init,
766 	.readlock	= tasks_torture_read_lock,
767 	.read_delay	= rcu_read_delay,  /* just reuse rcu's version. */
768 	.readunlock	= tasks_torture_read_unlock,
769 	.get_gp_seq	= rcu_no_completed,
770 	.deferred_free	= rcu_tasks_torture_deferred_free,
771 	.sync		= synchronize_rcu_tasks,
772 	.exp_sync	= synchronize_rcu_mult_test,
773 	.call		= call_rcu_tasks,
774 	.cb_barrier	= rcu_barrier_tasks,
775 	.gp_kthread_dbg	= show_rcu_tasks_classic_gp_kthread,
776 	.fqs		= NULL,
777 	.stats		= NULL,
778 	.irq_capable	= 1,
779 	.slow_gps	= 1,
780 	.name		= "tasks"
781 };
782 
783 /*
784  * Definitions for trivial CONFIG_PREEMPT=n-only torture testing.
785  * This implementation does not necessarily work well with CPU hotplug.
786  */
787 
788 static void synchronize_rcu_trivial(void)
789 {
790 	int cpu;
791 
792 	for_each_online_cpu(cpu) {
793 		rcutorture_sched_setaffinity(current->pid, cpumask_of(cpu));
794 		WARN_ON_ONCE(raw_smp_processor_id() != cpu);
795 	}
796 }
797 
798 static int rcu_torture_read_lock_trivial(void) __acquires(RCU)
799 {
800 	preempt_disable();
801 	return 0;
802 }
803 
804 static void rcu_torture_read_unlock_trivial(int idx) __releases(RCU)
805 {
806 	preempt_enable();
807 }
808 
809 static struct rcu_torture_ops trivial_ops = {
810 	.ttype		= RCU_TRIVIAL_FLAVOR,
811 	.init		= rcu_sync_torture_init,
812 	.readlock	= rcu_torture_read_lock_trivial,
813 	.read_delay	= rcu_read_delay,  /* just reuse rcu's version. */
814 	.readunlock	= rcu_torture_read_unlock_trivial,
815 	.readlock_held	= torture_readlock_not_held,
816 	.get_gp_seq	= rcu_no_completed,
817 	.sync		= synchronize_rcu_trivial,
818 	.exp_sync	= synchronize_rcu_trivial,
819 	.fqs		= NULL,
820 	.stats		= NULL,
821 	.irq_capable	= 1,
822 	.name		= "trivial"
823 };
824 
825 /*
826  * Definitions for rude RCU-tasks torture testing.
827  */
828 
829 static void rcu_tasks_rude_torture_deferred_free(struct rcu_torture *p)
830 {
831 	call_rcu_tasks_rude(&p->rtort_rcu, rcu_torture_cb);
832 }
833 
834 static struct rcu_torture_ops tasks_rude_ops = {
835 	.ttype		= RCU_TASKS_RUDE_FLAVOR,
836 	.init		= rcu_sync_torture_init,
837 	.readlock	= rcu_torture_read_lock_trivial,
838 	.read_delay	= rcu_read_delay,  /* just reuse rcu's version. */
839 	.readunlock	= rcu_torture_read_unlock_trivial,
840 	.get_gp_seq	= rcu_no_completed,
841 	.deferred_free	= rcu_tasks_rude_torture_deferred_free,
842 	.sync		= synchronize_rcu_tasks_rude,
843 	.exp_sync	= synchronize_rcu_tasks_rude,
844 	.call		= call_rcu_tasks_rude,
845 	.cb_barrier	= rcu_barrier_tasks_rude,
846 	.gp_kthread_dbg	= show_rcu_tasks_rude_gp_kthread,
847 	.cbflood_max	= 50000,
848 	.fqs		= NULL,
849 	.stats		= NULL,
850 	.irq_capable	= 1,
851 	.name		= "tasks-rude"
852 };
853 
854 /*
855  * Definitions for tracing RCU-tasks torture testing.
856  */
857 
858 static int tasks_tracing_torture_read_lock(void)
859 {
860 	rcu_read_lock_trace();
861 	return 0;
862 }
863 
864 static void tasks_tracing_torture_read_unlock(int idx)
865 {
866 	rcu_read_unlock_trace();
867 }
868 
869 static void rcu_tasks_tracing_torture_deferred_free(struct rcu_torture *p)
870 {
871 	call_rcu_tasks_trace(&p->rtort_rcu, rcu_torture_cb);
872 }
873 
874 static struct rcu_torture_ops tasks_tracing_ops = {
875 	.ttype		= RCU_TASKS_TRACING_FLAVOR,
876 	.init		= rcu_sync_torture_init,
877 	.readlock	= tasks_tracing_torture_read_lock,
878 	.read_delay	= srcu_read_delay,  /* just reuse srcu's version. */
879 	.readunlock	= tasks_tracing_torture_read_unlock,
880 	.readlock_held	= rcu_read_lock_trace_held,
881 	.get_gp_seq	= rcu_no_completed,
882 	.deferred_free	= rcu_tasks_tracing_torture_deferred_free,
883 	.sync		= synchronize_rcu_tasks_trace,
884 	.exp_sync	= synchronize_rcu_tasks_trace,
885 	.call		= call_rcu_tasks_trace,
886 	.cb_barrier	= rcu_barrier_tasks_trace,
887 	.gp_kthread_dbg	= show_rcu_tasks_trace_gp_kthread,
888 	.cbflood_max	= 50000,
889 	.fqs		= NULL,
890 	.stats		= NULL,
891 	.irq_capable	= 1,
892 	.slow_gps	= 1,
893 	.name		= "tasks-tracing"
894 };
895 
896 static unsigned long rcutorture_seq_diff(unsigned long new, unsigned long old)
897 {
898 	if (!cur_ops->gp_diff)
899 		return new - old;
900 	return cur_ops->gp_diff(new, old);
901 }
902 
903 /*
904  * RCU torture priority-boost testing.  Runs one real-time thread per
905  * CPU for moderate bursts, repeatedly starting grace periods and waiting
906  * for them to complete.  If a given grace period takes too long, we assume
907  * that priority inversion has occurred.
908  */
909 
910 static int old_rt_runtime = -1;
911 
912 static void rcu_torture_disable_rt_throttle(void)
913 {
914 	/*
915 	 * Disable RT throttling so that rcutorture's boost threads don't get
916 	 * throttled. Only possible if rcutorture is built-in otherwise the
917 	 * user should manually do this by setting the sched_rt_period_us and
918 	 * sched_rt_runtime sysctls.
919 	 */
920 	if (!IS_BUILTIN(CONFIG_RCU_TORTURE_TEST) || old_rt_runtime != -1)
921 		return;
922 
923 	old_rt_runtime = sysctl_sched_rt_runtime;
924 	sysctl_sched_rt_runtime = -1;
925 }
926 
927 static void rcu_torture_enable_rt_throttle(void)
928 {
929 	if (!IS_BUILTIN(CONFIG_RCU_TORTURE_TEST) || old_rt_runtime == -1)
930 		return;
931 
932 	sysctl_sched_rt_runtime = old_rt_runtime;
933 	old_rt_runtime = -1;
934 }
935 
936 static bool rcu_torture_boost_failed(unsigned long gp_state, unsigned long *start)
937 {
938 	int cpu;
939 	static int dbg_done;
940 	unsigned long end = jiffies;
941 	bool gp_done;
942 	unsigned long j;
943 	static unsigned long last_persist;
944 	unsigned long lp;
945 	unsigned long mininterval = test_boost_duration * HZ - HZ / 2;
946 
947 	if (end - *start > mininterval) {
948 		// Recheck after checking time to avoid false positives.
949 		smp_mb(); // Time check before grace-period check.
950 		if (cur_ops->poll_gp_state(gp_state))
951 			return false; // passed, though perhaps just barely
952 		if (cur_ops->check_boost_failed && !cur_ops->check_boost_failed(gp_state, &cpu)) {
953 			// At most one persisted message per boost test.
954 			j = jiffies;
955 			lp = READ_ONCE(last_persist);
956 			if (time_after(j, lp + mininterval) && cmpxchg(&last_persist, lp, j) == lp)
957 				pr_info("Boost inversion persisted: No QS from CPU %d\n", cpu);
958 			return false; // passed on a technicality
959 		}
960 		VERBOSE_TOROUT_STRING("rcu_torture_boost boosting failed");
961 		n_rcu_torture_boost_failure++;
962 		if (!xchg(&dbg_done, 1) && cur_ops->gp_kthread_dbg) {
963 			pr_info("Boost inversion thread ->rt_priority %u gp_state %lu jiffies %lu\n",
964 				current->rt_priority, gp_state, end - *start);
965 			cur_ops->gp_kthread_dbg();
966 			// Recheck after print to flag grace period ending during splat.
967 			gp_done = cur_ops->poll_gp_state(gp_state);
968 			pr_info("Boost inversion: GP %lu %s.\n", gp_state,
969 				gp_done ? "ended already" : "still pending");
970 
971 		}
972 
973 		return true; // failed
974 	} else if (cur_ops->check_boost_failed && !cur_ops->check_boost_failed(gp_state, NULL)) {
975 		*start = jiffies;
976 	}
977 
978 	return false; // passed
979 }
980 
981 static int rcu_torture_boost(void *arg)
982 {
983 	unsigned long endtime;
984 	unsigned long gp_state;
985 	unsigned long gp_state_time;
986 	unsigned long oldstarttime;
987 
988 	VERBOSE_TOROUT_STRING("rcu_torture_boost started");
989 
990 	/* Set real-time priority. */
991 	sched_set_fifo_low(current);
992 
993 	/* Each pass through the following loop does one boost-test cycle. */
994 	do {
995 		bool failed = false; // Test failed already in this test interval
996 		bool gp_initiated = false;
997 
998 		if (kthread_should_stop())
999 			goto checkwait;
1000 
1001 		/* Wait for the next test interval. */
1002 		oldstarttime = READ_ONCE(boost_starttime);
1003 		while (time_before(jiffies, oldstarttime)) {
1004 			schedule_timeout_interruptible(oldstarttime - jiffies);
1005 			if (stutter_wait("rcu_torture_boost"))
1006 				sched_set_fifo_low(current);
1007 			if (torture_must_stop())
1008 				goto checkwait;
1009 		}
1010 
1011 		// Do one boost-test interval.
1012 		endtime = oldstarttime + test_boost_duration * HZ;
1013 		while (time_before(jiffies, endtime)) {
1014 			// Has current GP gone too long?
1015 			if (gp_initiated && !failed && !cur_ops->poll_gp_state(gp_state))
1016 				failed = rcu_torture_boost_failed(gp_state, &gp_state_time);
1017 			// If we don't have a grace period in flight, start one.
1018 			if (!gp_initiated || cur_ops->poll_gp_state(gp_state)) {
1019 				gp_state = cur_ops->start_gp_poll();
1020 				gp_initiated = true;
1021 				gp_state_time = jiffies;
1022 			}
1023 			if (stutter_wait("rcu_torture_boost")) {
1024 				sched_set_fifo_low(current);
1025 				// If the grace period already ended,
1026 				// we don't know when that happened, so
1027 				// start over.
1028 				if (cur_ops->poll_gp_state(gp_state))
1029 					gp_initiated = false;
1030 			}
1031 			if (torture_must_stop())
1032 				goto checkwait;
1033 		}
1034 
1035 		// In case the grace period extended beyond the end of the loop.
1036 		if (gp_initiated && !failed && !cur_ops->poll_gp_state(gp_state))
1037 			rcu_torture_boost_failed(gp_state, &gp_state_time);
1038 
1039 		/*
1040 		 * Set the start time of the next test interval.
1041 		 * Yes, this is vulnerable to long delays, but such
1042 		 * delays simply cause a false negative for the next
1043 		 * interval.  Besides, we are running at RT priority,
1044 		 * so delays should be relatively rare.
1045 		 */
1046 		while (oldstarttime == READ_ONCE(boost_starttime) && !kthread_should_stop()) {
1047 			if (mutex_trylock(&boost_mutex)) {
1048 				if (oldstarttime == boost_starttime) {
1049 					WRITE_ONCE(boost_starttime,
1050 						   jiffies + test_boost_interval * HZ);
1051 					n_rcu_torture_boosts++;
1052 				}
1053 				mutex_unlock(&boost_mutex);
1054 				break;
1055 			}
1056 			schedule_timeout_uninterruptible(1);
1057 		}
1058 
1059 		/* Go do the stutter. */
1060 checkwait:	if (stutter_wait("rcu_torture_boost"))
1061 			sched_set_fifo_low(current);
1062 	} while (!torture_must_stop());
1063 
1064 	/* Clean up and exit. */
1065 	while (!kthread_should_stop()) {
1066 		torture_shutdown_absorb("rcu_torture_boost");
1067 		schedule_timeout_uninterruptible(1);
1068 	}
1069 	torture_kthread_stopping("rcu_torture_boost");
1070 	return 0;
1071 }
1072 
1073 /*
1074  * RCU torture force-quiescent-state kthread.  Repeatedly induces
1075  * bursts of calls to force_quiescent_state(), increasing the probability
1076  * of occurrence of some important types of race conditions.
1077  */
1078 static int
1079 rcu_torture_fqs(void *arg)
1080 {
1081 	unsigned long fqs_resume_time;
1082 	int fqs_burst_remaining;
1083 	int oldnice = task_nice(current);
1084 
1085 	VERBOSE_TOROUT_STRING("rcu_torture_fqs task started");
1086 	do {
1087 		fqs_resume_time = jiffies + fqs_stutter * HZ;
1088 		while (time_before(jiffies, fqs_resume_time) &&
1089 		       !kthread_should_stop()) {
1090 			schedule_timeout_interruptible(1);
1091 		}
1092 		fqs_burst_remaining = fqs_duration;
1093 		while (fqs_burst_remaining > 0 &&
1094 		       !kthread_should_stop()) {
1095 			cur_ops->fqs();
1096 			udelay(fqs_holdoff);
1097 			fqs_burst_remaining -= fqs_holdoff;
1098 		}
1099 		if (stutter_wait("rcu_torture_fqs"))
1100 			sched_set_normal(current, oldnice);
1101 	} while (!torture_must_stop());
1102 	torture_kthread_stopping("rcu_torture_fqs");
1103 	return 0;
1104 }
1105 
1106 // Used by writers to randomly choose from the available grace-period
1107 // primitives.  The only purpose of the initialization is to size the array.
1108 static int synctype[] = { RTWS_DEF_FREE, RTWS_EXP_SYNC, RTWS_COND_GET, RTWS_POLL_GET, RTWS_SYNC };
1109 static int nsynctypes;
1110 
1111 /*
1112  * Determine which grace-period primitives are available.
1113  */
1114 static void rcu_torture_write_types(void)
1115 {
1116 	bool gp_cond1 = gp_cond, gp_exp1 = gp_exp, gp_normal1 = gp_normal;
1117 	bool gp_poll1 = gp_poll, gp_sync1 = gp_sync;
1118 
1119 	/* Initialize synctype[] array.  If none set, take default. */
1120 	if (!gp_cond1 && !gp_exp1 && !gp_normal1 && !gp_poll1 && !gp_sync1)
1121 		gp_cond1 = gp_exp1 = gp_normal1 = gp_poll1 = gp_sync1 = true;
1122 	if (gp_cond1 && cur_ops->get_gp_state && cur_ops->cond_sync) {
1123 		synctype[nsynctypes++] = RTWS_COND_GET;
1124 		pr_info("%s: Testing conditional GPs.\n", __func__);
1125 	} else if (gp_cond && (!cur_ops->get_gp_state || !cur_ops->cond_sync)) {
1126 		pr_alert("%s: gp_cond without primitives.\n", __func__);
1127 	}
1128 	if (gp_exp1 && cur_ops->exp_sync) {
1129 		synctype[nsynctypes++] = RTWS_EXP_SYNC;
1130 		pr_info("%s: Testing expedited GPs.\n", __func__);
1131 	} else if (gp_exp && !cur_ops->exp_sync) {
1132 		pr_alert("%s: gp_exp without primitives.\n", __func__);
1133 	}
1134 	if (gp_normal1 && cur_ops->deferred_free) {
1135 		synctype[nsynctypes++] = RTWS_DEF_FREE;
1136 		pr_info("%s: Testing asynchronous GPs.\n", __func__);
1137 	} else if (gp_normal && !cur_ops->deferred_free) {
1138 		pr_alert("%s: gp_normal without primitives.\n", __func__);
1139 	}
1140 	if (gp_poll1 && cur_ops->start_gp_poll && cur_ops->poll_gp_state) {
1141 		synctype[nsynctypes++] = RTWS_POLL_GET;
1142 		pr_info("%s: Testing polling GPs.\n", __func__);
1143 	} else if (gp_poll && (!cur_ops->start_gp_poll || !cur_ops->poll_gp_state)) {
1144 		pr_alert("%s: gp_poll without primitives.\n", __func__);
1145 	}
1146 	if (gp_sync1 && cur_ops->sync) {
1147 		synctype[nsynctypes++] = RTWS_SYNC;
1148 		pr_info("%s: Testing normal GPs.\n", __func__);
1149 	} else if (gp_sync && !cur_ops->sync) {
1150 		pr_alert("%s: gp_sync without primitives.\n", __func__);
1151 	}
1152 }
1153 
1154 /*
1155  * RCU torture writer kthread.  Repeatedly substitutes a new structure
1156  * for that pointed to by rcu_torture_current, freeing the old structure
1157  * after a series of grace periods (the "pipeline").
1158  */
1159 static int
1160 rcu_torture_writer(void *arg)
1161 {
1162 	bool boot_ended;
1163 	bool can_expedite = !rcu_gp_is_expedited() && !rcu_gp_is_normal();
1164 	unsigned long cookie;
1165 	int expediting = 0;
1166 	unsigned long gp_snap;
1167 	int i;
1168 	int idx;
1169 	int oldnice = task_nice(current);
1170 	struct rcu_torture *rp;
1171 	struct rcu_torture *old_rp;
1172 	static DEFINE_TORTURE_RANDOM(rand);
1173 	bool stutter_waited;
1174 
1175 	VERBOSE_TOROUT_STRING("rcu_torture_writer task started");
1176 	if (!can_expedite)
1177 		pr_alert("%s" TORTURE_FLAG
1178 			 " GP expediting controlled from boot/sysfs for %s.\n",
1179 			 torture_type, cur_ops->name);
1180 	if (WARN_ONCE(nsynctypes == 0,
1181 		      "rcu_torture_writer: No update-side primitives.\n")) {
1182 		/*
1183 		 * No updates primitives, so don't try updating.
1184 		 * The resulting test won't be testing much, hence the
1185 		 * above WARN_ONCE().
1186 		 */
1187 		rcu_torture_writer_state = RTWS_STOPPING;
1188 		torture_kthread_stopping("rcu_torture_writer");
1189 	}
1190 
1191 	do {
1192 		rcu_torture_writer_state = RTWS_FIXED_DELAY;
1193 		torture_hrtimeout_us(500, 1000, &rand);
1194 		rp = rcu_torture_alloc();
1195 		if (rp == NULL)
1196 			continue;
1197 		rp->rtort_pipe_count = 0;
1198 		rcu_torture_writer_state = RTWS_DELAY;
1199 		udelay(torture_random(&rand) & 0x3ff);
1200 		rcu_torture_writer_state = RTWS_REPLACE;
1201 		old_rp = rcu_dereference_check(rcu_torture_current,
1202 					       current == writer_task);
1203 		rp->rtort_mbtest = 1;
1204 		rcu_assign_pointer(rcu_torture_current, rp);
1205 		smp_wmb(); /* Mods to old_rp must follow rcu_assign_pointer() */
1206 		if (old_rp) {
1207 			i = old_rp->rtort_pipe_count;
1208 			if (i > RCU_TORTURE_PIPE_LEN)
1209 				i = RCU_TORTURE_PIPE_LEN;
1210 			atomic_inc(&rcu_torture_wcount[i]);
1211 			WRITE_ONCE(old_rp->rtort_pipe_count,
1212 				   old_rp->rtort_pipe_count + 1);
1213 			if (cur_ops->get_gp_state && cur_ops->poll_gp_state) {
1214 				idx = cur_ops->readlock();
1215 				cookie = cur_ops->get_gp_state();
1216 				WARN_ONCE(rcu_torture_writer_state != RTWS_DEF_FREE &&
1217 					  cur_ops->poll_gp_state(cookie),
1218 					  "%s: Cookie check 1 failed %s(%d) %lu->%lu\n",
1219 					  __func__,
1220 					  rcu_torture_writer_state_getname(),
1221 					  rcu_torture_writer_state,
1222 					  cookie, cur_ops->get_gp_state());
1223 				cur_ops->readunlock(idx);
1224 			}
1225 			switch (synctype[torture_random(&rand) % nsynctypes]) {
1226 			case RTWS_DEF_FREE:
1227 				rcu_torture_writer_state = RTWS_DEF_FREE;
1228 				cur_ops->deferred_free(old_rp);
1229 				break;
1230 			case RTWS_EXP_SYNC:
1231 				rcu_torture_writer_state = RTWS_EXP_SYNC;
1232 				cur_ops->exp_sync();
1233 				rcu_torture_pipe_update(old_rp);
1234 				break;
1235 			case RTWS_COND_GET:
1236 				rcu_torture_writer_state = RTWS_COND_GET;
1237 				gp_snap = cur_ops->get_gp_state();
1238 				torture_hrtimeout_jiffies(torture_random(&rand) % 16, &rand);
1239 				rcu_torture_writer_state = RTWS_COND_SYNC;
1240 				cur_ops->cond_sync(gp_snap);
1241 				rcu_torture_pipe_update(old_rp);
1242 				break;
1243 			case RTWS_POLL_GET:
1244 				rcu_torture_writer_state = RTWS_POLL_GET;
1245 				gp_snap = cur_ops->start_gp_poll();
1246 				rcu_torture_writer_state = RTWS_POLL_WAIT;
1247 				while (!cur_ops->poll_gp_state(gp_snap))
1248 					torture_hrtimeout_jiffies(torture_random(&rand) % 16,
1249 								  &rand);
1250 				rcu_torture_pipe_update(old_rp);
1251 				break;
1252 			case RTWS_SYNC:
1253 				rcu_torture_writer_state = RTWS_SYNC;
1254 				cur_ops->sync();
1255 				rcu_torture_pipe_update(old_rp);
1256 				break;
1257 			default:
1258 				WARN_ON_ONCE(1);
1259 				break;
1260 			}
1261 		}
1262 		WRITE_ONCE(rcu_torture_current_version,
1263 			   rcu_torture_current_version + 1);
1264 		/* Cycle through nesting levels of rcu_expedite_gp() calls. */
1265 		if (can_expedite &&
1266 		    !(torture_random(&rand) & 0xff & (!!expediting - 1))) {
1267 			WARN_ON_ONCE(expediting == 0 && rcu_gp_is_expedited());
1268 			if (expediting >= 0)
1269 				rcu_expedite_gp();
1270 			else
1271 				rcu_unexpedite_gp();
1272 			if (++expediting > 3)
1273 				expediting = -expediting;
1274 		} else if (!can_expedite) { /* Disabled during boot, recheck. */
1275 			can_expedite = !rcu_gp_is_expedited() &&
1276 				       !rcu_gp_is_normal();
1277 		}
1278 		rcu_torture_writer_state = RTWS_STUTTER;
1279 		boot_ended = rcu_inkernel_boot_has_ended();
1280 		stutter_waited = stutter_wait("rcu_torture_writer");
1281 		if (stutter_waited &&
1282 		    !atomic_read(&rcu_fwd_cb_nodelay) &&
1283 		    !cur_ops->slow_gps &&
1284 		    !torture_must_stop() &&
1285 		    boot_ended)
1286 			for (i = 0; i < ARRAY_SIZE(rcu_tortures); i++)
1287 				if (list_empty(&rcu_tortures[i].rtort_free) &&
1288 				    rcu_access_pointer(rcu_torture_current) !=
1289 				    &rcu_tortures[i]) {
1290 					rcu_ftrace_dump(DUMP_ALL);
1291 					WARN(1, "%s: rtort_pipe_count: %d\n", __func__, rcu_tortures[i].rtort_pipe_count);
1292 				}
1293 		if (stutter_waited)
1294 			sched_set_normal(current, oldnice);
1295 	} while (!torture_must_stop());
1296 	rcu_torture_current = NULL;  // Let stats task know that we are done.
1297 	/* Reset expediting back to unexpedited. */
1298 	if (expediting > 0)
1299 		expediting = -expediting;
1300 	while (can_expedite && expediting++ < 0)
1301 		rcu_unexpedite_gp();
1302 	WARN_ON_ONCE(can_expedite && rcu_gp_is_expedited());
1303 	if (!can_expedite)
1304 		pr_alert("%s" TORTURE_FLAG
1305 			 " Dynamic grace-period expediting was disabled.\n",
1306 			 torture_type);
1307 	rcu_torture_writer_state = RTWS_STOPPING;
1308 	torture_kthread_stopping("rcu_torture_writer");
1309 	return 0;
1310 }
1311 
1312 /*
1313  * RCU torture fake writer kthread.  Repeatedly calls sync, with a random
1314  * delay between calls.
1315  */
1316 static int
1317 rcu_torture_fakewriter(void *arg)
1318 {
1319 	unsigned long gp_snap;
1320 	DEFINE_TORTURE_RANDOM(rand);
1321 
1322 	VERBOSE_TOROUT_STRING("rcu_torture_fakewriter task started");
1323 	set_user_nice(current, MAX_NICE);
1324 
1325 	do {
1326 		torture_hrtimeout_jiffies(torture_random(&rand) % 10, &rand);
1327 		if (cur_ops->cb_barrier != NULL &&
1328 		    torture_random(&rand) % (nfakewriters * 8) == 0) {
1329 			cur_ops->cb_barrier();
1330 		} else {
1331 			switch (synctype[torture_random(&rand) % nsynctypes]) {
1332 			case RTWS_DEF_FREE:
1333 				break;
1334 			case RTWS_EXP_SYNC:
1335 				cur_ops->exp_sync();
1336 				break;
1337 			case RTWS_COND_GET:
1338 				gp_snap = cur_ops->get_gp_state();
1339 				torture_hrtimeout_jiffies(torture_random(&rand) % 16, &rand);
1340 				cur_ops->cond_sync(gp_snap);
1341 				break;
1342 			case RTWS_POLL_GET:
1343 				gp_snap = cur_ops->start_gp_poll();
1344 				while (!cur_ops->poll_gp_state(gp_snap)) {
1345 					torture_hrtimeout_jiffies(torture_random(&rand) % 16,
1346 								  &rand);
1347 				}
1348 				break;
1349 			case RTWS_SYNC:
1350 				cur_ops->sync();
1351 				break;
1352 			default:
1353 				WARN_ON_ONCE(1);
1354 				break;
1355 			}
1356 		}
1357 		stutter_wait("rcu_torture_fakewriter");
1358 	} while (!torture_must_stop());
1359 
1360 	torture_kthread_stopping("rcu_torture_fakewriter");
1361 	return 0;
1362 }
1363 
1364 static void rcu_torture_timer_cb(struct rcu_head *rhp)
1365 {
1366 	kfree(rhp);
1367 }
1368 
1369 // Set up and carry out testing of RCU's global memory ordering
1370 static void rcu_torture_reader_do_mbchk(long myid, struct rcu_torture *rtp,
1371 					struct torture_random_state *trsp)
1372 {
1373 	unsigned long loops;
1374 	int noc = torture_num_online_cpus();
1375 	int rdrchked;
1376 	int rdrchker;
1377 	struct rcu_torture_reader_check *rtrcp; // Me.
1378 	struct rcu_torture_reader_check *rtrcp_assigner; // Assigned us to do checking.
1379 	struct rcu_torture_reader_check *rtrcp_chked; // Reader being checked.
1380 	struct rcu_torture_reader_check *rtrcp_chker; // Reader doing checking when not me.
1381 
1382 	if (myid < 0)
1383 		return; // Don't try this from timer handlers.
1384 
1385 	// Increment my counter.
1386 	rtrcp = &rcu_torture_reader_mbchk[myid];
1387 	WRITE_ONCE(rtrcp->rtc_myloops, rtrcp->rtc_myloops + 1);
1388 
1389 	// Attempt to assign someone else some checking work.
1390 	rdrchked = torture_random(trsp) % nrealreaders;
1391 	rtrcp_chked = &rcu_torture_reader_mbchk[rdrchked];
1392 	rdrchker = torture_random(trsp) % nrealreaders;
1393 	rtrcp_chker = &rcu_torture_reader_mbchk[rdrchker];
1394 	if (rdrchked != myid && rdrchked != rdrchker && noc >= rdrchked && noc >= rdrchker &&
1395 	    smp_load_acquire(&rtrcp->rtc_chkrdr) < 0 && // Pairs with smp_store_release below.
1396 	    !READ_ONCE(rtp->rtort_chkp) &&
1397 	    !smp_load_acquire(&rtrcp_chker->rtc_assigner)) { // Pairs with smp_store_release below.
1398 		rtrcp->rtc_chkloops = READ_ONCE(rtrcp_chked->rtc_myloops);
1399 		WARN_ON_ONCE(rtrcp->rtc_chkrdr >= 0);
1400 		rtrcp->rtc_chkrdr = rdrchked;
1401 		WARN_ON_ONCE(rtrcp->rtc_ready); // This gets set after the grace period ends.
1402 		if (cmpxchg_relaxed(&rtrcp_chker->rtc_assigner, NULL, rtrcp) ||
1403 		    cmpxchg_relaxed(&rtp->rtort_chkp, NULL, rtrcp))
1404 			(void)cmpxchg_relaxed(&rtrcp_chker->rtc_assigner, rtrcp, NULL); // Back out.
1405 	}
1406 
1407 	// If assigned some completed work, do it!
1408 	rtrcp_assigner = READ_ONCE(rtrcp->rtc_assigner);
1409 	if (!rtrcp_assigner || !smp_load_acquire(&rtrcp_assigner->rtc_ready))
1410 		return; // No work or work not yet ready.
1411 	rdrchked = rtrcp_assigner->rtc_chkrdr;
1412 	if (WARN_ON_ONCE(rdrchked < 0))
1413 		return;
1414 	rtrcp_chked = &rcu_torture_reader_mbchk[rdrchked];
1415 	loops = READ_ONCE(rtrcp_chked->rtc_myloops);
1416 	atomic_inc(&n_rcu_torture_mbchk_tries);
1417 	if (ULONG_CMP_LT(loops, rtrcp_assigner->rtc_chkloops))
1418 		atomic_inc(&n_rcu_torture_mbchk_fail);
1419 	rtrcp_assigner->rtc_chkloops = loops + ULONG_MAX / 2;
1420 	rtrcp_assigner->rtc_ready = 0;
1421 	smp_store_release(&rtrcp->rtc_assigner, NULL); // Someone else can assign us work.
1422 	smp_store_release(&rtrcp_assigner->rtc_chkrdr, -1); // Assigner can again assign.
1423 }
1424 
1425 /*
1426  * Do one extension of an RCU read-side critical section using the
1427  * current reader state in readstate (set to zero for initial entry
1428  * to extended critical section), set the new state as specified by
1429  * newstate (set to zero for final exit from extended critical section),
1430  * and random-number-generator state in trsp.  If this is neither the
1431  * beginning or end of the critical section and if there was actually a
1432  * change, do a ->read_delay().
1433  */
1434 static void rcutorture_one_extend(int *readstate, int newstate,
1435 				  struct torture_random_state *trsp,
1436 				  struct rt_read_seg *rtrsp)
1437 {
1438 	unsigned long flags;
1439 	int idxnew1 = -1;
1440 	int idxnew2 = -1;
1441 	int idxold1 = *readstate;
1442 	int idxold2 = idxold1;
1443 	int statesnew = ~*readstate & newstate;
1444 	int statesold = *readstate & ~newstate;
1445 
1446 	WARN_ON_ONCE(idxold2 < 0);
1447 	WARN_ON_ONCE((idxold2 >> RCUTORTURE_RDR_SHIFT_2) > 1);
1448 	rtrsp->rt_readstate = newstate;
1449 
1450 	/* First, put new protection in place to avoid critical-section gap. */
1451 	if (statesnew & RCUTORTURE_RDR_BH)
1452 		local_bh_disable();
1453 	if (statesnew & RCUTORTURE_RDR_RBH)
1454 		rcu_read_lock_bh();
1455 	if (statesnew & RCUTORTURE_RDR_IRQ)
1456 		local_irq_disable();
1457 	if (statesnew & RCUTORTURE_RDR_PREEMPT)
1458 		preempt_disable();
1459 	if (statesnew & RCUTORTURE_RDR_SCHED)
1460 		rcu_read_lock_sched();
1461 	if (statesnew & RCUTORTURE_RDR_RCU_1)
1462 		idxnew1 = (cur_ops->readlock() & 0x1) << RCUTORTURE_RDR_SHIFT_1;
1463 	if (statesnew & RCUTORTURE_RDR_RCU_2)
1464 		idxnew2 = (cur_ops->readlock() & 0x1) << RCUTORTURE_RDR_SHIFT_2;
1465 
1466 	/*
1467 	 * Next, remove old protection, in decreasing order of strength
1468 	 * to avoid unlock paths that aren't safe in the stronger
1469 	 * context. Namely: BH can not be enabled with disabled interrupts.
1470 	 * Additionally PREEMPT_RT requires that BH is enabled in preemptible
1471 	 * context.
1472 	 */
1473 	if (statesold & RCUTORTURE_RDR_IRQ)
1474 		local_irq_enable();
1475 	if (statesold & RCUTORTURE_RDR_PREEMPT)
1476 		preempt_enable();
1477 	if (statesold & RCUTORTURE_RDR_SCHED)
1478 		rcu_read_unlock_sched();
1479 	if (statesold & RCUTORTURE_RDR_BH)
1480 		local_bh_enable();
1481 	if (statesold & RCUTORTURE_RDR_RBH)
1482 		rcu_read_unlock_bh();
1483 	if (statesold & RCUTORTURE_RDR_RCU_2) {
1484 		cur_ops->readunlock((idxold2 >> RCUTORTURE_RDR_SHIFT_2) & 0x1);
1485 		WARN_ON_ONCE(idxnew2 != -1);
1486 		idxold2 = 0;
1487 	}
1488 	if (statesold & RCUTORTURE_RDR_RCU_1) {
1489 		bool lockit;
1490 
1491 		lockit = !cur_ops->no_pi_lock && !statesnew && !(torture_random(trsp) & 0xffff);
1492 		if (lockit)
1493 			raw_spin_lock_irqsave(&current->pi_lock, flags);
1494 		cur_ops->readunlock((idxold1 >> RCUTORTURE_RDR_SHIFT_1) & 0x1);
1495 		WARN_ON_ONCE(idxnew1 != -1);
1496 		idxold1 = 0;
1497 		if (lockit)
1498 			raw_spin_unlock_irqrestore(&current->pi_lock, flags);
1499 	}
1500 
1501 	/* Delay if neither beginning nor end and there was a change. */
1502 	if ((statesnew || statesold) && *readstate && newstate)
1503 		cur_ops->read_delay(trsp, rtrsp);
1504 
1505 	/* Update the reader state. */
1506 	if (idxnew1 == -1)
1507 		idxnew1 = idxold1 & RCUTORTURE_RDR_MASK_1;
1508 	WARN_ON_ONCE(idxnew1 < 0);
1509 	if (WARN_ON_ONCE((idxnew1 >> RCUTORTURE_RDR_SHIFT_1) > 1))
1510 		pr_info("Unexpected idxnew1 value of %#x\n", idxnew1);
1511 	if (idxnew2 == -1)
1512 		idxnew2 = idxold2 & RCUTORTURE_RDR_MASK_2;
1513 	WARN_ON_ONCE(idxnew2 < 0);
1514 	WARN_ON_ONCE((idxnew2 >> RCUTORTURE_RDR_SHIFT_2) > 1);
1515 	*readstate = idxnew1 | idxnew2 | newstate;
1516 	WARN_ON_ONCE(*readstate < 0);
1517 	if (WARN_ON_ONCE((*readstate >> RCUTORTURE_RDR_SHIFT_2) > 1))
1518 		pr_info("Unexpected idxnew2 value of %#x\n", idxnew2);
1519 }
1520 
1521 /* Return the biggest extendables mask given current RCU and boot parameters. */
1522 static int rcutorture_extend_mask_max(void)
1523 {
1524 	int mask;
1525 
1526 	WARN_ON_ONCE(extendables & ~RCUTORTURE_MAX_EXTEND);
1527 	mask = extendables & RCUTORTURE_MAX_EXTEND & cur_ops->extendables;
1528 	mask = mask | RCUTORTURE_RDR_RCU_1 | RCUTORTURE_RDR_RCU_2;
1529 	return mask;
1530 }
1531 
1532 /* Return a random protection state mask, but with at least one bit set. */
1533 static int
1534 rcutorture_extend_mask(int oldmask, struct torture_random_state *trsp)
1535 {
1536 	int mask = rcutorture_extend_mask_max();
1537 	unsigned long randmask1 = torture_random(trsp) >> 8;
1538 	unsigned long randmask2 = randmask1 >> 3;
1539 	unsigned long preempts = RCUTORTURE_RDR_PREEMPT | RCUTORTURE_RDR_SCHED;
1540 	unsigned long preempts_irq = preempts | RCUTORTURE_RDR_IRQ;
1541 	unsigned long bhs = RCUTORTURE_RDR_BH | RCUTORTURE_RDR_RBH;
1542 
1543 	WARN_ON_ONCE(mask >> RCUTORTURE_RDR_SHIFT_1);
1544 	/* Mostly only one bit (need preemption!), sometimes lots of bits. */
1545 	if (!(randmask1 & 0x7))
1546 		mask = mask & randmask2;
1547 	else
1548 		mask = mask & (1 << (randmask2 % RCUTORTURE_RDR_NBITS));
1549 
1550 	// Can't have nested RCU reader without outer RCU reader.
1551 	if (!(mask & RCUTORTURE_RDR_RCU_1) && (mask & RCUTORTURE_RDR_RCU_2)) {
1552 		if (oldmask & RCUTORTURE_RDR_RCU_1)
1553 			mask &= ~RCUTORTURE_RDR_RCU_2;
1554 		else
1555 			mask |= RCUTORTURE_RDR_RCU_1;
1556 	}
1557 
1558 	/*
1559 	 * Can't enable bh w/irq disabled.
1560 	 */
1561 	if (mask & RCUTORTURE_RDR_IRQ)
1562 		mask |= oldmask & bhs;
1563 
1564 	/*
1565 	 * Ideally these sequences would be detected in debug builds
1566 	 * (regardless of RT), but until then don't stop testing
1567 	 * them on non-RT.
1568 	 */
1569 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
1570 		/* Can't modify BH in atomic context */
1571 		if (oldmask & preempts_irq)
1572 			mask &= ~bhs;
1573 		if ((oldmask | mask) & preempts_irq)
1574 			mask |= oldmask & bhs;
1575 	}
1576 
1577 	return mask ?: RCUTORTURE_RDR_RCU_1;
1578 }
1579 
1580 /*
1581  * Do a randomly selected number of extensions of an existing RCU read-side
1582  * critical section.
1583  */
1584 static struct rt_read_seg *
1585 rcutorture_loop_extend(int *readstate, struct torture_random_state *trsp,
1586 		       struct rt_read_seg *rtrsp)
1587 {
1588 	int i;
1589 	int j;
1590 	int mask = rcutorture_extend_mask_max();
1591 
1592 	WARN_ON_ONCE(!*readstate); /* -Existing- RCU read-side critsect! */
1593 	if (!((mask - 1) & mask))
1594 		return rtrsp;  /* Current RCU reader not extendable. */
1595 	/* Bias towards larger numbers of loops. */
1596 	i = (torture_random(trsp) >> 3);
1597 	i = ((i | (i >> 3)) & RCUTORTURE_RDR_MAX_LOOPS) + 1;
1598 	for (j = 0; j < i; j++) {
1599 		mask = rcutorture_extend_mask(*readstate, trsp);
1600 		rcutorture_one_extend(readstate, mask, trsp, &rtrsp[j]);
1601 	}
1602 	return &rtrsp[j];
1603 }
1604 
1605 /*
1606  * Do one read-side critical section, returning false if there was
1607  * no data to read.  Can be invoked both from process context and
1608  * from a timer handler.
1609  */
1610 static bool rcu_torture_one_read(struct torture_random_state *trsp, long myid)
1611 {
1612 	unsigned long cookie;
1613 	int i;
1614 	unsigned long started;
1615 	unsigned long completed;
1616 	int newstate;
1617 	struct rcu_torture *p;
1618 	int pipe_count;
1619 	int readstate = 0;
1620 	struct rt_read_seg rtseg[RCUTORTURE_RDR_MAX_SEGS] = { { 0 } };
1621 	struct rt_read_seg *rtrsp = &rtseg[0];
1622 	struct rt_read_seg *rtrsp1;
1623 	unsigned long long ts;
1624 
1625 	WARN_ON_ONCE(!rcu_is_watching());
1626 	newstate = rcutorture_extend_mask(readstate, trsp);
1627 	rcutorture_one_extend(&readstate, newstate, trsp, rtrsp++);
1628 	if (cur_ops->get_gp_state && cur_ops->poll_gp_state)
1629 		cookie = cur_ops->get_gp_state();
1630 	started = cur_ops->get_gp_seq();
1631 	ts = rcu_trace_clock_local();
1632 	p = rcu_dereference_check(rcu_torture_current,
1633 				  !cur_ops->readlock_held || cur_ops->readlock_held());
1634 	if (p == NULL) {
1635 		/* Wait for rcu_torture_writer to get underway */
1636 		rcutorture_one_extend(&readstate, 0, trsp, rtrsp);
1637 		return false;
1638 	}
1639 	if (p->rtort_mbtest == 0)
1640 		atomic_inc(&n_rcu_torture_mberror);
1641 	rcu_torture_reader_do_mbchk(myid, p, trsp);
1642 	rtrsp = rcutorture_loop_extend(&readstate, trsp, rtrsp);
1643 	preempt_disable();
1644 	pipe_count = READ_ONCE(p->rtort_pipe_count);
1645 	if (pipe_count > RCU_TORTURE_PIPE_LEN) {
1646 		/* Should not happen, but... */
1647 		pipe_count = RCU_TORTURE_PIPE_LEN;
1648 	}
1649 	completed = cur_ops->get_gp_seq();
1650 	if (pipe_count > 1) {
1651 		do_trace_rcu_torture_read(cur_ops->name, &p->rtort_rcu,
1652 					  ts, started, completed);
1653 		rcu_ftrace_dump(DUMP_ALL);
1654 	}
1655 	__this_cpu_inc(rcu_torture_count[pipe_count]);
1656 	completed = rcutorture_seq_diff(completed, started);
1657 	if (completed > RCU_TORTURE_PIPE_LEN) {
1658 		/* Should not happen, but... */
1659 		completed = RCU_TORTURE_PIPE_LEN;
1660 	}
1661 	__this_cpu_inc(rcu_torture_batch[completed]);
1662 	preempt_enable();
1663 	if (cur_ops->get_gp_state && cur_ops->poll_gp_state)
1664 		WARN_ONCE(cur_ops->poll_gp_state(cookie),
1665 			  "%s: Cookie check 2 failed %s(%d) %lu->%lu\n",
1666 			  __func__,
1667 			  rcu_torture_writer_state_getname(),
1668 			  rcu_torture_writer_state,
1669 			  cookie, cur_ops->get_gp_state());
1670 	rcutorture_one_extend(&readstate, 0, trsp, rtrsp);
1671 	WARN_ON_ONCE(readstate);
1672 	// This next splat is expected behavior if leakpointer, especially
1673 	// for CONFIG_RCU_STRICT_GRACE_PERIOD=y kernels.
1674 	WARN_ON_ONCE(leakpointer && READ_ONCE(p->rtort_pipe_count) > 1);
1675 
1676 	/* If error or close call, record the sequence of reader protections. */
1677 	if ((pipe_count > 1 || completed > 1) && !xchg(&err_segs_recorded, 1)) {
1678 		i = 0;
1679 		for (rtrsp1 = &rtseg[0]; rtrsp1 < rtrsp; rtrsp1++)
1680 			err_segs[i++] = *rtrsp1;
1681 		rt_read_nsegs = i;
1682 	}
1683 
1684 	return true;
1685 }
1686 
1687 static DEFINE_TORTURE_RANDOM_PERCPU(rcu_torture_timer_rand);
1688 
1689 /*
1690  * RCU torture reader from timer handler.  Dereferences rcu_torture_current,
1691  * incrementing the corresponding element of the pipeline array.  The
1692  * counter in the element should never be greater than 1, otherwise, the
1693  * RCU implementation is broken.
1694  */
1695 static void rcu_torture_timer(struct timer_list *unused)
1696 {
1697 	atomic_long_inc(&n_rcu_torture_timers);
1698 	(void)rcu_torture_one_read(this_cpu_ptr(&rcu_torture_timer_rand), -1);
1699 
1700 	/* Test call_rcu() invocation from interrupt handler. */
1701 	if (cur_ops->call) {
1702 		struct rcu_head *rhp = kmalloc(sizeof(*rhp), GFP_NOWAIT);
1703 
1704 		if (rhp)
1705 			cur_ops->call(rhp, rcu_torture_timer_cb);
1706 	}
1707 }
1708 
1709 /*
1710  * RCU torture reader kthread.  Repeatedly dereferences rcu_torture_current,
1711  * incrementing the corresponding element of the pipeline array.  The
1712  * counter in the element should never be greater than 1, otherwise, the
1713  * RCU implementation is broken.
1714  */
1715 static int
1716 rcu_torture_reader(void *arg)
1717 {
1718 	unsigned long lastsleep = jiffies;
1719 	long myid = (long)arg;
1720 	int mynumonline = myid;
1721 	DEFINE_TORTURE_RANDOM(rand);
1722 	struct timer_list t;
1723 
1724 	VERBOSE_TOROUT_STRING("rcu_torture_reader task started");
1725 	set_user_nice(current, MAX_NICE);
1726 	if (irqreader && cur_ops->irq_capable)
1727 		timer_setup_on_stack(&t, rcu_torture_timer, 0);
1728 	tick_dep_set_task(current, TICK_DEP_BIT_RCU);
1729 	do {
1730 		if (irqreader && cur_ops->irq_capable) {
1731 			if (!timer_pending(&t))
1732 				mod_timer(&t, jiffies + 1);
1733 		}
1734 		if (!rcu_torture_one_read(&rand, myid) && !torture_must_stop())
1735 			schedule_timeout_interruptible(HZ);
1736 		if (time_after(jiffies, lastsleep) && !torture_must_stop()) {
1737 			torture_hrtimeout_us(500, 1000, &rand);
1738 			lastsleep = jiffies + 10;
1739 		}
1740 		while (torture_num_online_cpus() < mynumonline && !torture_must_stop())
1741 			schedule_timeout_interruptible(HZ / 5);
1742 		stutter_wait("rcu_torture_reader");
1743 	} while (!torture_must_stop());
1744 	if (irqreader && cur_ops->irq_capable) {
1745 		del_timer_sync(&t);
1746 		destroy_timer_on_stack(&t);
1747 	}
1748 	tick_dep_clear_task(current, TICK_DEP_BIT_RCU);
1749 	torture_kthread_stopping("rcu_torture_reader");
1750 	return 0;
1751 }
1752 
1753 /*
1754  * Randomly Toggle CPUs' callback-offload state.  This uses hrtimers to
1755  * increase race probabilities and fuzzes the interval between toggling.
1756  */
1757 static int rcu_nocb_toggle(void *arg)
1758 {
1759 	int cpu;
1760 	int maxcpu = -1;
1761 	int oldnice = task_nice(current);
1762 	long r;
1763 	DEFINE_TORTURE_RANDOM(rand);
1764 	ktime_t toggle_delay;
1765 	unsigned long toggle_fuzz;
1766 	ktime_t toggle_interval = ms_to_ktime(nocbs_toggle);
1767 
1768 	VERBOSE_TOROUT_STRING("rcu_nocb_toggle task started");
1769 	while (!rcu_inkernel_boot_has_ended())
1770 		schedule_timeout_interruptible(HZ / 10);
1771 	for_each_online_cpu(cpu)
1772 		maxcpu = cpu;
1773 	WARN_ON(maxcpu < 0);
1774 	if (toggle_interval > ULONG_MAX)
1775 		toggle_fuzz = ULONG_MAX >> 3;
1776 	else
1777 		toggle_fuzz = toggle_interval >> 3;
1778 	if (toggle_fuzz <= 0)
1779 		toggle_fuzz = NSEC_PER_USEC;
1780 	do {
1781 		r = torture_random(&rand);
1782 		cpu = (r >> 4) % (maxcpu + 1);
1783 		if (r & 0x1) {
1784 			rcu_nocb_cpu_offload(cpu);
1785 			atomic_long_inc(&n_nocb_offload);
1786 		} else {
1787 			rcu_nocb_cpu_deoffload(cpu);
1788 			atomic_long_inc(&n_nocb_deoffload);
1789 		}
1790 		toggle_delay = torture_random(&rand) % toggle_fuzz + toggle_interval;
1791 		set_current_state(TASK_INTERRUPTIBLE);
1792 		schedule_hrtimeout(&toggle_delay, HRTIMER_MODE_REL);
1793 		if (stutter_wait("rcu_nocb_toggle"))
1794 			sched_set_normal(current, oldnice);
1795 	} while (!torture_must_stop());
1796 	torture_kthread_stopping("rcu_nocb_toggle");
1797 	return 0;
1798 }
1799 
1800 /*
1801  * Print torture statistics.  Caller must ensure that there is only
1802  * one call to this function at a given time!!!  This is normally
1803  * accomplished by relying on the module system to only have one copy
1804  * of the module loaded, and then by giving the rcu_torture_stats
1805  * kthread full control (or the init/cleanup functions when rcu_torture_stats
1806  * thread is not running).
1807  */
1808 static void
1809 rcu_torture_stats_print(void)
1810 {
1811 	int cpu;
1812 	int i;
1813 	long pipesummary[RCU_TORTURE_PIPE_LEN + 1] = { 0 };
1814 	long batchsummary[RCU_TORTURE_PIPE_LEN + 1] = { 0 };
1815 	struct rcu_torture *rtcp;
1816 	static unsigned long rtcv_snap = ULONG_MAX;
1817 	static bool splatted;
1818 	struct task_struct *wtp;
1819 
1820 	for_each_possible_cpu(cpu) {
1821 		for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++) {
1822 			pipesummary[i] += READ_ONCE(per_cpu(rcu_torture_count, cpu)[i]);
1823 			batchsummary[i] += READ_ONCE(per_cpu(rcu_torture_batch, cpu)[i]);
1824 		}
1825 	}
1826 	for (i = RCU_TORTURE_PIPE_LEN - 1; i >= 0; i--) {
1827 		if (pipesummary[i] != 0)
1828 			break;
1829 	}
1830 
1831 	pr_alert("%s%s ", torture_type, TORTURE_FLAG);
1832 	rtcp = rcu_access_pointer(rcu_torture_current);
1833 	pr_cont("rtc: %p %s: %lu tfle: %d rta: %d rtaf: %d rtf: %d ",
1834 		rtcp,
1835 		rtcp && !rcu_stall_is_suppressed_at_boot() ? "ver" : "VER",
1836 		rcu_torture_current_version,
1837 		list_empty(&rcu_torture_freelist),
1838 		atomic_read(&n_rcu_torture_alloc),
1839 		atomic_read(&n_rcu_torture_alloc_fail),
1840 		atomic_read(&n_rcu_torture_free));
1841 	pr_cont("rtmbe: %d rtmbkf: %d/%d rtbe: %ld rtbke: %ld rtbre: %ld ",
1842 		atomic_read(&n_rcu_torture_mberror),
1843 		atomic_read(&n_rcu_torture_mbchk_fail), atomic_read(&n_rcu_torture_mbchk_tries),
1844 		n_rcu_torture_barrier_error,
1845 		n_rcu_torture_boost_ktrerror,
1846 		n_rcu_torture_boost_rterror);
1847 	pr_cont("rtbf: %ld rtb: %ld nt: %ld ",
1848 		n_rcu_torture_boost_failure,
1849 		n_rcu_torture_boosts,
1850 		atomic_long_read(&n_rcu_torture_timers));
1851 	torture_onoff_stats();
1852 	pr_cont("barrier: %ld/%ld:%ld ",
1853 		data_race(n_barrier_successes),
1854 		data_race(n_barrier_attempts),
1855 		data_race(n_rcu_torture_barrier_error));
1856 	pr_cont("read-exits: %ld ", data_race(n_read_exits)); // Statistic.
1857 	pr_cont("nocb-toggles: %ld:%ld\n",
1858 		atomic_long_read(&n_nocb_offload), atomic_long_read(&n_nocb_deoffload));
1859 
1860 	pr_alert("%s%s ", torture_type, TORTURE_FLAG);
1861 	if (atomic_read(&n_rcu_torture_mberror) ||
1862 	    atomic_read(&n_rcu_torture_mbchk_fail) ||
1863 	    n_rcu_torture_barrier_error || n_rcu_torture_boost_ktrerror ||
1864 	    n_rcu_torture_boost_rterror || n_rcu_torture_boost_failure ||
1865 	    i > 1) {
1866 		pr_cont("%s", "!!! ");
1867 		atomic_inc(&n_rcu_torture_error);
1868 		WARN_ON_ONCE(atomic_read(&n_rcu_torture_mberror));
1869 		WARN_ON_ONCE(atomic_read(&n_rcu_torture_mbchk_fail));
1870 		WARN_ON_ONCE(n_rcu_torture_barrier_error);  // rcu_barrier()
1871 		WARN_ON_ONCE(n_rcu_torture_boost_ktrerror); // no boost kthread
1872 		WARN_ON_ONCE(n_rcu_torture_boost_rterror); // can't set RT prio
1873 		WARN_ON_ONCE(n_rcu_torture_boost_failure); // boost failed (TIMER_SOFTIRQ RT prio?)
1874 		WARN_ON_ONCE(i > 1); // Too-short grace period
1875 	}
1876 	pr_cont("Reader Pipe: ");
1877 	for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++)
1878 		pr_cont(" %ld", pipesummary[i]);
1879 	pr_cont("\n");
1880 
1881 	pr_alert("%s%s ", torture_type, TORTURE_FLAG);
1882 	pr_cont("Reader Batch: ");
1883 	for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++)
1884 		pr_cont(" %ld", batchsummary[i]);
1885 	pr_cont("\n");
1886 
1887 	pr_alert("%s%s ", torture_type, TORTURE_FLAG);
1888 	pr_cont("Free-Block Circulation: ");
1889 	for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++) {
1890 		pr_cont(" %d", atomic_read(&rcu_torture_wcount[i]));
1891 	}
1892 	pr_cont("\n");
1893 
1894 	if (cur_ops->stats)
1895 		cur_ops->stats();
1896 	if (rtcv_snap == rcu_torture_current_version &&
1897 	    rcu_access_pointer(rcu_torture_current) &&
1898 	    !rcu_stall_is_suppressed()) {
1899 		int __maybe_unused flags = 0;
1900 		unsigned long __maybe_unused gp_seq = 0;
1901 
1902 		rcutorture_get_gp_data(cur_ops->ttype,
1903 				       &flags, &gp_seq);
1904 		srcutorture_get_gp_data(cur_ops->ttype, srcu_ctlp,
1905 					&flags, &gp_seq);
1906 		wtp = READ_ONCE(writer_task);
1907 		pr_alert("??? Writer stall state %s(%d) g%lu f%#x ->state %#x cpu %d\n",
1908 			 rcu_torture_writer_state_getname(),
1909 			 rcu_torture_writer_state, gp_seq, flags,
1910 			 wtp == NULL ? ~0U : wtp->__state,
1911 			 wtp == NULL ? -1 : (int)task_cpu(wtp));
1912 		if (!splatted && wtp) {
1913 			sched_show_task(wtp);
1914 			splatted = true;
1915 		}
1916 		if (cur_ops->gp_kthread_dbg)
1917 			cur_ops->gp_kthread_dbg();
1918 		rcu_ftrace_dump(DUMP_ALL);
1919 	}
1920 	rtcv_snap = rcu_torture_current_version;
1921 }
1922 
1923 /*
1924  * Periodically prints torture statistics, if periodic statistics printing
1925  * was specified via the stat_interval module parameter.
1926  */
1927 static int
1928 rcu_torture_stats(void *arg)
1929 {
1930 	VERBOSE_TOROUT_STRING("rcu_torture_stats task started");
1931 	do {
1932 		schedule_timeout_interruptible(stat_interval * HZ);
1933 		rcu_torture_stats_print();
1934 		torture_shutdown_absorb("rcu_torture_stats");
1935 	} while (!torture_must_stop());
1936 	torture_kthread_stopping("rcu_torture_stats");
1937 	return 0;
1938 }
1939 
1940 /* Test mem_dump_obj() and friends.  */
1941 static void rcu_torture_mem_dump_obj(void)
1942 {
1943 	struct rcu_head *rhp;
1944 	struct kmem_cache *kcp;
1945 	static int z;
1946 
1947 	kcp = kmem_cache_create("rcuscale", 136, 8, SLAB_STORE_USER, NULL);
1948 	rhp = kmem_cache_alloc(kcp, GFP_KERNEL);
1949 	pr_alert("mem_dump_obj() slab test: rcu_torture_stats = %px, &rhp = %px, rhp = %px, &z = %px\n", stats_task, &rhp, rhp, &z);
1950 	pr_alert("mem_dump_obj(ZERO_SIZE_PTR):");
1951 	mem_dump_obj(ZERO_SIZE_PTR);
1952 	pr_alert("mem_dump_obj(NULL):");
1953 	mem_dump_obj(NULL);
1954 	pr_alert("mem_dump_obj(%px):", &rhp);
1955 	mem_dump_obj(&rhp);
1956 	pr_alert("mem_dump_obj(%px):", rhp);
1957 	mem_dump_obj(rhp);
1958 	pr_alert("mem_dump_obj(%px):", &rhp->func);
1959 	mem_dump_obj(&rhp->func);
1960 	pr_alert("mem_dump_obj(%px):", &z);
1961 	mem_dump_obj(&z);
1962 	kmem_cache_free(kcp, rhp);
1963 	kmem_cache_destroy(kcp);
1964 	rhp = kmalloc(sizeof(*rhp), GFP_KERNEL);
1965 	pr_alert("mem_dump_obj() kmalloc test: rcu_torture_stats = %px, &rhp = %px, rhp = %px\n", stats_task, &rhp, rhp);
1966 	pr_alert("mem_dump_obj(kmalloc %px):", rhp);
1967 	mem_dump_obj(rhp);
1968 	pr_alert("mem_dump_obj(kmalloc %px):", &rhp->func);
1969 	mem_dump_obj(&rhp->func);
1970 	kfree(rhp);
1971 	rhp = vmalloc(4096);
1972 	pr_alert("mem_dump_obj() vmalloc test: rcu_torture_stats = %px, &rhp = %px, rhp = %px\n", stats_task, &rhp, rhp);
1973 	pr_alert("mem_dump_obj(vmalloc %px):", rhp);
1974 	mem_dump_obj(rhp);
1975 	pr_alert("mem_dump_obj(vmalloc %px):", &rhp->func);
1976 	mem_dump_obj(&rhp->func);
1977 	vfree(rhp);
1978 }
1979 
1980 static void
1981 rcu_torture_print_module_parms(struct rcu_torture_ops *cur_ops, const char *tag)
1982 {
1983 	pr_alert("%s" TORTURE_FLAG
1984 		 "--- %s: nreaders=%d nfakewriters=%d "
1985 		 "stat_interval=%d verbose=%d test_no_idle_hz=%d "
1986 		 "shuffle_interval=%d stutter=%d irqreader=%d "
1987 		 "fqs_duration=%d fqs_holdoff=%d fqs_stutter=%d "
1988 		 "test_boost=%d/%d test_boost_interval=%d "
1989 		 "test_boost_duration=%d shutdown_secs=%d "
1990 		 "stall_cpu=%d stall_cpu_holdoff=%d stall_cpu_irqsoff=%d "
1991 		 "stall_cpu_block=%d "
1992 		 "n_barrier_cbs=%d "
1993 		 "onoff_interval=%d onoff_holdoff=%d "
1994 		 "read_exit_delay=%d read_exit_burst=%d "
1995 		 "nocbs_nthreads=%d nocbs_toggle=%d\n",
1996 		 torture_type, tag, nrealreaders, nfakewriters,
1997 		 stat_interval, verbose, test_no_idle_hz, shuffle_interval,
1998 		 stutter, irqreader, fqs_duration, fqs_holdoff, fqs_stutter,
1999 		 test_boost, cur_ops->can_boost,
2000 		 test_boost_interval, test_boost_duration, shutdown_secs,
2001 		 stall_cpu, stall_cpu_holdoff, stall_cpu_irqsoff,
2002 		 stall_cpu_block,
2003 		 n_barrier_cbs,
2004 		 onoff_interval, onoff_holdoff,
2005 		 read_exit_delay, read_exit_burst,
2006 		 nocbs_nthreads, nocbs_toggle);
2007 }
2008 
2009 static int rcutorture_booster_cleanup(unsigned int cpu)
2010 {
2011 	struct task_struct *t;
2012 
2013 	if (boost_tasks[cpu] == NULL)
2014 		return 0;
2015 	mutex_lock(&boost_mutex);
2016 	t = boost_tasks[cpu];
2017 	boost_tasks[cpu] = NULL;
2018 	rcu_torture_enable_rt_throttle();
2019 	mutex_unlock(&boost_mutex);
2020 
2021 	/* This must be outside of the mutex, otherwise deadlock! */
2022 	torture_stop_kthread(rcu_torture_boost, t);
2023 	return 0;
2024 }
2025 
2026 static int rcutorture_booster_init(unsigned int cpu)
2027 {
2028 	int retval;
2029 
2030 	if (boost_tasks[cpu] != NULL)
2031 		return 0;  /* Already created, nothing more to do. */
2032 
2033 	/* Don't allow time recalculation while creating a new task. */
2034 	mutex_lock(&boost_mutex);
2035 	rcu_torture_disable_rt_throttle();
2036 	VERBOSE_TOROUT_STRING("Creating rcu_torture_boost task");
2037 	boost_tasks[cpu] = kthread_run_on_cpu(rcu_torture_boost, NULL,
2038 					      cpu, "rcu_torture_boost_%u");
2039 	if (IS_ERR(boost_tasks[cpu])) {
2040 		retval = PTR_ERR(boost_tasks[cpu]);
2041 		VERBOSE_TOROUT_STRING("rcu_torture_boost task create failed");
2042 		n_rcu_torture_boost_ktrerror++;
2043 		boost_tasks[cpu] = NULL;
2044 		mutex_unlock(&boost_mutex);
2045 		return retval;
2046 	}
2047 	mutex_unlock(&boost_mutex);
2048 	return 0;
2049 }
2050 
2051 /*
2052  * CPU-stall kthread.  It waits as specified by stall_cpu_holdoff, then
2053  * induces a CPU stall for the time specified by stall_cpu.
2054  */
2055 static int rcu_torture_stall(void *args)
2056 {
2057 	int idx;
2058 	unsigned long stop_at;
2059 
2060 	VERBOSE_TOROUT_STRING("rcu_torture_stall task started");
2061 	if (stall_cpu_holdoff > 0) {
2062 		VERBOSE_TOROUT_STRING("rcu_torture_stall begin holdoff");
2063 		schedule_timeout_interruptible(stall_cpu_holdoff * HZ);
2064 		VERBOSE_TOROUT_STRING("rcu_torture_stall end holdoff");
2065 	}
2066 	if (!kthread_should_stop() && stall_gp_kthread > 0) {
2067 		VERBOSE_TOROUT_STRING("rcu_torture_stall begin GP stall");
2068 		rcu_gp_set_torture_wait(stall_gp_kthread * HZ);
2069 		for (idx = 0; idx < stall_gp_kthread + 2; idx++) {
2070 			if (kthread_should_stop())
2071 				break;
2072 			schedule_timeout_uninterruptible(HZ);
2073 		}
2074 	}
2075 	if (!kthread_should_stop() && stall_cpu > 0) {
2076 		VERBOSE_TOROUT_STRING("rcu_torture_stall begin CPU stall");
2077 		stop_at = ktime_get_seconds() + stall_cpu;
2078 		/* RCU CPU stall is expected behavior in following code. */
2079 		idx = cur_ops->readlock();
2080 		if (stall_cpu_irqsoff)
2081 			local_irq_disable();
2082 		else if (!stall_cpu_block)
2083 			preempt_disable();
2084 		pr_alert("%s start on CPU %d.\n",
2085 			  __func__, raw_smp_processor_id());
2086 		while (ULONG_CMP_LT((unsigned long)ktime_get_seconds(),
2087 				    stop_at))
2088 			if (stall_cpu_block) {
2089 #ifdef CONFIG_PREEMPTION
2090 				preempt_schedule();
2091 #else
2092 				schedule_timeout_uninterruptible(HZ);
2093 #endif
2094 			} else if (stall_no_softlockup) {
2095 				touch_softlockup_watchdog();
2096 			}
2097 		if (stall_cpu_irqsoff)
2098 			local_irq_enable();
2099 		else if (!stall_cpu_block)
2100 			preempt_enable();
2101 		cur_ops->readunlock(idx);
2102 	}
2103 	pr_alert("%s end.\n", __func__);
2104 	torture_shutdown_absorb("rcu_torture_stall");
2105 	while (!kthread_should_stop())
2106 		schedule_timeout_interruptible(10 * HZ);
2107 	return 0;
2108 }
2109 
2110 /* Spawn CPU-stall kthread, if stall_cpu specified. */
2111 static int __init rcu_torture_stall_init(void)
2112 {
2113 	if (stall_cpu <= 0 && stall_gp_kthread <= 0)
2114 		return 0;
2115 	return torture_create_kthread(rcu_torture_stall, NULL, stall_task);
2116 }
2117 
2118 /* State structure for forward-progress self-propagating RCU callback. */
2119 struct fwd_cb_state {
2120 	struct rcu_head rh;
2121 	int stop;
2122 };
2123 
2124 /*
2125  * Forward-progress self-propagating RCU callback function.  Because
2126  * callbacks run from softirq, this function is an implicit RCU read-side
2127  * critical section.
2128  */
2129 static void rcu_torture_fwd_prog_cb(struct rcu_head *rhp)
2130 {
2131 	struct fwd_cb_state *fcsp = container_of(rhp, struct fwd_cb_state, rh);
2132 
2133 	if (READ_ONCE(fcsp->stop)) {
2134 		WRITE_ONCE(fcsp->stop, 2);
2135 		return;
2136 	}
2137 	cur_ops->call(&fcsp->rh, rcu_torture_fwd_prog_cb);
2138 }
2139 
2140 /* State for continuous-flood RCU callbacks. */
2141 struct rcu_fwd_cb {
2142 	struct rcu_head rh;
2143 	struct rcu_fwd_cb *rfc_next;
2144 	struct rcu_fwd *rfc_rfp;
2145 	int rfc_gps;
2146 };
2147 
2148 #define MAX_FWD_CB_JIFFIES	(8 * HZ) /* Maximum CB test duration. */
2149 #define MIN_FWD_CB_LAUNDERS	3	/* This many CB invocations to count. */
2150 #define MIN_FWD_CBS_LAUNDERED	100	/* Number of counted CBs. */
2151 #define FWD_CBS_HIST_DIV	10	/* Histogram buckets/second. */
2152 #define N_LAUNDERS_HIST (2 * MAX_FWD_CB_JIFFIES / (HZ / FWD_CBS_HIST_DIV))
2153 
2154 struct rcu_launder_hist {
2155 	long n_launders;
2156 	unsigned long launder_gp_seq;
2157 };
2158 
2159 struct rcu_fwd {
2160 	spinlock_t rcu_fwd_lock;
2161 	struct rcu_fwd_cb *rcu_fwd_cb_head;
2162 	struct rcu_fwd_cb **rcu_fwd_cb_tail;
2163 	long n_launders_cb;
2164 	unsigned long rcu_fwd_startat;
2165 	struct rcu_launder_hist n_launders_hist[N_LAUNDERS_HIST];
2166 	unsigned long rcu_launder_gp_seq_start;
2167 	int rcu_fwd_id;
2168 };
2169 
2170 static DEFINE_MUTEX(rcu_fwd_mutex);
2171 static struct rcu_fwd *rcu_fwds;
2172 static unsigned long rcu_fwd_seq;
2173 static atomic_long_t rcu_fwd_max_cbs;
2174 static bool rcu_fwd_emergency_stop;
2175 
2176 static void rcu_torture_fwd_cb_hist(struct rcu_fwd *rfp)
2177 {
2178 	unsigned long gps;
2179 	unsigned long gps_old;
2180 	int i;
2181 	int j;
2182 
2183 	for (i = ARRAY_SIZE(rfp->n_launders_hist) - 1; i > 0; i--)
2184 		if (rfp->n_launders_hist[i].n_launders > 0)
2185 			break;
2186 	pr_alert("%s: Callback-invocation histogram %d (duration %lu jiffies):",
2187 		 __func__, rfp->rcu_fwd_id, jiffies - rfp->rcu_fwd_startat);
2188 	gps_old = rfp->rcu_launder_gp_seq_start;
2189 	for (j = 0; j <= i; j++) {
2190 		gps = rfp->n_launders_hist[j].launder_gp_seq;
2191 		pr_cont(" %ds/%d: %ld:%ld",
2192 			j + 1, FWD_CBS_HIST_DIV,
2193 			rfp->n_launders_hist[j].n_launders,
2194 			rcutorture_seq_diff(gps, gps_old));
2195 		gps_old = gps;
2196 	}
2197 	pr_cont("\n");
2198 }
2199 
2200 /* Callback function for continuous-flood RCU callbacks. */
2201 static void rcu_torture_fwd_cb_cr(struct rcu_head *rhp)
2202 {
2203 	unsigned long flags;
2204 	int i;
2205 	struct rcu_fwd_cb *rfcp = container_of(rhp, struct rcu_fwd_cb, rh);
2206 	struct rcu_fwd_cb **rfcpp;
2207 	struct rcu_fwd *rfp = rfcp->rfc_rfp;
2208 
2209 	rfcp->rfc_next = NULL;
2210 	rfcp->rfc_gps++;
2211 	spin_lock_irqsave(&rfp->rcu_fwd_lock, flags);
2212 	rfcpp = rfp->rcu_fwd_cb_tail;
2213 	rfp->rcu_fwd_cb_tail = &rfcp->rfc_next;
2214 	WRITE_ONCE(*rfcpp, rfcp);
2215 	WRITE_ONCE(rfp->n_launders_cb, rfp->n_launders_cb + 1);
2216 	i = ((jiffies - rfp->rcu_fwd_startat) / (HZ / FWD_CBS_HIST_DIV));
2217 	if (i >= ARRAY_SIZE(rfp->n_launders_hist))
2218 		i = ARRAY_SIZE(rfp->n_launders_hist) - 1;
2219 	rfp->n_launders_hist[i].n_launders++;
2220 	rfp->n_launders_hist[i].launder_gp_seq = cur_ops->get_gp_seq();
2221 	spin_unlock_irqrestore(&rfp->rcu_fwd_lock, flags);
2222 }
2223 
2224 // Give the scheduler a chance, even on nohz_full CPUs.
2225 static void rcu_torture_fwd_prog_cond_resched(unsigned long iter)
2226 {
2227 	if (IS_ENABLED(CONFIG_PREEMPTION) && IS_ENABLED(CONFIG_NO_HZ_FULL)) {
2228 		// Real call_rcu() floods hit userspace, so emulate that.
2229 		if (need_resched() || (iter & 0xfff))
2230 			schedule();
2231 		return;
2232 	}
2233 	// No userspace emulation: CB invocation throttles call_rcu()
2234 	cond_resched();
2235 }
2236 
2237 /*
2238  * Free all callbacks on the rcu_fwd_cb_head list, either because the
2239  * test is over or because we hit an OOM event.
2240  */
2241 static unsigned long rcu_torture_fwd_prog_cbfree(struct rcu_fwd *rfp)
2242 {
2243 	unsigned long flags;
2244 	unsigned long freed = 0;
2245 	struct rcu_fwd_cb *rfcp;
2246 
2247 	for (;;) {
2248 		spin_lock_irqsave(&rfp->rcu_fwd_lock, flags);
2249 		rfcp = rfp->rcu_fwd_cb_head;
2250 		if (!rfcp) {
2251 			spin_unlock_irqrestore(&rfp->rcu_fwd_lock, flags);
2252 			break;
2253 		}
2254 		rfp->rcu_fwd_cb_head = rfcp->rfc_next;
2255 		if (!rfp->rcu_fwd_cb_head)
2256 			rfp->rcu_fwd_cb_tail = &rfp->rcu_fwd_cb_head;
2257 		spin_unlock_irqrestore(&rfp->rcu_fwd_lock, flags);
2258 		kfree(rfcp);
2259 		freed++;
2260 		rcu_torture_fwd_prog_cond_resched(freed);
2261 		if (tick_nohz_full_enabled()) {
2262 			local_irq_save(flags);
2263 			rcu_momentary_dyntick_idle();
2264 			local_irq_restore(flags);
2265 		}
2266 	}
2267 	return freed;
2268 }
2269 
2270 /* Carry out need_resched()/cond_resched() forward-progress testing. */
2271 static void rcu_torture_fwd_prog_nr(struct rcu_fwd *rfp,
2272 				    int *tested, int *tested_tries)
2273 {
2274 	unsigned long cver;
2275 	unsigned long dur;
2276 	struct fwd_cb_state fcs;
2277 	unsigned long gps;
2278 	int idx;
2279 	int sd;
2280 	int sd4;
2281 	bool selfpropcb = false;
2282 	unsigned long stopat;
2283 	static DEFINE_TORTURE_RANDOM(trs);
2284 
2285 	pr_alert("%s: Starting forward-progress test %d\n", __func__, rfp->rcu_fwd_id);
2286 	if (!cur_ops->sync)
2287 		return; // Cannot do need_resched() forward progress testing without ->sync.
2288 	if (cur_ops->call && cur_ops->cb_barrier) {
2289 		init_rcu_head_on_stack(&fcs.rh);
2290 		selfpropcb = true;
2291 	}
2292 
2293 	/* Tight loop containing cond_resched(). */
2294 	atomic_inc(&rcu_fwd_cb_nodelay);
2295 	cur_ops->sync(); /* Later readers see above write. */
2296 	if  (selfpropcb) {
2297 		WRITE_ONCE(fcs.stop, 0);
2298 		cur_ops->call(&fcs.rh, rcu_torture_fwd_prog_cb);
2299 	}
2300 	cver = READ_ONCE(rcu_torture_current_version);
2301 	gps = cur_ops->get_gp_seq();
2302 	sd = cur_ops->stall_dur() + 1;
2303 	sd4 = (sd + fwd_progress_div - 1) / fwd_progress_div;
2304 	dur = sd4 + torture_random(&trs) % (sd - sd4);
2305 	WRITE_ONCE(rfp->rcu_fwd_startat, jiffies);
2306 	stopat = rfp->rcu_fwd_startat + dur;
2307 	while (time_before(jiffies, stopat) &&
2308 	       !shutdown_time_arrived() &&
2309 	       !READ_ONCE(rcu_fwd_emergency_stop) && !torture_must_stop()) {
2310 		idx = cur_ops->readlock();
2311 		udelay(10);
2312 		cur_ops->readunlock(idx);
2313 		if (!fwd_progress_need_resched || need_resched())
2314 			cond_resched();
2315 	}
2316 	(*tested_tries)++;
2317 	if (!time_before(jiffies, stopat) &&
2318 	    !shutdown_time_arrived() &&
2319 	    !READ_ONCE(rcu_fwd_emergency_stop) && !torture_must_stop()) {
2320 		(*tested)++;
2321 		cver = READ_ONCE(rcu_torture_current_version) - cver;
2322 		gps = rcutorture_seq_diff(cur_ops->get_gp_seq(), gps);
2323 		WARN_ON(!cver && gps < 2);
2324 		pr_alert("%s: %d Duration %ld cver %ld gps %ld\n", __func__,
2325 			 rfp->rcu_fwd_id, dur, cver, gps);
2326 	}
2327 	if (selfpropcb) {
2328 		WRITE_ONCE(fcs.stop, 1);
2329 		cur_ops->sync(); /* Wait for running CB to complete. */
2330 		pr_alert("%s: Waiting for CBs: %pS() %d\n", __func__, cur_ops->cb_barrier, rfp->rcu_fwd_id);
2331 		cur_ops->cb_barrier(); /* Wait for queued callbacks. */
2332 	}
2333 
2334 	if (selfpropcb) {
2335 		WARN_ON(READ_ONCE(fcs.stop) != 2);
2336 		destroy_rcu_head_on_stack(&fcs.rh);
2337 	}
2338 	schedule_timeout_uninterruptible(HZ / 10); /* Let kthreads recover. */
2339 	atomic_dec(&rcu_fwd_cb_nodelay);
2340 }
2341 
2342 /* Carry out call_rcu() forward-progress testing. */
2343 static void rcu_torture_fwd_prog_cr(struct rcu_fwd *rfp)
2344 {
2345 	unsigned long cver;
2346 	unsigned long flags;
2347 	unsigned long gps;
2348 	int i;
2349 	long n_launders;
2350 	long n_launders_cb_snap;
2351 	long n_launders_sa;
2352 	long n_max_cbs;
2353 	long n_max_gps;
2354 	struct rcu_fwd_cb *rfcp;
2355 	struct rcu_fwd_cb *rfcpn;
2356 	unsigned long stopat;
2357 	unsigned long stoppedat;
2358 
2359 	pr_alert("%s: Starting forward-progress test %d\n", __func__, rfp->rcu_fwd_id);
2360 	if (READ_ONCE(rcu_fwd_emergency_stop))
2361 		return; /* Get out of the way quickly, no GP wait! */
2362 	if (!cur_ops->call)
2363 		return; /* Can't do call_rcu() fwd prog without ->call. */
2364 
2365 	/* Loop continuously posting RCU callbacks. */
2366 	atomic_inc(&rcu_fwd_cb_nodelay);
2367 	cur_ops->sync(); /* Later readers see above write. */
2368 	WRITE_ONCE(rfp->rcu_fwd_startat, jiffies);
2369 	stopat = rfp->rcu_fwd_startat + MAX_FWD_CB_JIFFIES;
2370 	n_launders = 0;
2371 	rfp->n_launders_cb = 0; // Hoist initialization for multi-kthread
2372 	n_launders_sa = 0;
2373 	n_max_cbs = 0;
2374 	n_max_gps = 0;
2375 	for (i = 0; i < ARRAY_SIZE(rfp->n_launders_hist); i++)
2376 		rfp->n_launders_hist[i].n_launders = 0;
2377 	cver = READ_ONCE(rcu_torture_current_version);
2378 	gps = cur_ops->get_gp_seq();
2379 	rfp->rcu_launder_gp_seq_start = gps;
2380 	tick_dep_set_task(current, TICK_DEP_BIT_RCU);
2381 	while (time_before(jiffies, stopat) &&
2382 	       !shutdown_time_arrived() &&
2383 	       !READ_ONCE(rcu_fwd_emergency_stop) && !torture_must_stop()) {
2384 		rfcp = READ_ONCE(rfp->rcu_fwd_cb_head);
2385 		rfcpn = NULL;
2386 		if (rfcp)
2387 			rfcpn = READ_ONCE(rfcp->rfc_next);
2388 		if (rfcpn) {
2389 			if (rfcp->rfc_gps >= MIN_FWD_CB_LAUNDERS &&
2390 			    ++n_max_gps >= MIN_FWD_CBS_LAUNDERED)
2391 				break;
2392 			rfp->rcu_fwd_cb_head = rfcpn;
2393 			n_launders++;
2394 			n_launders_sa++;
2395 		} else if (!cur_ops->cbflood_max || cur_ops->cbflood_max > n_max_cbs) {
2396 			rfcp = kmalloc(sizeof(*rfcp), GFP_KERNEL);
2397 			if (WARN_ON_ONCE(!rfcp)) {
2398 				schedule_timeout_interruptible(1);
2399 				continue;
2400 			}
2401 			n_max_cbs++;
2402 			n_launders_sa = 0;
2403 			rfcp->rfc_gps = 0;
2404 			rfcp->rfc_rfp = rfp;
2405 		} else {
2406 			rfcp = NULL;
2407 		}
2408 		if (rfcp)
2409 			cur_ops->call(&rfcp->rh, rcu_torture_fwd_cb_cr);
2410 		rcu_torture_fwd_prog_cond_resched(n_launders + n_max_cbs);
2411 		if (tick_nohz_full_enabled()) {
2412 			local_irq_save(flags);
2413 			rcu_momentary_dyntick_idle();
2414 			local_irq_restore(flags);
2415 		}
2416 	}
2417 	stoppedat = jiffies;
2418 	n_launders_cb_snap = READ_ONCE(rfp->n_launders_cb);
2419 	cver = READ_ONCE(rcu_torture_current_version) - cver;
2420 	gps = rcutorture_seq_diff(cur_ops->get_gp_seq(), gps);
2421 	pr_alert("%s: Waiting for CBs: %pS() %d\n", __func__, cur_ops->cb_barrier, rfp->rcu_fwd_id);
2422 	cur_ops->cb_barrier(); /* Wait for callbacks to be invoked. */
2423 	(void)rcu_torture_fwd_prog_cbfree(rfp);
2424 
2425 	if (!torture_must_stop() && !READ_ONCE(rcu_fwd_emergency_stop) &&
2426 	    !shutdown_time_arrived()) {
2427 		WARN_ON(n_max_gps < MIN_FWD_CBS_LAUNDERED);
2428 		pr_alert("%s Duration %lu barrier: %lu pending %ld n_launders: %ld n_launders_sa: %ld n_max_gps: %ld n_max_cbs: %ld cver %ld gps %ld\n",
2429 			 __func__,
2430 			 stoppedat - rfp->rcu_fwd_startat, jiffies - stoppedat,
2431 			 n_launders + n_max_cbs - n_launders_cb_snap,
2432 			 n_launders, n_launders_sa,
2433 			 n_max_gps, n_max_cbs, cver, gps);
2434 		atomic_long_add(n_max_cbs, &rcu_fwd_max_cbs);
2435 		mutex_lock(&rcu_fwd_mutex); // Serialize histograms.
2436 		rcu_torture_fwd_cb_hist(rfp);
2437 		mutex_unlock(&rcu_fwd_mutex);
2438 	}
2439 	schedule_timeout_uninterruptible(HZ); /* Let CBs drain. */
2440 	tick_dep_clear_task(current, TICK_DEP_BIT_RCU);
2441 	atomic_dec(&rcu_fwd_cb_nodelay);
2442 }
2443 
2444 
2445 /*
2446  * OOM notifier, but this only prints diagnostic information for the
2447  * current forward-progress test.
2448  */
2449 static int rcutorture_oom_notify(struct notifier_block *self,
2450 				 unsigned long notused, void *nfreed)
2451 {
2452 	int i;
2453 	long ncbs;
2454 	struct rcu_fwd *rfp;
2455 
2456 	mutex_lock(&rcu_fwd_mutex);
2457 	rfp = rcu_fwds;
2458 	if (!rfp) {
2459 		mutex_unlock(&rcu_fwd_mutex);
2460 		return NOTIFY_OK;
2461 	}
2462 	WARN(1, "%s invoked upon OOM during forward-progress testing.\n",
2463 	     __func__);
2464 	for (i = 0; i < fwd_progress; i++) {
2465 		rcu_torture_fwd_cb_hist(&rfp[i]);
2466 		rcu_fwd_progress_check(1 + (jiffies - READ_ONCE(rfp[i].rcu_fwd_startat)) / 2);
2467 	}
2468 	WRITE_ONCE(rcu_fwd_emergency_stop, true);
2469 	smp_mb(); /* Emergency stop before free and wait to avoid hangs. */
2470 	ncbs = 0;
2471 	for (i = 0; i < fwd_progress; i++)
2472 		ncbs += rcu_torture_fwd_prog_cbfree(&rfp[i]);
2473 	pr_info("%s: Freed %lu RCU callbacks.\n", __func__, ncbs);
2474 	rcu_barrier();
2475 	ncbs = 0;
2476 	for (i = 0; i < fwd_progress; i++)
2477 		ncbs += rcu_torture_fwd_prog_cbfree(&rfp[i]);
2478 	pr_info("%s: Freed %lu RCU callbacks.\n", __func__, ncbs);
2479 	rcu_barrier();
2480 	ncbs = 0;
2481 	for (i = 0; i < fwd_progress; i++)
2482 		ncbs += rcu_torture_fwd_prog_cbfree(&rfp[i]);
2483 	pr_info("%s: Freed %lu RCU callbacks.\n", __func__, ncbs);
2484 	smp_mb(); /* Frees before return to avoid redoing OOM. */
2485 	(*(unsigned long *)nfreed)++; /* Forward progress CBs freed! */
2486 	pr_info("%s returning after OOM processing.\n", __func__);
2487 	mutex_unlock(&rcu_fwd_mutex);
2488 	return NOTIFY_OK;
2489 }
2490 
2491 static struct notifier_block rcutorture_oom_nb = {
2492 	.notifier_call = rcutorture_oom_notify
2493 };
2494 
2495 /* Carry out grace-period forward-progress testing. */
2496 static int rcu_torture_fwd_prog(void *args)
2497 {
2498 	bool firsttime = true;
2499 	long max_cbs;
2500 	int oldnice = task_nice(current);
2501 	unsigned long oldseq = READ_ONCE(rcu_fwd_seq);
2502 	struct rcu_fwd *rfp = args;
2503 	int tested = 0;
2504 	int tested_tries = 0;
2505 
2506 	VERBOSE_TOROUT_STRING("rcu_torture_fwd_progress task started");
2507 	rcu_bind_current_to_nocb();
2508 	if (!IS_ENABLED(CONFIG_SMP) || !IS_ENABLED(CONFIG_RCU_BOOST))
2509 		set_user_nice(current, MAX_NICE);
2510 	do {
2511 		if (!rfp->rcu_fwd_id) {
2512 			schedule_timeout_interruptible(fwd_progress_holdoff * HZ);
2513 			WRITE_ONCE(rcu_fwd_emergency_stop, false);
2514 			if (!firsttime) {
2515 				max_cbs = atomic_long_xchg(&rcu_fwd_max_cbs, 0);
2516 				pr_alert("%s n_max_cbs: %ld\n", __func__, max_cbs);
2517 			}
2518 			firsttime = false;
2519 			WRITE_ONCE(rcu_fwd_seq, rcu_fwd_seq + 1);
2520 		} else {
2521 			while (READ_ONCE(rcu_fwd_seq) == oldseq && !torture_must_stop())
2522 				schedule_timeout_interruptible(1);
2523 			oldseq = READ_ONCE(rcu_fwd_seq);
2524 		}
2525 		pr_alert("%s: Starting forward-progress test %d\n", __func__, rfp->rcu_fwd_id);
2526 		if (rcu_inkernel_boot_has_ended() && torture_num_online_cpus() > rfp->rcu_fwd_id)
2527 			rcu_torture_fwd_prog_cr(rfp);
2528 		if ((cur_ops->stall_dur && cur_ops->stall_dur() > 0) &&
2529 		    (!IS_ENABLED(CONFIG_TINY_RCU) ||
2530 		     (rcu_inkernel_boot_has_ended() &&
2531 		      torture_num_online_cpus() > rfp->rcu_fwd_id)))
2532 			rcu_torture_fwd_prog_nr(rfp, &tested, &tested_tries);
2533 
2534 		/* Avoid slow periods, better to test when busy. */
2535 		if (stutter_wait("rcu_torture_fwd_prog"))
2536 			sched_set_normal(current, oldnice);
2537 	} while (!torture_must_stop());
2538 	/* Short runs might not contain a valid forward-progress attempt. */
2539 	if (!rfp->rcu_fwd_id) {
2540 		WARN_ON(!tested && tested_tries >= 5);
2541 		pr_alert("%s: tested %d tested_tries %d\n", __func__, tested, tested_tries);
2542 	}
2543 	torture_kthread_stopping("rcu_torture_fwd_prog");
2544 	return 0;
2545 }
2546 
2547 /* If forward-progress checking is requested and feasible, spawn the thread. */
2548 static int __init rcu_torture_fwd_prog_init(void)
2549 {
2550 	int i;
2551 	int ret = 0;
2552 	struct rcu_fwd *rfp;
2553 
2554 	if (!fwd_progress)
2555 		return 0; /* Not requested, so don't do it. */
2556 	if (fwd_progress >= nr_cpu_ids) {
2557 		VERBOSE_TOROUT_STRING("rcu_torture_fwd_prog_init: Limiting fwd_progress to # CPUs.\n");
2558 		fwd_progress = nr_cpu_ids;
2559 	} else if (fwd_progress < 0) {
2560 		fwd_progress = nr_cpu_ids;
2561 	}
2562 	if ((!cur_ops->sync && !cur_ops->call) ||
2563 	    (!cur_ops->cbflood_max && (!cur_ops->stall_dur || cur_ops->stall_dur() <= 0)) ||
2564 	    cur_ops == &rcu_busted_ops) {
2565 		VERBOSE_TOROUT_STRING("rcu_torture_fwd_prog_init: Disabled, unsupported by RCU flavor under test");
2566 		fwd_progress = 0;
2567 		return 0;
2568 	}
2569 	if (stall_cpu > 0) {
2570 		VERBOSE_TOROUT_STRING("rcu_torture_fwd_prog_init: Disabled, conflicts with CPU-stall testing");
2571 		fwd_progress = 0;
2572 		if (IS_MODULE(CONFIG_RCU_TORTURE_TEST))
2573 			return -EINVAL; /* In module, can fail back to user. */
2574 		WARN_ON(1); /* Make sure rcutorture notices conflict. */
2575 		return 0;
2576 	}
2577 	if (fwd_progress_holdoff <= 0)
2578 		fwd_progress_holdoff = 1;
2579 	if (fwd_progress_div <= 0)
2580 		fwd_progress_div = 4;
2581 	rfp = kcalloc(fwd_progress, sizeof(*rfp), GFP_KERNEL);
2582 	fwd_prog_tasks = kcalloc(fwd_progress, sizeof(*fwd_prog_tasks), GFP_KERNEL);
2583 	if (!rfp || !fwd_prog_tasks) {
2584 		kfree(rfp);
2585 		kfree(fwd_prog_tasks);
2586 		fwd_prog_tasks = NULL;
2587 		fwd_progress = 0;
2588 		return -ENOMEM;
2589 	}
2590 	for (i = 0; i < fwd_progress; i++) {
2591 		spin_lock_init(&rfp[i].rcu_fwd_lock);
2592 		rfp[i].rcu_fwd_cb_tail = &rfp[i].rcu_fwd_cb_head;
2593 		rfp[i].rcu_fwd_id = i;
2594 	}
2595 	mutex_lock(&rcu_fwd_mutex);
2596 	rcu_fwds = rfp;
2597 	mutex_unlock(&rcu_fwd_mutex);
2598 	register_oom_notifier(&rcutorture_oom_nb);
2599 	for (i = 0; i < fwd_progress; i++) {
2600 		ret = torture_create_kthread(rcu_torture_fwd_prog, &rcu_fwds[i], fwd_prog_tasks[i]);
2601 		if (ret) {
2602 			fwd_progress = i;
2603 			return ret;
2604 		}
2605 	}
2606 	return 0;
2607 }
2608 
2609 static void rcu_torture_fwd_prog_cleanup(void)
2610 {
2611 	int i;
2612 	struct rcu_fwd *rfp;
2613 
2614 	if (!rcu_fwds || !fwd_prog_tasks)
2615 		return;
2616 	for (i = 0; i < fwd_progress; i++)
2617 		torture_stop_kthread(rcu_torture_fwd_prog, fwd_prog_tasks[i]);
2618 	unregister_oom_notifier(&rcutorture_oom_nb);
2619 	mutex_lock(&rcu_fwd_mutex);
2620 	rfp = rcu_fwds;
2621 	rcu_fwds = NULL;
2622 	mutex_unlock(&rcu_fwd_mutex);
2623 	kfree(rfp);
2624 	kfree(fwd_prog_tasks);
2625 	fwd_prog_tasks = NULL;
2626 }
2627 
2628 /* Callback function for RCU barrier testing. */
2629 static void rcu_torture_barrier_cbf(struct rcu_head *rcu)
2630 {
2631 	atomic_inc(&barrier_cbs_invoked);
2632 }
2633 
2634 /* IPI handler to get callback posted on desired CPU, if online. */
2635 static void rcu_torture_barrier1cb(void *rcu_void)
2636 {
2637 	struct rcu_head *rhp = rcu_void;
2638 
2639 	cur_ops->call(rhp, rcu_torture_barrier_cbf);
2640 }
2641 
2642 /* kthread function to register callbacks used to test RCU barriers. */
2643 static int rcu_torture_barrier_cbs(void *arg)
2644 {
2645 	long myid = (long)arg;
2646 	bool lastphase = false;
2647 	bool newphase;
2648 	struct rcu_head rcu;
2649 
2650 	init_rcu_head_on_stack(&rcu);
2651 	VERBOSE_TOROUT_STRING("rcu_torture_barrier_cbs task started");
2652 	set_user_nice(current, MAX_NICE);
2653 	do {
2654 		wait_event(barrier_cbs_wq[myid],
2655 			   (newphase =
2656 			    smp_load_acquire(&barrier_phase)) != lastphase ||
2657 			   torture_must_stop());
2658 		lastphase = newphase;
2659 		if (torture_must_stop())
2660 			break;
2661 		/*
2662 		 * The above smp_load_acquire() ensures barrier_phase load
2663 		 * is ordered before the following ->call().
2664 		 */
2665 		if (smp_call_function_single(myid, rcu_torture_barrier1cb,
2666 					     &rcu, 1)) {
2667 			// IPI failed, so use direct call from current CPU.
2668 			cur_ops->call(&rcu, rcu_torture_barrier_cbf);
2669 		}
2670 		if (atomic_dec_and_test(&barrier_cbs_count))
2671 			wake_up(&barrier_wq);
2672 	} while (!torture_must_stop());
2673 	if (cur_ops->cb_barrier != NULL)
2674 		cur_ops->cb_barrier();
2675 	destroy_rcu_head_on_stack(&rcu);
2676 	torture_kthread_stopping("rcu_torture_barrier_cbs");
2677 	return 0;
2678 }
2679 
2680 /* kthread function to drive and coordinate RCU barrier testing. */
2681 static int rcu_torture_barrier(void *arg)
2682 {
2683 	int i;
2684 
2685 	VERBOSE_TOROUT_STRING("rcu_torture_barrier task starting");
2686 	do {
2687 		atomic_set(&barrier_cbs_invoked, 0);
2688 		atomic_set(&barrier_cbs_count, n_barrier_cbs);
2689 		/* Ensure barrier_phase ordered after prior assignments. */
2690 		smp_store_release(&barrier_phase, !barrier_phase);
2691 		for (i = 0; i < n_barrier_cbs; i++)
2692 			wake_up(&barrier_cbs_wq[i]);
2693 		wait_event(barrier_wq,
2694 			   atomic_read(&barrier_cbs_count) == 0 ||
2695 			   torture_must_stop());
2696 		if (torture_must_stop())
2697 			break;
2698 		n_barrier_attempts++;
2699 		cur_ops->cb_barrier(); /* Implies smp_mb() for wait_event(). */
2700 		if (atomic_read(&barrier_cbs_invoked) != n_barrier_cbs) {
2701 			n_rcu_torture_barrier_error++;
2702 			pr_err("barrier_cbs_invoked = %d, n_barrier_cbs = %d\n",
2703 			       atomic_read(&barrier_cbs_invoked),
2704 			       n_barrier_cbs);
2705 			WARN_ON(1);
2706 			// Wait manually for the remaining callbacks
2707 			i = 0;
2708 			do {
2709 				if (WARN_ON(i++ > HZ))
2710 					i = INT_MIN;
2711 				schedule_timeout_interruptible(1);
2712 				cur_ops->cb_barrier();
2713 			} while (atomic_read(&barrier_cbs_invoked) !=
2714 				 n_barrier_cbs &&
2715 				 !torture_must_stop());
2716 			smp_mb(); // Can't trust ordering if broken.
2717 			if (!torture_must_stop())
2718 				pr_err("Recovered: barrier_cbs_invoked = %d\n",
2719 				       atomic_read(&barrier_cbs_invoked));
2720 		} else {
2721 			n_barrier_successes++;
2722 		}
2723 		schedule_timeout_interruptible(HZ / 10);
2724 	} while (!torture_must_stop());
2725 	torture_kthread_stopping("rcu_torture_barrier");
2726 	return 0;
2727 }
2728 
2729 /* Initialize RCU barrier testing. */
2730 static int rcu_torture_barrier_init(void)
2731 {
2732 	int i;
2733 	int ret;
2734 
2735 	if (n_barrier_cbs <= 0)
2736 		return 0;
2737 	if (cur_ops->call == NULL || cur_ops->cb_barrier == NULL) {
2738 		pr_alert("%s" TORTURE_FLAG
2739 			 " Call or barrier ops missing for %s,\n",
2740 			 torture_type, cur_ops->name);
2741 		pr_alert("%s" TORTURE_FLAG
2742 			 " RCU barrier testing omitted from run.\n",
2743 			 torture_type);
2744 		return 0;
2745 	}
2746 	atomic_set(&barrier_cbs_count, 0);
2747 	atomic_set(&barrier_cbs_invoked, 0);
2748 	barrier_cbs_tasks =
2749 		kcalloc(n_barrier_cbs, sizeof(barrier_cbs_tasks[0]),
2750 			GFP_KERNEL);
2751 	barrier_cbs_wq =
2752 		kcalloc(n_barrier_cbs, sizeof(barrier_cbs_wq[0]), GFP_KERNEL);
2753 	if (barrier_cbs_tasks == NULL || !barrier_cbs_wq)
2754 		return -ENOMEM;
2755 	for (i = 0; i < n_barrier_cbs; i++) {
2756 		init_waitqueue_head(&barrier_cbs_wq[i]);
2757 		ret = torture_create_kthread(rcu_torture_barrier_cbs,
2758 					     (void *)(long)i,
2759 					     barrier_cbs_tasks[i]);
2760 		if (ret)
2761 			return ret;
2762 	}
2763 	return torture_create_kthread(rcu_torture_barrier, NULL, barrier_task);
2764 }
2765 
2766 /* Clean up after RCU barrier testing. */
2767 static void rcu_torture_barrier_cleanup(void)
2768 {
2769 	int i;
2770 
2771 	torture_stop_kthread(rcu_torture_barrier, barrier_task);
2772 	if (barrier_cbs_tasks != NULL) {
2773 		for (i = 0; i < n_barrier_cbs; i++)
2774 			torture_stop_kthread(rcu_torture_barrier_cbs,
2775 					     barrier_cbs_tasks[i]);
2776 		kfree(barrier_cbs_tasks);
2777 		barrier_cbs_tasks = NULL;
2778 	}
2779 	if (barrier_cbs_wq != NULL) {
2780 		kfree(barrier_cbs_wq);
2781 		barrier_cbs_wq = NULL;
2782 	}
2783 }
2784 
2785 static bool rcu_torture_can_boost(void)
2786 {
2787 	static int boost_warn_once;
2788 	int prio;
2789 
2790 	if (!(test_boost == 1 && cur_ops->can_boost) && test_boost != 2)
2791 		return false;
2792 	if (!cur_ops->start_gp_poll || !cur_ops->poll_gp_state)
2793 		return false;
2794 
2795 	prio = rcu_get_gp_kthreads_prio();
2796 	if (!prio)
2797 		return false;
2798 
2799 	if (prio < 2) {
2800 		if (boost_warn_once == 1)
2801 			return false;
2802 
2803 		pr_alert("%s: WARN: RCU kthread priority too low to test boosting.  Skipping RCU boost test. Try passing rcutree.kthread_prio > 1 on the kernel command line.\n", KBUILD_MODNAME);
2804 		boost_warn_once = 1;
2805 		return false;
2806 	}
2807 
2808 	return true;
2809 }
2810 
2811 static bool read_exit_child_stop;
2812 static bool read_exit_child_stopped;
2813 static wait_queue_head_t read_exit_wq;
2814 
2815 // Child kthread which just does an rcutorture reader and exits.
2816 static int rcu_torture_read_exit_child(void *trsp_in)
2817 {
2818 	struct torture_random_state *trsp = trsp_in;
2819 
2820 	set_user_nice(current, MAX_NICE);
2821 	// Minimize time between reading and exiting.
2822 	while (!kthread_should_stop())
2823 		schedule_timeout_uninterruptible(1);
2824 	(void)rcu_torture_one_read(trsp, -1);
2825 	return 0;
2826 }
2827 
2828 // Parent kthread which creates and destroys read-exit child kthreads.
2829 static int rcu_torture_read_exit(void *unused)
2830 {
2831 	int count = 0;
2832 	bool errexit = false;
2833 	int i;
2834 	struct task_struct *tsp;
2835 	DEFINE_TORTURE_RANDOM(trs);
2836 
2837 	// Allocate and initialize.
2838 	set_user_nice(current, MAX_NICE);
2839 	VERBOSE_TOROUT_STRING("rcu_torture_read_exit: Start of test");
2840 
2841 	// Each pass through this loop does one read-exit episode.
2842 	do {
2843 		if (++count > read_exit_burst) {
2844 			VERBOSE_TOROUT_STRING("rcu_torture_read_exit: End of episode");
2845 			rcu_barrier(); // Wait for task_struct free, avoid OOM.
2846 			for (i = 0; i < read_exit_delay; i++) {
2847 				schedule_timeout_uninterruptible(HZ);
2848 				if (READ_ONCE(read_exit_child_stop))
2849 					break;
2850 			}
2851 			if (!READ_ONCE(read_exit_child_stop))
2852 				VERBOSE_TOROUT_STRING("rcu_torture_read_exit: Start of episode");
2853 			count = 0;
2854 		}
2855 		if (READ_ONCE(read_exit_child_stop))
2856 			break;
2857 		// Spawn child.
2858 		tsp = kthread_run(rcu_torture_read_exit_child,
2859 				     &trs, "%s",
2860 				     "rcu_torture_read_exit_child");
2861 		if (IS_ERR(tsp)) {
2862 			TOROUT_ERRSTRING("out of memory");
2863 			errexit = true;
2864 			tsp = NULL;
2865 			break;
2866 		}
2867 		cond_resched();
2868 		kthread_stop(tsp);
2869 		n_read_exits ++;
2870 		stutter_wait("rcu_torture_read_exit");
2871 	} while (!errexit && !READ_ONCE(read_exit_child_stop));
2872 
2873 	// Clean up and exit.
2874 	smp_store_release(&read_exit_child_stopped, true); // After reaping.
2875 	smp_mb(); // Store before wakeup.
2876 	wake_up(&read_exit_wq);
2877 	while (!torture_must_stop())
2878 		schedule_timeout_uninterruptible(1);
2879 	torture_kthread_stopping("rcu_torture_read_exit");
2880 	return 0;
2881 }
2882 
2883 static int rcu_torture_read_exit_init(void)
2884 {
2885 	if (read_exit_burst <= 0)
2886 		return 0;
2887 	init_waitqueue_head(&read_exit_wq);
2888 	read_exit_child_stop = false;
2889 	read_exit_child_stopped = false;
2890 	return torture_create_kthread(rcu_torture_read_exit, NULL,
2891 				      read_exit_task);
2892 }
2893 
2894 static void rcu_torture_read_exit_cleanup(void)
2895 {
2896 	if (!read_exit_task)
2897 		return;
2898 	WRITE_ONCE(read_exit_child_stop, true);
2899 	smp_mb(); // Above write before wait.
2900 	wait_event(read_exit_wq, smp_load_acquire(&read_exit_child_stopped));
2901 	torture_stop_kthread(rcutorture_read_exit, read_exit_task);
2902 }
2903 
2904 static enum cpuhp_state rcutor_hp;
2905 
2906 static void
2907 rcu_torture_cleanup(void)
2908 {
2909 	int firsttime;
2910 	int flags = 0;
2911 	unsigned long gp_seq = 0;
2912 	int i;
2913 
2914 	if (torture_cleanup_begin()) {
2915 		if (cur_ops->cb_barrier != NULL) {
2916 			pr_info("%s: Invoking %pS().\n", __func__, cur_ops->cb_barrier);
2917 			cur_ops->cb_barrier();
2918 		}
2919 		return;
2920 	}
2921 	if (!cur_ops) {
2922 		torture_cleanup_end();
2923 		return;
2924 	}
2925 
2926 	if (cur_ops->gp_kthread_dbg)
2927 		cur_ops->gp_kthread_dbg();
2928 	rcu_torture_read_exit_cleanup();
2929 	rcu_torture_barrier_cleanup();
2930 	rcu_torture_fwd_prog_cleanup();
2931 	torture_stop_kthread(rcu_torture_stall, stall_task);
2932 	torture_stop_kthread(rcu_torture_writer, writer_task);
2933 
2934 	if (nocb_tasks) {
2935 		for (i = 0; i < nrealnocbers; i++)
2936 			torture_stop_kthread(rcu_nocb_toggle, nocb_tasks[i]);
2937 		kfree(nocb_tasks);
2938 		nocb_tasks = NULL;
2939 	}
2940 
2941 	if (reader_tasks) {
2942 		for (i = 0; i < nrealreaders; i++)
2943 			torture_stop_kthread(rcu_torture_reader,
2944 					     reader_tasks[i]);
2945 		kfree(reader_tasks);
2946 		reader_tasks = NULL;
2947 	}
2948 	kfree(rcu_torture_reader_mbchk);
2949 	rcu_torture_reader_mbchk = NULL;
2950 
2951 	if (fakewriter_tasks) {
2952 		for (i = 0; i < nfakewriters; i++)
2953 			torture_stop_kthread(rcu_torture_fakewriter,
2954 					     fakewriter_tasks[i]);
2955 		kfree(fakewriter_tasks);
2956 		fakewriter_tasks = NULL;
2957 	}
2958 
2959 	rcutorture_get_gp_data(cur_ops->ttype, &flags, &gp_seq);
2960 	srcutorture_get_gp_data(cur_ops->ttype, srcu_ctlp, &flags, &gp_seq);
2961 	pr_alert("%s:  End-test grace-period state: g%ld f%#x total-gps=%ld\n",
2962 		 cur_ops->name, (long)gp_seq, flags,
2963 		 rcutorture_seq_diff(gp_seq, start_gp_seq));
2964 	torture_stop_kthread(rcu_torture_stats, stats_task);
2965 	torture_stop_kthread(rcu_torture_fqs, fqs_task);
2966 	if (rcu_torture_can_boost() && rcutor_hp >= 0)
2967 		cpuhp_remove_state(rcutor_hp);
2968 
2969 	/*
2970 	 * Wait for all RCU callbacks to fire, then do torture-type-specific
2971 	 * cleanup operations.
2972 	 */
2973 	if (cur_ops->cb_barrier != NULL) {
2974 		pr_info("%s: Invoking %pS().\n", __func__, cur_ops->cb_barrier);
2975 		cur_ops->cb_barrier();
2976 	}
2977 	if (cur_ops->cleanup != NULL)
2978 		cur_ops->cleanup();
2979 
2980 	rcu_torture_mem_dump_obj();
2981 
2982 	rcu_torture_stats_print();  /* -After- the stats thread is stopped! */
2983 
2984 	if (err_segs_recorded) {
2985 		pr_alert("Failure/close-call rcutorture reader segments:\n");
2986 		if (rt_read_nsegs == 0)
2987 			pr_alert("\t: No segments recorded!!!\n");
2988 		firsttime = 1;
2989 		for (i = 0; i < rt_read_nsegs; i++) {
2990 			pr_alert("\t%d: %#x ", i, err_segs[i].rt_readstate);
2991 			if (err_segs[i].rt_delay_jiffies != 0) {
2992 				pr_cont("%s%ldjiffies", firsttime ? "" : "+",
2993 					err_segs[i].rt_delay_jiffies);
2994 				firsttime = 0;
2995 			}
2996 			if (err_segs[i].rt_delay_ms != 0) {
2997 				pr_cont("%s%ldms", firsttime ? "" : "+",
2998 					err_segs[i].rt_delay_ms);
2999 				firsttime = 0;
3000 			}
3001 			if (err_segs[i].rt_delay_us != 0) {
3002 				pr_cont("%s%ldus", firsttime ? "" : "+",
3003 					err_segs[i].rt_delay_us);
3004 				firsttime = 0;
3005 			}
3006 			pr_cont("%s\n",
3007 				err_segs[i].rt_preempted ? "preempted" : "");
3008 
3009 		}
3010 	}
3011 	if (atomic_read(&n_rcu_torture_error) || n_rcu_torture_barrier_error)
3012 		rcu_torture_print_module_parms(cur_ops, "End of test: FAILURE");
3013 	else if (torture_onoff_failures())
3014 		rcu_torture_print_module_parms(cur_ops,
3015 					       "End of test: RCU_HOTPLUG");
3016 	else
3017 		rcu_torture_print_module_parms(cur_ops, "End of test: SUCCESS");
3018 	torture_cleanup_end();
3019 }
3020 
3021 #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD
3022 static void rcu_torture_leak_cb(struct rcu_head *rhp)
3023 {
3024 }
3025 
3026 static void rcu_torture_err_cb(struct rcu_head *rhp)
3027 {
3028 	/*
3029 	 * This -might- happen due to race conditions, but is unlikely.
3030 	 * The scenario that leads to this happening is that the
3031 	 * first of the pair of duplicate callbacks is queued,
3032 	 * someone else starts a grace period that includes that
3033 	 * callback, then the second of the pair must wait for the
3034 	 * next grace period.  Unlikely, but can happen.  If it
3035 	 * does happen, the debug-objects subsystem won't have splatted.
3036 	 */
3037 	pr_alert("%s: duplicated callback was invoked.\n", KBUILD_MODNAME);
3038 }
3039 #endif /* #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD */
3040 
3041 /*
3042  * Verify that double-free causes debug-objects to complain, but only
3043  * if CONFIG_DEBUG_OBJECTS_RCU_HEAD=y.  Otherwise, say that the test
3044  * cannot be carried out.
3045  */
3046 static void rcu_test_debug_objects(void)
3047 {
3048 #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD
3049 	struct rcu_head rh1;
3050 	struct rcu_head rh2;
3051 	struct rcu_head *rhp = kmalloc(sizeof(*rhp), GFP_KERNEL);
3052 
3053 	init_rcu_head_on_stack(&rh1);
3054 	init_rcu_head_on_stack(&rh2);
3055 	pr_alert("%s: WARN: Duplicate call_rcu() test starting.\n", KBUILD_MODNAME);
3056 
3057 	/* Try to queue the rh2 pair of callbacks for the same grace period. */
3058 	preempt_disable(); /* Prevent preemption from interrupting test. */
3059 	rcu_read_lock(); /* Make it impossible to finish a grace period. */
3060 	call_rcu(&rh1, rcu_torture_leak_cb); /* Start grace period. */
3061 	local_irq_disable(); /* Make it harder to start a new grace period. */
3062 	call_rcu(&rh2, rcu_torture_leak_cb);
3063 	call_rcu(&rh2, rcu_torture_err_cb); /* Duplicate callback. */
3064 	if (rhp) {
3065 		call_rcu(rhp, rcu_torture_leak_cb);
3066 		call_rcu(rhp, rcu_torture_err_cb); /* Another duplicate callback. */
3067 	}
3068 	local_irq_enable();
3069 	rcu_read_unlock();
3070 	preempt_enable();
3071 
3072 	/* Wait for them all to get done so we can safely return. */
3073 	rcu_barrier();
3074 	pr_alert("%s: WARN: Duplicate call_rcu() test complete.\n", KBUILD_MODNAME);
3075 	destroy_rcu_head_on_stack(&rh1);
3076 	destroy_rcu_head_on_stack(&rh2);
3077 #else /* #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD */
3078 	pr_alert("%s: !CONFIG_DEBUG_OBJECTS_RCU_HEAD, not testing duplicate call_rcu()\n", KBUILD_MODNAME);
3079 #endif /* #else #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD */
3080 }
3081 
3082 static void rcutorture_sync(void)
3083 {
3084 	static unsigned long n;
3085 
3086 	if (cur_ops->sync && !(++n & 0xfff))
3087 		cur_ops->sync();
3088 }
3089 
3090 static int __init
3091 rcu_torture_init(void)
3092 {
3093 	long i;
3094 	int cpu;
3095 	int firsterr = 0;
3096 	int flags = 0;
3097 	unsigned long gp_seq = 0;
3098 	static struct rcu_torture_ops *torture_ops[] = {
3099 		&rcu_ops, &rcu_busted_ops, &srcu_ops, &srcud_ops,
3100 		&busted_srcud_ops, &tasks_ops, &tasks_rude_ops,
3101 		&tasks_tracing_ops, &trivial_ops,
3102 	};
3103 
3104 	if (!torture_init_begin(torture_type, verbose))
3105 		return -EBUSY;
3106 
3107 	/* Process args and tell the world that the torturer is on the job. */
3108 	for (i = 0; i < ARRAY_SIZE(torture_ops); i++) {
3109 		cur_ops = torture_ops[i];
3110 		if (strcmp(torture_type, cur_ops->name) == 0)
3111 			break;
3112 	}
3113 	if (i == ARRAY_SIZE(torture_ops)) {
3114 		pr_alert("rcu-torture: invalid torture type: \"%s\"\n",
3115 			 torture_type);
3116 		pr_alert("rcu-torture types:");
3117 		for (i = 0; i < ARRAY_SIZE(torture_ops); i++)
3118 			pr_cont(" %s", torture_ops[i]->name);
3119 		pr_cont("\n");
3120 		firsterr = -EINVAL;
3121 		cur_ops = NULL;
3122 		goto unwind;
3123 	}
3124 	if (cur_ops->fqs == NULL && fqs_duration != 0) {
3125 		pr_alert("rcu-torture: ->fqs NULL and non-zero fqs_duration, fqs disabled.\n");
3126 		fqs_duration = 0;
3127 	}
3128 	if (cur_ops->init)
3129 		cur_ops->init();
3130 
3131 	if (nreaders >= 0) {
3132 		nrealreaders = nreaders;
3133 	} else {
3134 		nrealreaders = num_online_cpus() - 2 - nreaders;
3135 		if (nrealreaders <= 0)
3136 			nrealreaders = 1;
3137 	}
3138 	rcu_torture_print_module_parms(cur_ops, "Start of test");
3139 	rcutorture_get_gp_data(cur_ops->ttype, &flags, &gp_seq);
3140 	srcutorture_get_gp_data(cur_ops->ttype, srcu_ctlp, &flags, &gp_seq);
3141 	start_gp_seq = gp_seq;
3142 	pr_alert("%s:  Start-test grace-period state: g%ld f%#x\n",
3143 		 cur_ops->name, (long)gp_seq, flags);
3144 
3145 	/* Set up the freelist. */
3146 
3147 	INIT_LIST_HEAD(&rcu_torture_freelist);
3148 	for (i = 0; i < ARRAY_SIZE(rcu_tortures); i++) {
3149 		rcu_tortures[i].rtort_mbtest = 0;
3150 		list_add_tail(&rcu_tortures[i].rtort_free,
3151 			      &rcu_torture_freelist);
3152 	}
3153 
3154 	/* Initialize the statistics so that each run gets its own numbers. */
3155 
3156 	rcu_torture_current = NULL;
3157 	rcu_torture_current_version = 0;
3158 	atomic_set(&n_rcu_torture_alloc, 0);
3159 	atomic_set(&n_rcu_torture_alloc_fail, 0);
3160 	atomic_set(&n_rcu_torture_free, 0);
3161 	atomic_set(&n_rcu_torture_mberror, 0);
3162 	atomic_set(&n_rcu_torture_mbchk_fail, 0);
3163 	atomic_set(&n_rcu_torture_mbchk_tries, 0);
3164 	atomic_set(&n_rcu_torture_error, 0);
3165 	n_rcu_torture_barrier_error = 0;
3166 	n_rcu_torture_boost_ktrerror = 0;
3167 	n_rcu_torture_boost_rterror = 0;
3168 	n_rcu_torture_boost_failure = 0;
3169 	n_rcu_torture_boosts = 0;
3170 	for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++)
3171 		atomic_set(&rcu_torture_wcount[i], 0);
3172 	for_each_possible_cpu(cpu) {
3173 		for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++) {
3174 			per_cpu(rcu_torture_count, cpu)[i] = 0;
3175 			per_cpu(rcu_torture_batch, cpu)[i] = 0;
3176 		}
3177 	}
3178 	err_segs_recorded = 0;
3179 	rt_read_nsegs = 0;
3180 
3181 	/* Start up the kthreads. */
3182 
3183 	rcu_torture_write_types();
3184 	firsterr = torture_create_kthread(rcu_torture_writer, NULL,
3185 					  writer_task);
3186 	if (torture_init_error(firsterr))
3187 		goto unwind;
3188 	if (nfakewriters > 0) {
3189 		fakewriter_tasks = kcalloc(nfakewriters,
3190 					   sizeof(fakewriter_tasks[0]),
3191 					   GFP_KERNEL);
3192 		if (fakewriter_tasks == NULL) {
3193 			TOROUT_ERRSTRING("out of memory");
3194 			firsterr = -ENOMEM;
3195 			goto unwind;
3196 		}
3197 	}
3198 	for (i = 0; i < nfakewriters; i++) {
3199 		firsterr = torture_create_kthread(rcu_torture_fakewriter,
3200 						  NULL, fakewriter_tasks[i]);
3201 		if (torture_init_error(firsterr))
3202 			goto unwind;
3203 	}
3204 	reader_tasks = kcalloc(nrealreaders, sizeof(reader_tasks[0]),
3205 			       GFP_KERNEL);
3206 	rcu_torture_reader_mbchk = kcalloc(nrealreaders, sizeof(*rcu_torture_reader_mbchk),
3207 					   GFP_KERNEL);
3208 	if (!reader_tasks || !rcu_torture_reader_mbchk) {
3209 		TOROUT_ERRSTRING("out of memory");
3210 		firsterr = -ENOMEM;
3211 		goto unwind;
3212 	}
3213 	for (i = 0; i < nrealreaders; i++) {
3214 		rcu_torture_reader_mbchk[i].rtc_chkrdr = -1;
3215 		firsterr = torture_create_kthread(rcu_torture_reader, (void *)i,
3216 						  reader_tasks[i]);
3217 		if (torture_init_error(firsterr))
3218 			goto unwind;
3219 	}
3220 	nrealnocbers = nocbs_nthreads;
3221 	if (WARN_ON(nrealnocbers < 0))
3222 		nrealnocbers = 1;
3223 	if (WARN_ON(nocbs_toggle < 0))
3224 		nocbs_toggle = HZ;
3225 	if (nrealnocbers > 0) {
3226 		nocb_tasks = kcalloc(nrealnocbers, sizeof(nocb_tasks[0]), GFP_KERNEL);
3227 		if (nocb_tasks == NULL) {
3228 			TOROUT_ERRSTRING("out of memory");
3229 			firsterr = -ENOMEM;
3230 			goto unwind;
3231 		}
3232 	} else {
3233 		nocb_tasks = NULL;
3234 	}
3235 	for (i = 0; i < nrealnocbers; i++) {
3236 		firsterr = torture_create_kthread(rcu_nocb_toggle, NULL, nocb_tasks[i]);
3237 		if (torture_init_error(firsterr))
3238 			goto unwind;
3239 	}
3240 	if (stat_interval > 0) {
3241 		firsterr = torture_create_kthread(rcu_torture_stats, NULL,
3242 						  stats_task);
3243 		if (torture_init_error(firsterr))
3244 			goto unwind;
3245 	}
3246 	if (test_no_idle_hz && shuffle_interval > 0) {
3247 		firsterr = torture_shuffle_init(shuffle_interval * HZ);
3248 		if (torture_init_error(firsterr))
3249 			goto unwind;
3250 	}
3251 	if (stutter < 0)
3252 		stutter = 0;
3253 	if (stutter) {
3254 		int t;
3255 
3256 		t = cur_ops->stall_dur ? cur_ops->stall_dur() : stutter * HZ;
3257 		firsterr = torture_stutter_init(stutter * HZ, t);
3258 		if (torture_init_error(firsterr))
3259 			goto unwind;
3260 	}
3261 	if (fqs_duration < 0)
3262 		fqs_duration = 0;
3263 	if (fqs_duration) {
3264 		/* Create the fqs thread */
3265 		firsterr = torture_create_kthread(rcu_torture_fqs, NULL,
3266 						  fqs_task);
3267 		if (torture_init_error(firsterr))
3268 			goto unwind;
3269 	}
3270 	if (test_boost_interval < 1)
3271 		test_boost_interval = 1;
3272 	if (test_boost_duration < 2)
3273 		test_boost_duration = 2;
3274 	if (rcu_torture_can_boost()) {
3275 
3276 		boost_starttime = jiffies + test_boost_interval * HZ;
3277 
3278 		firsterr = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "RCU_TORTURE",
3279 					     rcutorture_booster_init,
3280 					     rcutorture_booster_cleanup);
3281 		rcutor_hp = firsterr;
3282 		if (torture_init_error(firsterr))
3283 			goto unwind;
3284 
3285 		// Testing RCU priority boosting requires rcutorture do
3286 		// some serious abuse.  Counter this by running ksoftirqd
3287 		// at higher priority.
3288 		if (IS_BUILTIN(CONFIG_RCU_TORTURE_TEST)) {
3289 			for_each_online_cpu(cpu) {
3290 				struct sched_param sp;
3291 				struct task_struct *t;
3292 
3293 				t = per_cpu(ksoftirqd, cpu);
3294 				WARN_ON_ONCE(!t);
3295 				sp.sched_priority = 2;
3296 				sched_setscheduler_nocheck(t, SCHED_FIFO, &sp);
3297 			}
3298 		}
3299 	}
3300 	shutdown_jiffies = jiffies + shutdown_secs * HZ;
3301 	firsterr = torture_shutdown_init(shutdown_secs, rcu_torture_cleanup);
3302 	if (torture_init_error(firsterr))
3303 		goto unwind;
3304 	firsterr = torture_onoff_init(onoff_holdoff * HZ, onoff_interval,
3305 				      rcutorture_sync);
3306 	if (torture_init_error(firsterr))
3307 		goto unwind;
3308 	firsterr = rcu_torture_stall_init();
3309 	if (torture_init_error(firsterr))
3310 		goto unwind;
3311 	firsterr = rcu_torture_fwd_prog_init();
3312 	if (torture_init_error(firsterr))
3313 		goto unwind;
3314 	firsterr = rcu_torture_barrier_init();
3315 	if (torture_init_error(firsterr))
3316 		goto unwind;
3317 	firsterr = rcu_torture_read_exit_init();
3318 	if (torture_init_error(firsterr))
3319 		goto unwind;
3320 	if (object_debug)
3321 		rcu_test_debug_objects();
3322 	torture_init_end();
3323 	return 0;
3324 
3325 unwind:
3326 	torture_init_end();
3327 	rcu_torture_cleanup();
3328 	if (shutdown_secs) {
3329 		WARN_ON(!IS_MODULE(CONFIG_RCU_TORTURE_TEST));
3330 		kernel_power_off();
3331 	}
3332 	return firsterr;
3333 }
3334 
3335 module_init(rcu_torture_init);
3336 module_exit(rcu_torture_cleanup);
3337