xref: /linux/kernel/rcu/rcutorture.c (revision 056a5087d87ead77dedbe9cf5bde53b7cd4b4651)
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/rcu_notifier.h>
25 #include <linux/interrupt.h>
26 #include <linux/sched/signal.h>
27 #include <uapi/linux/sched/types.h>
28 #include <linux/atomic.h>
29 #include <linux/bitops.h>
30 #include <linux/completion.h>
31 #include <linux/moduleparam.h>
32 #include <linux/percpu.h>
33 #include <linux/notifier.h>
34 #include <linux/reboot.h>
35 #include <linux/freezer.h>
36 #include <linux/cpu.h>
37 #include <linux/delay.h>
38 #include <linux/stat.h>
39 #include <linux/srcu.h>
40 #include <linux/slab.h>
41 #include <linux/trace_clock.h>
42 #include <asm/byteorder.h>
43 #include <linux/torture.h>
44 #include <linux/vmalloc.h>
45 #include <linux/sched/debug.h>
46 #include <linux/sched/sysctl.h>
47 #include <linux/oom.h>
48 #include <linux/tick.h>
49 #include <linux/rcupdate_trace.h>
50 #include <linux/nmi.h>
51 
52 #include "rcu.h"
53 
54 MODULE_DESCRIPTION("Read-Copy Update module-based torture test facility");
55 MODULE_LICENSE("GPL");
56 MODULE_AUTHOR("Paul E. McKenney <paulmck@linux.ibm.com> and Josh Triplett <josh@joshtriplett.org>");
57 
58 // Bits for ->extendables field, extendables param, and related definitions.
59 #define RCUTORTURE_RDR_SHIFT_1	8	// Put SRCU index in upper bits.
60 #define RCUTORTURE_RDR_MASK_1	(0xff << RCUTORTURE_RDR_SHIFT_1)
61 #define RCUTORTURE_RDR_SHIFT_2	16	// Put SRCU index in upper bits.
62 #define RCUTORTURE_RDR_MASK_2	(0xff << RCUTORTURE_RDR_SHIFT_2)
63 #define RCUTORTURE_RDR_BH	0x01	// Extend readers by disabling bh.
64 #define RCUTORTURE_RDR_IRQ	0x02	//  ... disabling interrupts.
65 #define RCUTORTURE_RDR_PREEMPT	0x04	//  ... disabling preemption.
66 #define RCUTORTURE_RDR_RBH	0x08	//  ... rcu_read_lock_bh().
67 #define RCUTORTURE_RDR_SCHED	0x10	//  ... rcu_read_lock_sched().
68 #define RCUTORTURE_RDR_RCU_1	0x20	//  ... entering another RCU reader.
69 #define RCUTORTURE_RDR_RCU_2	0x40	//  ... entering another RCU reader.
70 #define RCUTORTURE_RDR_UPDOWN	0x80	//  ... up-read from task, down-read from timer.
71 					//	Note: Manual start, automatic end.
72 #define RCUTORTURE_RDR_NBITS	8	// Number of bits defined above.
73 #define RCUTORTURE_MAX_EXTEND	\
74 	(RCUTORTURE_RDR_BH | RCUTORTURE_RDR_IRQ | RCUTORTURE_RDR_PREEMPT | \
75 	 RCUTORTURE_RDR_RBH | RCUTORTURE_RDR_SCHED)  // Intentionally omit RCUTORTURE_RDR_UPDOWN.
76 #define RCUTORTURE_RDR_ALLBITS	\
77 	(RCUTORTURE_MAX_EXTEND | RCUTORTURE_RDR_RCU_1 | RCUTORTURE_RDR_RCU_2 | \
78 	 RCUTORTURE_RDR_MASK_1 | RCUTORTURE_RDR_MASK_2)
79 #define RCUTORTURE_RDR_MAX_LOOPS 0x7	/* Maximum reader extensions. */
80 					/* Must be power of two minus one. */
81 #define RCUTORTURE_RDR_MAX_SEGS (RCUTORTURE_RDR_MAX_LOOPS + 3)
82 
83 torture_param(int, extendables, RCUTORTURE_MAX_EXTEND,
84 	      "Extend readers by disabling bh (1), irqs (2), or preempt (4)");
85 torture_param(int, fqs_duration, 0, "Duration of fqs bursts (us), 0 to disable");
86 torture_param(int, fqs_holdoff, 0, "Holdoff time within fqs bursts (us)");
87 torture_param(int, fqs_stutter, 3, "Wait time between fqs bursts (s)");
88 torture_param(int, fwd_progress, 1, "Number of grace-period forward progress tasks (0 to disable)");
89 torture_param(int, fwd_progress_div, 4, "Fraction of CPU stall to wait");
90 torture_param(int, fwd_progress_holdoff, 60, "Time between forward-progress tests (s)");
91 torture_param(bool, fwd_progress_need_resched, 1, "Hide cond_resched() behind need_resched()");
92 torture_param(bool, gp_cond, false, "Use conditional/async GP wait primitives");
93 torture_param(bool, gp_cond_exp, false, "Use conditional/async expedited GP wait primitives");
94 torture_param(bool, gp_cond_full, false, "Use conditional/async full-state GP wait primitives");
95 torture_param(bool, gp_cond_exp_full, false,
96 		    "Use conditional/async full-stateexpedited GP wait primitives");
97 torture_param(int, gp_cond_wi, 16 * USEC_PER_SEC / HZ,
98 		   "Wait interval for normal conditional grace periods, us (default 16 jiffies)");
99 torture_param(int, gp_cond_wi_exp, 128,
100 		   "Wait interval for expedited conditional grace periods, us (default 128 us)");
101 torture_param(bool, gp_exp, false, "Use expedited GP wait primitives");
102 torture_param(bool, gp_normal, false, "Use normal (non-expedited) GP wait primitives");
103 torture_param(bool, gp_poll, false, "Use polling GP wait primitives");
104 torture_param(bool, gp_poll_exp, false, "Use polling expedited GP wait primitives");
105 torture_param(bool, gp_poll_full, false, "Use polling full-state GP wait primitives");
106 torture_param(bool, gp_poll_exp_full, false, "Use polling full-state expedited GP wait primitives");
107 torture_param(int, gp_poll_wi, 16 * USEC_PER_SEC / HZ,
108 		   "Wait interval for normal polled grace periods, us (default 16 jiffies)");
109 torture_param(int, gp_poll_wi_exp, 128,
110 		   "Wait interval for expedited polled grace periods, us (default 128 us)");
111 torture_param(bool, gp_sync, false, "Use synchronous GP wait primitives");
112 torture_param(int, irqreader, 1, "Allow RCU readers from irq handlers");
113 torture_param(int, leakpointer, 0, "Leak pointer dereferences from readers");
114 torture_param(int, n_barrier_cbs, 0, "# of callbacks/kthreads for barrier testing");
115 torture_param(int, n_up_down, 32, "# of concurrent up/down hrtimer-based RCU readers");
116 torture_param(int, nfakewriters, 4, "Number of RCU fake writer threads");
117 torture_param(int, nreaders, -1, "Number of RCU reader threads");
118 torture_param(int, object_debug, 0, "Enable debug-object double call_rcu() testing");
119 torture_param(int, onoff_holdoff, 0, "Time after boot before CPU hotplugs (s)");
120 torture_param(int, onoff_interval, 0, "Time between CPU hotplugs (jiffies), 0=disable");
121 torture_param(bool, gpwrap_lag, true, "Enable grace-period wrap lag testing");
122 torture_param(int, gpwrap_lag_gps, 8, "Value to set for set_gpwrap_lag during an active testing period.");
123 torture_param(int, gpwrap_lag_cycle_mins, 30, "Total cycle duration for gpwrap lag testing (in minutes)");
124 torture_param(int, gpwrap_lag_active_mins, 5, "Duration for which gpwrap lag is active within each cycle (in minutes)");
125 torture_param(int, nocbs_nthreads, 0, "Number of NOCB toggle threads, 0 to disable");
126 torture_param(int, nocbs_toggle, 1000, "Time between toggling nocb state (ms)");
127 torture_param(int, preempt_duration, 0, "Preemption duration (ms), zero to disable");
128 torture_param(int, preempt_interval, MSEC_PER_SEC, "Interval between preemptions (ms)");
129 torture_param(int, read_exit_delay, 13, "Delay between read-then-exit episodes (s)");
130 torture_param(int, read_exit_burst, 16, "# of read-then-exit bursts per episode, zero to disable");
131 torture_param(int, reader_flavor, SRCU_READ_FLAVOR_NORMAL, "Reader flavors to use, one per bit.");
132 torture_param(int, shuffle_interval, 3, "Number of seconds between shuffles");
133 torture_param(int, shutdown_secs, 0, "Shutdown time (s), <= zero to disable.");
134 torture_param(int, stall_cpu, 0, "Stall duration (s), zero to disable.");
135 torture_param(int, stall_cpu_holdoff, 10, "Time to wait before starting stall (s).");
136 torture_param(bool, stall_no_softlockup, false, "Avoid softlockup warning during cpu stall.");
137 torture_param(int, stall_cpu_irqsoff, 0, "Disable interrupts while stalling.");
138 torture_param(int, stall_cpu_block, 0, "Sleep while stalling.");
139 torture_param(int, stall_cpu_repeat, 0, "Number of additional stalls after the first one.");
140 torture_param(int, stall_gp_kthread, 0, "Grace-period kthread stall duration (s).");
141 torture_param(int, stat_interval, 60, "Number of seconds between stats printk()s");
142 torture_param(int, stutter, 5, "Number of seconds to run/halt test");
143 torture_param(int, test_boost, 1, "Test RCU prio boost: 0=no, 1=maybe, 2=yes.");
144 torture_param(int, test_boost_duration, 4, "Duration of each boost test, seconds.");
145 torture_param(int, test_boost_holdoff, 0, "Holdoff time from rcutorture start, seconds.");
146 torture_param(int, test_boost_interval, 7, "Interval between boost tests, seconds.");
147 torture_param(int, test_nmis, 0, "End-test NMI tests, 0 to disable.");
148 torture_param(bool, test_no_idle_hz, true, "Test support for tickless idle CPUs");
149 torture_param(int, test_srcu_lockdep, 0, "Test specified SRCU deadlock scenario.");
150 torture_param(int, verbose, 1, "Enable verbose debugging printk()s");
151 
152 static char *torture_type = "rcu";
153 module_param(torture_type, charp, 0444);
154 MODULE_PARM_DESC(torture_type, "Type of RCU to torture (rcu, srcu, ...)");
155 
156 static int nrealnocbers;
157 static int nrealreaders;
158 static int nrealfakewriters;
159 static struct task_struct *writer_task;
160 static struct task_struct **fakewriter_tasks;
161 static struct task_struct **reader_tasks;
162 static struct task_struct *updown_task;
163 static struct task_struct **nocb_tasks;
164 static struct task_struct *stats_task;
165 static struct task_struct *fqs_task;
166 static struct task_struct *boost_tasks[NR_CPUS];
167 static struct task_struct *stall_task;
168 static struct task_struct **fwd_prog_tasks;
169 static struct task_struct **barrier_cbs_tasks;
170 static struct task_struct *barrier_task;
171 static struct task_struct *read_exit_task;
172 static struct task_struct *preempt_task;
173 
174 #define RCU_TORTURE_PIPE_LEN 10
175 
176 // Mailbox-like structure to check RCU global memory ordering.
177 struct rcu_torture_reader_check {
178 	unsigned long rtc_myloops;
179 	int rtc_chkrdr;
180 	unsigned long rtc_chkloops;
181 	int rtc_ready;
182 	struct rcu_torture_reader_check *rtc_assigner;
183 } ____cacheline_internodealigned_in_smp;
184 
185 // Update-side data structure used to check RCU readers.
186 struct rcu_torture {
187 	struct rcu_head rtort_rcu;
188 	int rtort_pipe_count;
189 	struct list_head rtort_free;
190 	int rtort_mbtest;
191 	struct rcu_torture_reader_check *rtort_chkp;
192 };
193 
194 static LIST_HEAD(rcu_torture_freelist);
195 static struct rcu_torture __rcu *rcu_torture_current;
196 static unsigned long rcu_torture_current_version;
197 static struct rcu_torture rcu_tortures[10 * RCU_TORTURE_PIPE_LEN];
198 static DEFINE_SPINLOCK(rcu_torture_lock);
199 static DEFINE_PER_CPU(long [RCU_TORTURE_PIPE_LEN + 1], rcu_torture_count);
200 static DEFINE_PER_CPU(long [RCU_TORTURE_PIPE_LEN + 1], rcu_torture_batch);
201 static atomic_t rcu_torture_wcount[RCU_TORTURE_PIPE_LEN + 1];
202 static struct rcu_torture_reader_check *rcu_torture_reader_mbchk;
203 static atomic_t n_rcu_torture_alloc;
204 static atomic_t n_rcu_torture_alloc_fail;
205 static atomic_t n_rcu_torture_free;
206 static atomic_t n_rcu_torture_mberror;
207 static atomic_t n_rcu_torture_mbchk_fail;
208 static atomic_t n_rcu_torture_mbchk_tries;
209 static atomic_t n_rcu_torture_error;
210 static long n_rcu_torture_barrier_error;
211 static long n_rcu_torture_boost_ktrerror;
212 static long n_rcu_torture_boost_failure;
213 static long n_rcu_torture_boosts;
214 static atomic_long_t n_rcu_torture_timers;
215 static long n_barrier_attempts;
216 static long n_barrier_successes; /* did rcu_barrier test succeed? */
217 static unsigned long n_read_exits;
218 static struct list_head rcu_torture_removed;
219 static unsigned long shutdown_jiffies;
220 static unsigned long start_gp_seq;
221 static atomic_long_t n_nocb_offload;
222 static atomic_long_t n_nocb_deoffload;
223 
224 static int rcu_torture_writer_state;
225 #define RTWS_FIXED_DELAY	0
226 #define RTWS_DELAY		1
227 #define RTWS_REPLACE		2
228 #define RTWS_DEF_FREE		3
229 #define RTWS_EXP_SYNC		4
230 #define RTWS_COND_GET		5
231 #define RTWS_COND_GET_FULL	6
232 #define RTWS_COND_GET_EXP	7
233 #define RTWS_COND_GET_EXP_FULL	8
234 #define RTWS_COND_SYNC		9
235 #define RTWS_COND_SYNC_FULL	10
236 #define RTWS_COND_SYNC_EXP	11
237 #define RTWS_COND_SYNC_EXP_FULL	12
238 #define RTWS_POLL_GET		13
239 #define RTWS_POLL_GET_FULL	14
240 #define RTWS_POLL_GET_EXP	15
241 #define RTWS_POLL_GET_EXP_FULL	16
242 #define RTWS_POLL_WAIT		17
243 #define RTWS_POLL_WAIT_FULL	18
244 #define RTWS_POLL_WAIT_EXP	19
245 #define RTWS_POLL_WAIT_EXP_FULL	20
246 #define RTWS_SYNC		21
247 #define RTWS_STUTTER		22
248 #define RTWS_STOPPING		23
249 static const char * const rcu_torture_writer_state_names[] = {
250 	"RTWS_FIXED_DELAY",
251 	"RTWS_DELAY",
252 	"RTWS_REPLACE",
253 	"RTWS_DEF_FREE",
254 	"RTWS_EXP_SYNC",
255 	"RTWS_COND_GET",
256 	"RTWS_COND_GET_FULL",
257 	"RTWS_COND_GET_EXP",
258 	"RTWS_COND_GET_EXP_FULL",
259 	"RTWS_COND_SYNC",
260 	"RTWS_COND_SYNC_FULL",
261 	"RTWS_COND_SYNC_EXP",
262 	"RTWS_COND_SYNC_EXP_FULL",
263 	"RTWS_POLL_GET",
264 	"RTWS_POLL_GET_FULL",
265 	"RTWS_POLL_GET_EXP",
266 	"RTWS_POLL_GET_EXP_FULL",
267 	"RTWS_POLL_WAIT",
268 	"RTWS_POLL_WAIT_FULL",
269 	"RTWS_POLL_WAIT_EXP",
270 	"RTWS_POLL_WAIT_EXP_FULL",
271 	"RTWS_SYNC",
272 	"RTWS_STUTTER",
273 	"RTWS_STOPPING",
274 };
275 
276 /* Record reader segment types and duration for first failing read. */
277 struct rt_read_seg {
278 	int rt_readstate;
279 	unsigned long rt_delay_jiffies;
280 	unsigned long rt_delay_ms;
281 	unsigned long rt_delay_us;
282 	bool rt_preempted;
283 	int rt_cpu;
284 	int rt_end_cpu;
285 	unsigned long long rt_gp_seq;
286 	unsigned long long rt_gp_seq_end;
287 	u64 rt_ts;
288 };
289 static int err_segs_recorded;
290 static struct rt_read_seg err_segs[RCUTORTURE_RDR_MAX_SEGS];
291 static int rt_read_nsegs;
292 static int rt_read_preempted;
293 
294 static const char *rcu_torture_writer_state_getname(void)
295 {
296 	unsigned int i = READ_ONCE(rcu_torture_writer_state);
297 
298 	if (i >= ARRAY_SIZE(rcu_torture_writer_state_names))
299 		return "???";
300 	return rcu_torture_writer_state_names[i];
301 }
302 
303 #ifdef CONFIG_RCU_TRACE
304 static u64 notrace rcu_trace_clock_local(void)
305 {
306 	u64 ts = trace_clock_local();
307 
308 	(void)do_div(ts, NSEC_PER_USEC);
309 	return ts;
310 }
311 #else /* #ifdef CONFIG_RCU_TRACE */
312 static u64 notrace rcu_trace_clock_local(void)
313 {
314 	return 0ULL;
315 }
316 #endif /* #else #ifdef CONFIG_RCU_TRACE */
317 
318 /*
319  * Stop aggressive CPU-hog tests a bit before the end of the test in order
320  * to avoid interfering with test shutdown.
321  */
322 static bool shutdown_time_arrived(void)
323 {
324 	return shutdown_secs && time_after(jiffies, shutdown_jiffies - 30 * HZ);
325 }
326 
327 static unsigned long boost_starttime;	/* jiffies of next boost test start. */
328 static DEFINE_MUTEX(boost_mutex);	/* protect setting boost_starttime */
329 					/*  and boost task create/destroy. */
330 static atomic_t barrier_cbs_count;	/* Barrier callbacks registered. */
331 static bool barrier_phase;		/* Test phase. */
332 static atomic_t barrier_cbs_invoked;	/* Barrier callbacks invoked. */
333 static wait_queue_head_t *barrier_cbs_wq; /* Coordinate barrier testing. */
334 static DECLARE_WAIT_QUEUE_HEAD(barrier_wq);
335 
336 static atomic_t rcu_fwd_cb_nodelay;	/* Short rcu_torture_delay() delays. */
337 
338 /*
339  * Allocate an element from the rcu_tortures pool.
340  */
341 static struct rcu_torture *
342 rcu_torture_alloc(void)
343 {
344 	struct list_head *p;
345 
346 	spin_lock_bh(&rcu_torture_lock);
347 	if (list_empty(&rcu_torture_freelist)) {
348 		atomic_inc(&n_rcu_torture_alloc_fail);
349 		spin_unlock_bh(&rcu_torture_lock);
350 		return NULL;
351 	}
352 	atomic_inc(&n_rcu_torture_alloc);
353 	p = rcu_torture_freelist.next;
354 	list_del_init(p);
355 	spin_unlock_bh(&rcu_torture_lock);
356 	return container_of(p, struct rcu_torture, rtort_free);
357 }
358 
359 /*
360  * Free an element to the rcu_tortures pool.
361  */
362 static void
363 rcu_torture_free(struct rcu_torture *p)
364 {
365 	atomic_inc(&n_rcu_torture_free);
366 	spin_lock_bh(&rcu_torture_lock);
367 	list_add_tail(&p->rtort_free, &rcu_torture_freelist);
368 	spin_unlock_bh(&rcu_torture_lock);
369 }
370 
371 /*
372  * Operations vector for selecting different types of tests.
373  */
374 
375 struct rcu_torture_ops {
376 	int ttype;
377 	void (*init)(void);
378 	void (*cleanup)(void);
379 	int (*readlock)(void);
380 	void (*read_delay)(struct torture_random_state *rrsp,
381 			   struct rt_read_seg *rtrsp);
382 	void (*readunlock)(int idx);
383 	int (*readlock_held)(void);   // lockdep.
384 	int (*readlock_nesting)(void); // actual nesting, if available, -1 if not.
385 	int (*down_read)(void);
386 	void (*up_read)(int idx);
387 	unsigned long (*get_gp_seq)(void);
388 	unsigned long (*gp_diff)(unsigned long new, unsigned long old);
389 	void (*deferred_free)(struct rcu_torture *p);
390 	void (*sync)(void);
391 	void (*exp_sync)(void);
392 	void (*exp_current)(void);
393 	unsigned long (*get_gp_state_exp)(void);
394 	unsigned long (*start_gp_poll_exp)(void);
395 	void (*start_gp_poll_exp_full)(struct rcu_gp_oldstate *rgosp);
396 	bool (*poll_gp_state_exp)(unsigned long oldstate);
397 	void (*cond_sync_exp)(unsigned long oldstate);
398 	void (*cond_sync_exp_full)(struct rcu_gp_oldstate *rgosp);
399 	unsigned long (*get_comp_state)(void);
400 	void (*get_comp_state_full)(struct rcu_gp_oldstate *rgosp);
401 	bool (*same_gp_state)(unsigned long oldstate1, unsigned long oldstate2);
402 	bool (*same_gp_state_full)(struct rcu_gp_oldstate *rgosp1, struct rcu_gp_oldstate *rgosp2);
403 	unsigned long (*get_gp_state)(void);
404 	void (*get_gp_state_full)(struct rcu_gp_oldstate *rgosp);
405 	unsigned long (*start_gp_poll)(void);
406 	void (*start_gp_poll_full)(struct rcu_gp_oldstate *rgosp);
407 	bool (*poll_gp_state)(unsigned long oldstate);
408 	bool (*poll_gp_state_full)(struct rcu_gp_oldstate *rgosp);
409 	bool (*poll_need_2gp)(bool poll, bool poll_full);
410 	void (*cond_sync)(unsigned long oldstate);
411 	void (*cond_sync_full)(struct rcu_gp_oldstate *rgosp);
412 	int poll_active;
413 	int poll_active_full;
414 	call_rcu_func_t call;
415 	void (*cb_barrier)(void);
416 	void (*fqs)(void);
417 	void (*stats)(void);
418 	void (*gp_kthread_dbg)(void);
419 	bool (*check_boost_failed)(unsigned long gp_state, int *cpup);
420 	int (*stall_dur)(void);
421 	void (*get_gp_data)(int *flags, unsigned long *gp_seq);
422 	void (*gp_slow_register)(atomic_t *rgssp);
423 	void (*gp_slow_unregister)(atomic_t *rgssp);
424 	bool (*reader_blocked)(void);
425 	unsigned long long (*gather_gp_seqs)(void);
426 	void (*format_gp_seqs)(unsigned long long seqs, char *cp, size_t len);
427 	void (*set_gpwrap_lag)(unsigned long lag);
428 	int (*get_gpwrap_count)(int cpu);
429 	long cbflood_max;
430 	int irq_capable;
431 	int can_boost;
432 	int extendables;
433 	int slow_gps;
434 	int no_pi_lock;
435 	int debug_objects;
436 	int start_poll_irqsoff;
437 	int have_up_down;
438 	const char *name;
439 };
440 
441 static struct rcu_torture_ops *cur_ops;
442 
443 /*
444  * Definitions for rcu torture testing.
445  */
446 
447 static int torture_readlock_not_held(void)
448 {
449 	return rcu_read_lock_bh_held() || rcu_read_lock_sched_held();
450 }
451 
452 static int rcu_torture_read_lock(void)
453 {
454 	rcu_read_lock();
455 	return 0;
456 }
457 
458 static void
459 rcu_read_delay(struct torture_random_state *rrsp, struct rt_read_seg *rtrsp)
460 {
461 	unsigned long started;
462 	unsigned long completed;
463 	const unsigned long shortdelay_us = 200;
464 	unsigned long longdelay_ms = 300;
465 	unsigned long long ts;
466 
467 	/* We want a short delay sometimes to make a reader delay the grace
468 	 * period, and we want a long delay occasionally to trigger
469 	 * force_quiescent_state. */
470 
471 	if (!atomic_read(&rcu_fwd_cb_nodelay) &&
472 	    !(torture_random(rrsp) % (nrealreaders * 2000 * longdelay_ms))) {
473 		started = cur_ops->get_gp_seq();
474 		ts = rcu_trace_clock_local();
475 		if ((preempt_count() & HARDIRQ_MASK) || softirq_count())
476 			longdelay_ms = 5; /* Avoid triggering BH limits. */
477 		mdelay(longdelay_ms);
478 		rtrsp->rt_delay_ms = longdelay_ms;
479 		completed = cur_ops->get_gp_seq();
480 		do_trace_rcu_torture_read(cur_ops->name, NULL, ts,
481 					  started, completed);
482 	}
483 	if (!(torture_random(rrsp) % (nrealreaders * 2 * shortdelay_us))) {
484 		udelay(shortdelay_us);
485 		rtrsp->rt_delay_us = shortdelay_us;
486 	}
487 	if (!preempt_count() &&
488 	    !(torture_random(rrsp) % (nrealreaders * 500)))
489 		torture_preempt_schedule();  /* QS only if preemptible. */
490 }
491 
492 static void rcu_torture_read_unlock(int idx)
493 {
494 	rcu_read_unlock();
495 }
496 
497 static int rcu_torture_readlock_nesting(void)
498 {
499 	if (IS_ENABLED(CONFIG_PREEMPT_RCU))
500 		return rcu_preempt_depth();
501 	if (IS_ENABLED(CONFIG_PREEMPT_COUNT))
502 		return (preempt_count() & PREEMPT_MASK);
503 	return -1;
504 }
505 
506 /*
507  * Update callback in the pipe.  This should be invoked after a grace period.
508  */
509 static bool
510 rcu_torture_pipe_update_one(struct rcu_torture *rp)
511 {
512 	int i;
513 	struct rcu_torture_reader_check *rtrcp = READ_ONCE(rp->rtort_chkp);
514 
515 	if (rtrcp) {
516 		WRITE_ONCE(rp->rtort_chkp, NULL);
517 		smp_store_release(&rtrcp->rtc_ready, 1); // Pair with smp_load_acquire().
518 	}
519 	i = rp->rtort_pipe_count;
520 	if (i > RCU_TORTURE_PIPE_LEN)
521 		i = RCU_TORTURE_PIPE_LEN;
522 	atomic_inc(&rcu_torture_wcount[i]);
523 	WRITE_ONCE(rp->rtort_pipe_count, i + 1);
524 	ASSERT_EXCLUSIVE_WRITER(rp->rtort_pipe_count);
525 	if (i + 1 >= RCU_TORTURE_PIPE_LEN) {
526 		rp->rtort_mbtest = 0;
527 		return true;
528 	}
529 	return false;
530 }
531 
532 /*
533  * Update all callbacks in the pipe.  Suitable for synchronous grace-period
534  * primitives.
535  */
536 static void
537 rcu_torture_pipe_update(struct rcu_torture *old_rp)
538 {
539 	struct rcu_torture *rp;
540 	struct rcu_torture *rp1;
541 
542 	if (old_rp)
543 		list_add(&old_rp->rtort_free, &rcu_torture_removed);
544 	list_for_each_entry_safe(rp, rp1, &rcu_torture_removed, rtort_free) {
545 		if (rcu_torture_pipe_update_one(rp)) {
546 			list_del(&rp->rtort_free);
547 			rcu_torture_free(rp);
548 		}
549 	}
550 }
551 
552 static void
553 rcu_torture_cb(struct rcu_head *p)
554 {
555 	struct rcu_torture *rp = container_of(p, struct rcu_torture, rtort_rcu);
556 
557 	if (torture_must_stop_irq()) {
558 		/* Test is ending, just drop callbacks on the floor. */
559 		/* The next initialization will pick up the pieces. */
560 		return;
561 	}
562 	if (rcu_torture_pipe_update_one(rp))
563 		rcu_torture_free(rp);
564 	else
565 		cur_ops->deferred_free(rp);
566 }
567 
568 static unsigned long rcu_no_completed(void)
569 {
570 	return 0;
571 }
572 
573 static void rcu_torture_deferred_free(struct rcu_torture *p)
574 {
575 	call_rcu(&p->rtort_rcu, rcu_torture_cb);
576 }
577 
578 static void rcu_sync_torture_init(void)
579 {
580 	INIT_LIST_HEAD(&rcu_torture_removed);
581 }
582 
583 static bool rcu_poll_need_2gp(bool poll, bool poll_full)
584 {
585 	return poll;
586 }
587 
588 static struct rcu_torture_ops rcu_ops = {
589 	.ttype			= RCU_FLAVOR,
590 	.init			= rcu_sync_torture_init,
591 	.readlock		= rcu_torture_read_lock,
592 	.read_delay		= rcu_read_delay,
593 	.readunlock		= rcu_torture_read_unlock,
594 	.readlock_held		= torture_readlock_not_held,
595 	.readlock_nesting	= rcu_torture_readlock_nesting,
596 	.get_gp_seq		= rcu_get_gp_seq,
597 	.gp_diff		= rcu_seq_diff,
598 	.deferred_free		= rcu_torture_deferred_free,
599 	.sync			= synchronize_rcu,
600 	.exp_sync		= synchronize_rcu_expedited,
601 	.same_gp_state		= same_state_synchronize_rcu,
602 	.same_gp_state_full	= same_state_synchronize_rcu_full,
603 	.get_comp_state		= get_completed_synchronize_rcu,
604 	.get_comp_state_full	= get_completed_synchronize_rcu_full,
605 	.get_gp_state		= get_state_synchronize_rcu,
606 	.get_gp_state_full	= get_state_synchronize_rcu_full,
607 	.start_gp_poll		= start_poll_synchronize_rcu,
608 	.start_gp_poll_full	= start_poll_synchronize_rcu_full,
609 	.poll_gp_state		= poll_state_synchronize_rcu,
610 	.poll_gp_state_full	= poll_state_synchronize_rcu_full,
611 	.poll_need_2gp		= rcu_poll_need_2gp,
612 	.cond_sync		= cond_synchronize_rcu,
613 	.cond_sync_full		= cond_synchronize_rcu_full,
614 	.poll_active		= NUM_ACTIVE_RCU_POLL_OLDSTATE,
615 	.poll_active_full	= NUM_ACTIVE_RCU_POLL_FULL_OLDSTATE,
616 	.get_gp_state_exp	= get_state_synchronize_rcu,
617 	.start_gp_poll_exp	= start_poll_synchronize_rcu_expedited,
618 	.start_gp_poll_exp_full	= start_poll_synchronize_rcu_expedited_full,
619 	.poll_gp_state_exp	= poll_state_synchronize_rcu,
620 	.cond_sync_exp		= cond_synchronize_rcu_expedited,
621 	.cond_sync_exp_full	= cond_synchronize_rcu_expedited_full,
622 	.call			= call_rcu,
623 	.cb_barrier		= rcu_barrier,
624 	.fqs			= rcu_force_quiescent_state,
625 	.gp_kthread_dbg		= show_rcu_gp_kthreads,
626 	.check_boost_failed	= rcu_check_boost_fail,
627 	.stall_dur		= rcu_jiffies_till_stall_check,
628 	.get_gp_data		= rcutorture_get_gp_data,
629 	.gp_slow_register	= rcu_gp_slow_register,
630 	.gp_slow_unregister	= rcu_gp_slow_unregister,
631 	.reader_blocked		= IS_ENABLED(CONFIG_RCU_TORTURE_TEST_LOG_CPU)
632 				  ? has_rcu_reader_blocked
633 				  : NULL,
634 	.gather_gp_seqs		= rcutorture_gather_gp_seqs,
635 	.format_gp_seqs		= rcutorture_format_gp_seqs,
636 	.set_gpwrap_lag		= rcu_set_gpwrap_lag,
637 	.get_gpwrap_count	= rcu_get_gpwrap_count,
638 	.irq_capable		= 1,
639 	.can_boost		= IS_ENABLED(CONFIG_RCU_BOOST),
640 	.extendables		= RCUTORTURE_MAX_EXTEND,
641 	.debug_objects		= 1,
642 	.start_poll_irqsoff	= 1,
643 	.name			= "rcu"
644 };
645 
646 /*
647  * Don't even think about trying any of these in real life!!!
648  * The names includes "busted", and they really means it!
649  * The only purpose of these functions is to provide a buggy RCU
650  * implementation to make sure that rcutorture correctly emits
651  * buggy-RCU error messages.
652  */
653 static void rcu_busted_torture_deferred_free(struct rcu_torture *p)
654 {
655 	/* This is a deliberate bug for testing purposes only! */
656 	rcu_torture_cb(&p->rtort_rcu);
657 }
658 
659 static void synchronize_rcu_busted(void)
660 {
661 	/* This is a deliberate bug for testing purposes only! */
662 }
663 
664 static void
665 call_rcu_busted(struct rcu_head *head, rcu_callback_t func)
666 {
667 	/* This is a deliberate bug for testing purposes only! */
668 	func(head);
669 }
670 
671 static struct rcu_torture_ops rcu_busted_ops = {
672 	.ttype		= INVALID_RCU_FLAVOR,
673 	.init		= rcu_sync_torture_init,
674 	.readlock	= rcu_torture_read_lock,
675 	.read_delay	= rcu_read_delay,  /* just reuse rcu's version. */
676 	.readunlock	= rcu_torture_read_unlock,
677 	.readlock_held	= torture_readlock_not_held,
678 	.get_gp_seq	= rcu_no_completed,
679 	.deferred_free	= rcu_busted_torture_deferred_free,
680 	.sync		= synchronize_rcu_busted,
681 	.exp_sync	= synchronize_rcu_busted,
682 	.call		= call_rcu_busted,
683 	.gather_gp_seqs	= rcutorture_gather_gp_seqs,
684 	.format_gp_seqs	= rcutorture_format_gp_seqs,
685 	.irq_capable	= 1,
686 	.extendables	= RCUTORTURE_MAX_EXTEND,
687 	.name		= "busted"
688 };
689 
690 /*
691  * Definitions for srcu torture testing.
692  */
693 
694 DEFINE_STATIC_SRCU(srcu_ctl);
695 DEFINE_STATIC_SRCU_FAST(srcu_ctlf);
696 DEFINE_STATIC_SRCU_FAST_UPDOWN(srcu_ctlfud);
697 static struct srcu_struct srcu_ctld;
698 static struct srcu_struct *srcu_ctlp = &srcu_ctl;
699 static struct rcu_torture_ops srcud_ops;
700 
701 static void srcu_torture_init(void)
702 {
703 	rcu_sync_torture_init();
704 	if (!reader_flavor || (reader_flavor & SRCU_READ_FLAVOR_NORMAL))
705 		VERBOSE_TOROUT_STRING("srcu_torture_init normal SRCU");
706 	if (reader_flavor & SRCU_READ_FLAVOR_NMI)
707 		VERBOSE_TOROUT_STRING("srcu_torture_init NMI-safe SRCU");
708 	if (reader_flavor & SRCU_READ_FLAVOR_FAST) {
709 		srcu_ctlp = &srcu_ctlf;
710 		VERBOSE_TOROUT_STRING("srcu_torture_init fast SRCU");
711 	}
712 	if (reader_flavor & SRCU_READ_FLAVOR_FAST_UPDOWN) {
713 		srcu_ctlp = &srcu_ctlfud;
714 		VERBOSE_TOROUT_STRING("srcu_torture_init fast-up/down SRCU");
715 	}
716 }
717 
718 static void srcu_get_gp_data(int *flags, unsigned long *gp_seq)
719 {
720 	srcutorture_get_gp_data(srcu_ctlp, flags, gp_seq);
721 }
722 
723 static int srcu_torture_read_lock(void)
724 {
725 	int idx;
726 	struct srcu_ctr __percpu *scp;
727 	int ret = 0;
728 
729 	WARN_ON_ONCE(reader_flavor & ~SRCU_READ_FLAVOR_ALL);
730 
731 	if ((reader_flavor & SRCU_READ_FLAVOR_NORMAL) || !(reader_flavor & SRCU_READ_FLAVOR_ALL)) {
732 		idx = srcu_read_lock(srcu_ctlp);
733 		WARN_ON_ONCE(idx & ~0x1);
734 		ret += idx;
735 	}
736 	if (reader_flavor & SRCU_READ_FLAVOR_NMI) {
737 		idx = srcu_read_lock_nmisafe(srcu_ctlp);
738 		WARN_ON_ONCE(idx & ~0x1);
739 		ret += idx << 1;
740 	}
741 	if (reader_flavor & SRCU_READ_FLAVOR_FAST) {
742 		scp = srcu_read_lock_fast(srcu_ctlp);
743 		idx = __srcu_ptr_to_ctr(srcu_ctlp, scp);
744 		WARN_ON_ONCE(idx & ~0x1);
745 		ret += idx << 2;
746 	}
747 	if (reader_flavor & SRCU_READ_FLAVOR_FAST_UPDOWN) {
748 		scp = srcu_read_lock_fast_updown(srcu_ctlp);
749 		idx = __srcu_ptr_to_ctr(srcu_ctlp, scp);
750 		WARN_ON_ONCE(idx & ~0x1);
751 		ret += idx << 3;
752 	}
753 	return ret;
754 }
755 
756 static void
757 srcu_read_delay(struct torture_random_state *rrsp, struct rt_read_seg *rtrsp)
758 {
759 	long delay;
760 	const long uspertick = 1000000 / HZ;
761 	const long longdelay = 10;
762 
763 	/* We want there to be long-running readers, but not all the time. */
764 
765 	delay = torture_random(rrsp) %
766 		(nrealreaders * 2 * longdelay * uspertick);
767 	if (!delay && in_task()) {
768 		schedule_timeout_interruptible(longdelay);
769 		rtrsp->rt_delay_jiffies = longdelay;
770 	} else {
771 		rcu_read_delay(rrsp, rtrsp);
772 	}
773 }
774 
775 static void srcu_torture_read_unlock(int idx)
776 {
777 	WARN_ON_ONCE((reader_flavor && (idx & ~reader_flavor)) || (!reader_flavor && (idx & ~0x1)));
778 	if (reader_flavor & SRCU_READ_FLAVOR_FAST_UPDOWN)
779 		srcu_read_unlock_fast_updown(srcu_ctlp,
780 					     __srcu_ctr_to_ptr(srcu_ctlp, (idx & 0x8) >> 3));
781 	if (reader_flavor & SRCU_READ_FLAVOR_FAST)
782 		srcu_read_unlock_fast(srcu_ctlp, __srcu_ctr_to_ptr(srcu_ctlp, (idx & 0x4) >> 2));
783 	if (reader_flavor & SRCU_READ_FLAVOR_NMI)
784 		srcu_read_unlock_nmisafe(srcu_ctlp, (idx & 0x2) >> 1);
785 	if ((reader_flavor & SRCU_READ_FLAVOR_NORMAL) || !(reader_flavor & SRCU_READ_FLAVOR_ALL))
786 		srcu_read_unlock(srcu_ctlp, idx & 0x1);
787 }
788 
789 static int torture_srcu_read_lock_held(void)
790 {
791 	return srcu_read_lock_held(srcu_ctlp);
792 }
793 
794 static bool srcu_torture_have_up_down(void)
795 {
796 	int rf = reader_flavor;
797 
798 	if (!rf)
799 		rf = SRCU_READ_FLAVOR_NORMAL;
800 	return !!(cur_ops->have_up_down & rf);
801 }
802 
803 static int srcu_torture_down_read(void)
804 {
805 	int idx;
806 	struct srcu_ctr __percpu *scp;
807 
808 	WARN_ON_ONCE(reader_flavor & ~SRCU_READ_FLAVOR_ALL);
809 	WARN_ON_ONCE(reader_flavor & (reader_flavor - 1));
810 
811 	if ((reader_flavor & SRCU_READ_FLAVOR_NORMAL) || !(reader_flavor & SRCU_READ_FLAVOR_ALL)) {
812 		idx = srcu_down_read(srcu_ctlp);
813 		WARN_ON_ONCE(idx & ~0x1);
814 		return idx;
815 	}
816 	if (reader_flavor & SRCU_READ_FLAVOR_FAST_UPDOWN) {
817 		scp = srcu_down_read_fast(srcu_ctlp);
818 		idx = __srcu_ptr_to_ctr(srcu_ctlp, scp);
819 		WARN_ON_ONCE(idx & ~0x1);
820 		return idx << 3;
821 	}
822 	WARN_ON_ONCE(1);
823 	return 0;
824 }
825 
826 static void srcu_torture_up_read(int idx)
827 {
828 	WARN_ON_ONCE((reader_flavor && (idx & ~reader_flavor)) || (!reader_flavor && (idx & ~0x1)));
829 	if (reader_flavor & SRCU_READ_FLAVOR_FAST_UPDOWN)
830 		srcu_up_read_fast(srcu_ctlp, __srcu_ctr_to_ptr(srcu_ctlp, (idx & 0x8) >> 3));
831 	else if ((reader_flavor & SRCU_READ_FLAVOR_NORMAL) ||
832 		 !(reader_flavor & SRCU_READ_FLAVOR_ALL))
833 		srcu_up_read(srcu_ctlp, idx & 0x1);
834 	else
835 		WARN_ON_ONCE(1);
836 }
837 
838 static unsigned long srcu_torture_completed(void)
839 {
840 	return srcu_batches_completed(srcu_ctlp);
841 }
842 
843 static void srcu_torture_deferred_free(struct rcu_torture *rp)
844 {
845 	unsigned long flags;
846 	bool lockit = jiffies & 0x1;
847 
848 	if (lockit)
849 		raw_spin_lock_irqsave(&current->pi_lock, flags);
850 	call_srcu(srcu_ctlp, &rp->rtort_rcu, rcu_torture_cb);
851 	if (lockit)
852 		raw_spin_unlock_irqrestore(&current->pi_lock, flags);
853 }
854 
855 static void srcu_torture_synchronize(void)
856 {
857 	synchronize_srcu(srcu_ctlp);
858 }
859 
860 static unsigned long srcu_torture_get_gp_state(void)
861 {
862 	return get_state_synchronize_srcu(srcu_ctlp);
863 }
864 
865 static unsigned long srcu_torture_start_gp_poll(void)
866 {
867 	return start_poll_synchronize_srcu(srcu_ctlp);
868 }
869 
870 static bool srcu_torture_poll_gp_state(unsigned long oldstate)
871 {
872 	return poll_state_synchronize_srcu(srcu_ctlp, oldstate);
873 }
874 
875 static void srcu_torture_call(struct rcu_head *head,
876 			      rcu_callback_t func)
877 {
878 	call_srcu(srcu_ctlp, head, func);
879 }
880 
881 static void srcu_torture_barrier(void)
882 {
883 	srcu_barrier(srcu_ctlp);
884 }
885 
886 static void srcu_torture_stats(void)
887 {
888 	srcu_torture_stats_print(srcu_ctlp, torture_type, TORTURE_FLAG);
889 }
890 
891 static void srcu_torture_synchronize_expedited(void)
892 {
893 	synchronize_srcu_expedited(srcu_ctlp);
894 }
895 
896 static void srcu_torture_expedite_current(void)
897 {
898 	srcu_expedite_current(srcu_ctlp);
899 }
900 
901 static struct rcu_torture_ops srcu_ops = {
902 	.ttype		= SRCU_FLAVOR,
903 	.init		= srcu_torture_init,
904 	.readlock	= srcu_torture_read_lock,
905 	.read_delay	= srcu_read_delay,
906 	.readunlock	= srcu_torture_read_unlock,
907 	.down_read	= srcu_torture_down_read,
908 	.up_read	= srcu_torture_up_read,
909 	.readlock_held	= torture_srcu_read_lock_held,
910 	.get_gp_seq	= srcu_torture_completed,
911 	.gp_diff	= rcu_seq_diff,
912 	.deferred_free	= srcu_torture_deferred_free,
913 	.sync		= srcu_torture_synchronize,
914 	.exp_sync	= srcu_torture_synchronize_expedited,
915 	.exp_current	= srcu_torture_expedite_current,
916 	.same_gp_state	= same_state_synchronize_srcu,
917 	.get_comp_state = get_completed_synchronize_srcu,
918 	.get_gp_state	= srcu_torture_get_gp_state,
919 	.start_gp_poll	= srcu_torture_start_gp_poll,
920 	.poll_gp_state	= srcu_torture_poll_gp_state,
921 	.poll_active	= NUM_ACTIVE_SRCU_POLL_OLDSTATE,
922 	.call		= srcu_torture_call,
923 	.cb_barrier	= srcu_torture_barrier,
924 	.stats		= srcu_torture_stats,
925 	.get_gp_data	= srcu_get_gp_data,
926 	.cbflood_max	= 50000,
927 	.irq_capable	= 1,
928 	.no_pi_lock	= IS_ENABLED(CONFIG_TINY_SRCU),
929 	.debug_objects	= 1,
930 	.have_up_down	= IS_ENABLED(CONFIG_TINY_SRCU)
931 				? 0 : SRCU_READ_FLAVOR_NORMAL | SRCU_READ_FLAVOR_FAST_UPDOWN,
932 	.name		= "srcu"
933 };
934 
935 static void srcud_torture_init(void)
936 {
937 	rcu_sync_torture_init();
938 	if (!reader_flavor || (reader_flavor & SRCU_READ_FLAVOR_NORMAL)) {
939 		WARN_ON(init_srcu_struct(&srcu_ctld));
940 		VERBOSE_TOROUT_STRING("srcud_torture_init normal SRCU");
941 	} else if (reader_flavor & SRCU_READ_FLAVOR_NMI) {
942 		WARN_ON(init_srcu_struct(&srcu_ctld));
943 		VERBOSE_TOROUT_STRING("srcud_torture_init NMI-safe SRCU");
944 	} else if (reader_flavor & SRCU_READ_FLAVOR_FAST) {
945 		WARN_ON(init_srcu_struct_fast(&srcu_ctld));
946 		VERBOSE_TOROUT_STRING("srcud_torture_init fast SRCU");
947 	} else if (reader_flavor & SRCU_READ_FLAVOR_FAST_UPDOWN) {
948 		WARN_ON(init_srcu_struct_fast_updown(&srcu_ctld));
949 		VERBOSE_TOROUT_STRING("srcud_torture_init fast-up/down SRCU");
950 	} else {
951 		WARN_ON(init_srcu_struct(&srcu_ctld));
952 	}
953 	srcu_ctlp = &srcu_ctld;
954 }
955 
956 static void srcu_torture_cleanup(void)
957 {
958 	cleanup_srcu_struct(&srcu_ctld);
959 	srcu_ctlp = &srcu_ctl; /* In case of a later rcutorture run. */
960 }
961 
962 /* As above, but dynamically allocated. */
963 static struct rcu_torture_ops srcud_ops = {
964 	.ttype		= SRCU_FLAVOR,
965 	.init		= srcud_torture_init,
966 	.cleanup	= srcu_torture_cleanup,
967 	.readlock	= srcu_torture_read_lock,
968 	.read_delay	= srcu_read_delay,
969 	.readunlock	= srcu_torture_read_unlock,
970 	.readlock_held	= torture_srcu_read_lock_held,
971 	.down_read	= srcu_torture_down_read,
972 	.up_read	= srcu_torture_up_read,
973 	.get_gp_seq	= srcu_torture_completed,
974 	.gp_diff	= rcu_seq_diff,
975 	.deferred_free	= srcu_torture_deferred_free,
976 	.sync		= srcu_torture_synchronize,
977 	.exp_sync	= srcu_torture_synchronize_expedited,
978 	.exp_current	= srcu_torture_expedite_current,
979 	.same_gp_state	= same_state_synchronize_srcu,
980 	.get_comp_state = get_completed_synchronize_srcu,
981 	.get_gp_state	= srcu_torture_get_gp_state,
982 	.start_gp_poll	= srcu_torture_start_gp_poll,
983 	.poll_gp_state	= srcu_torture_poll_gp_state,
984 	.poll_active	= NUM_ACTIVE_SRCU_POLL_OLDSTATE,
985 	.call		= srcu_torture_call,
986 	.cb_barrier	= srcu_torture_barrier,
987 	.stats		= srcu_torture_stats,
988 	.get_gp_data	= srcu_get_gp_data,
989 	.cbflood_max	= 50000,
990 	.irq_capable	= 1,
991 	.no_pi_lock	= IS_ENABLED(CONFIG_TINY_SRCU),
992 	.debug_objects	= 1,
993 	.have_up_down	= IS_ENABLED(CONFIG_TINY_SRCU)
994 				? 0 : SRCU_READ_FLAVOR_NORMAL | SRCU_READ_FLAVOR_FAST_UPDOWN,
995 	.name		= "srcud"
996 };
997 
998 /* As above, but broken due to inappropriate reader extension. */
999 static struct rcu_torture_ops busted_srcud_ops = {
1000 	.ttype		= SRCU_FLAVOR,
1001 	.init		= srcu_torture_init,
1002 	.cleanup	= srcu_torture_cleanup,
1003 	.readlock	= srcu_torture_read_lock,
1004 	.read_delay	= rcu_read_delay,
1005 	.readunlock	= srcu_torture_read_unlock,
1006 	.readlock_held	= torture_srcu_read_lock_held,
1007 	.get_gp_seq	= srcu_torture_completed,
1008 	.deferred_free	= srcu_torture_deferred_free,
1009 	.sync		= srcu_torture_synchronize,
1010 	.exp_sync	= srcu_torture_synchronize_expedited,
1011 	.call		= srcu_torture_call,
1012 	.cb_barrier	= srcu_torture_barrier,
1013 	.stats		= srcu_torture_stats,
1014 	.irq_capable	= 1,
1015 	.no_pi_lock	= IS_ENABLED(CONFIG_TINY_SRCU),
1016 	.extendables	= RCUTORTURE_MAX_EXTEND,
1017 	.name		= "busted_srcud"
1018 };
1019 
1020 /*
1021  * Definitions for trivial CONFIG_PREEMPT=n-only torture testing.
1022  * This implementation does not work well with CPU hotplug nor
1023  * with rcutorture's shuffling.
1024  */
1025 
1026 static void synchronize_rcu_trivial(void)
1027 {
1028 	int cpu;
1029 
1030 	for_each_online_cpu(cpu) {
1031 		torture_sched_setaffinity(current->pid, cpumask_of(cpu), true);
1032 		WARN_ON_ONCE(raw_smp_processor_id() != cpu);
1033 	}
1034 }
1035 
1036 static void rcu_sync_torture_init_trivial(void)
1037 {
1038 	rcu_sync_torture_init();
1039 	// if (onoff_interval || shuffle_interval) {
1040 	if (WARN_ONCE(onoff_interval || shuffle_interval, "%s: Non-zero onoff_interval (%d) or shuffle_interval (%d) breaks trivial RCU, resetting to zero", __func__, onoff_interval, shuffle_interval)) {
1041 		onoff_interval = 0;
1042 		shuffle_interval = 0;
1043 	}
1044 }
1045 
1046 static int rcu_torture_read_lock_trivial(void)
1047 {
1048 	preempt_disable();
1049 	return 0;
1050 }
1051 
1052 static void rcu_torture_read_unlock_trivial(int idx)
1053 {
1054 	preempt_enable();
1055 }
1056 
1057 static struct rcu_torture_ops trivial_ops = {
1058 	.ttype		= RCU_TRIVIAL_FLAVOR,
1059 	.init		= rcu_sync_torture_init_trivial,
1060 	.readlock	= rcu_torture_read_lock_trivial,
1061 	.read_delay	= rcu_read_delay,  /* just reuse rcu's version. */
1062 	.readunlock	= rcu_torture_read_unlock_trivial,
1063 	.readlock_held	= torture_readlock_not_held,
1064 	.get_gp_seq	= rcu_no_completed,
1065 	.sync		= synchronize_rcu_trivial,
1066 	.exp_sync	= synchronize_rcu_trivial,
1067 	.irq_capable	= 1,
1068 	.name		= "trivial"
1069 };
1070 
1071 #ifdef CONFIG_TRIVIAL_PREEMPT_RCU
1072 
1073 /*
1074  * Definitions for trivial CONFIG_PREEMPT=y torture testing.  This
1075  * implementation does not work well with large numbers of tasks or with
1076  * long-term preemption.  Either or both get you RCU CPU stall warnings.
1077  */
1078 
1079 static void rcu_sync_torture_init_trivial_preempt(void)
1080 {
1081 	rcu_sync_torture_init();
1082 	if (WARN_ONCE(onoff_interval || shuffle_interval, "%s: Non-zero onoff_interval (%d) or shuffle_interval (%d) breaks trivial RCU, resetting to zero", __func__, onoff_interval, shuffle_interval)) {
1083 		onoff_interval = 0;
1084 		shuffle_interval = 0;
1085 	}
1086 }
1087 
1088 static int rcu_torture_read_lock_trivial_preempt(void)
1089 {
1090 	struct task_struct *t = current;
1091 
1092 	WRITE_ONCE(t->rcu_trivial_preempt_nesting, t->rcu_trivial_preempt_nesting + 1);
1093 	smp_mb();
1094 	return 0;
1095 }
1096 
1097 static void rcu_torture_read_unlock_trivial_preempt(int idx)
1098 {
1099 	struct task_struct *t = current;
1100 
1101 	smp_store_release(&t->rcu_trivial_preempt_nesting, t->rcu_trivial_preempt_nesting - 1);
1102 }
1103 
1104 static struct rcu_torture_ops trivial_preempt_ops = {
1105 	.ttype		= RCU_TRIVIAL_FLAVOR,
1106 	.init		= rcu_sync_torture_init_trivial_preempt,
1107 	.readlock	= rcu_torture_read_lock_trivial_preempt,
1108 	.read_delay	= rcu_read_delay,  // just reuse rcu's version.
1109 	.readunlock	= rcu_torture_read_unlock_trivial_preempt,
1110 	.readlock_held	= torture_readlock_not_held,
1111 	.get_gp_seq	= rcu_no_completed,
1112 	.sync		= synchronize_rcu_trivial_preempt,
1113 	.exp_sync	= synchronize_rcu_trivial_preempt,
1114 	.irq_capable	= 0, // In theory it should be, but let's keep it trivial.
1115 	.name		= "trivial-preempt"
1116 };
1117 
1118 #define TRIVIAL_PREEMPT_OPS &trivial_preempt_ops,
1119 
1120 #else // #ifdef CONFIG_TRIVIAL_PREEMPT_RCU
1121 
1122 #define TRIVIAL_PREEMPT_OPS
1123 
1124 #endif // #else // #ifdef CONFIG_TRIVIAL_PREEMPT_RCU
1125 
1126 #ifdef CONFIG_TASKS_RCU
1127 
1128 /*
1129  * Definitions for RCU-tasks torture testing.
1130  */
1131 
1132 static int tasks_torture_read_lock(void)
1133 {
1134 	return 0;
1135 }
1136 
1137 static void tasks_torture_read_unlock(int idx)
1138 {
1139 }
1140 
1141 static void rcu_tasks_torture_deferred_free(struct rcu_torture *p)
1142 {
1143 	call_rcu_tasks(&p->rtort_rcu, rcu_torture_cb);
1144 }
1145 
1146 static void synchronize_rcu_mult_test(void)
1147 {
1148 	synchronize_rcu_mult(call_rcu_tasks, call_rcu);
1149 }
1150 
1151 static struct rcu_torture_ops tasks_ops = {
1152 	.ttype		= RCU_TASKS_FLAVOR,
1153 	.init		= rcu_sync_torture_init,
1154 	.readlock	= tasks_torture_read_lock,
1155 	.read_delay	= rcu_read_delay,  /* just reuse rcu's version. */
1156 	.readunlock	= tasks_torture_read_unlock,
1157 	.get_gp_seq	= rcu_no_completed,
1158 	.deferred_free	= rcu_tasks_torture_deferred_free,
1159 	.sync		= synchronize_rcu_tasks,
1160 	.exp_sync	= synchronize_rcu_mult_test,
1161 	.call		= call_rcu_tasks,
1162 	.cb_barrier	= rcu_barrier_tasks,
1163 	.gp_kthread_dbg	= show_rcu_tasks_classic_gp_kthread,
1164 	.get_gp_data	= rcu_tasks_get_gp_data,
1165 	.irq_capable	= 1,
1166 	.slow_gps	= 1,
1167 	.name		= "tasks"
1168 };
1169 
1170 #define TASKS_OPS &tasks_ops,
1171 
1172 #else // #ifdef CONFIG_TASKS_RCU
1173 
1174 #define TASKS_OPS
1175 
1176 #endif // #else #ifdef CONFIG_TASKS_RCU
1177 
1178 
1179 #ifdef CONFIG_TASKS_RUDE_RCU
1180 
1181 /*
1182  * Definitions for rude RCU-tasks torture testing.
1183  */
1184 
1185 static struct rcu_torture_ops tasks_rude_ops = {
1186 	.ttype		= RCU_TASKS_RUDE_FLAVOR,
1187 	.init		= rcu_sync_torture_init,
1188 	.readlock	= rcu_torture_read_lock_trivial,
1189 	.read_delay	= rcu_read_delay,  /* just reuse rcu's version. */
1190 	.readunlock	= rcu_torture_read_unlock_trivial,
1191 	.get_gp_seq	= rcu_no_completed,
1192 	.sync		= synchronize_rcu_tasks_rude,
1193 	.exp_sync	= synchronize_rcu_tasks_rude,
1194 	.gp_kthread_dbg	= show_rcu_tasks_rude_gp_kthread,
1195 	.get_gp_data	= rcu_tasks_rude_get_gp_data,
1196 	.cbflood_max	= 50000,
1197 	.irq_capable	= 1,
1198 	.name		= "tasks-rude"
1199 };
1200 
1201 #define TASKS_RUDE_OPS &tasks_rude_ops,
1202 
1203 #else // #ifdef CONFIG_TASKS_RUDE_RCU
1204 
1205 #define TASKS_RUDE_OPS
1206 
1207 #endif // #else #ifdef CONFIG_TASKS_RUDE_RCU
1208 
1209 
1210 #ifdef CONFIG_TASKS_TRACE_RCU
1211 
1212 /*
1213  * Definitions for tracing RCU-tasks torture testing.
1214  */
1215 
1216 static int tasks_tracing_torture_read_lock(void)
1217 {
1218 	rcu_read_lock_trace();
1219 	return 0;
1220 }
1221 
1222 static void tasks_tracing_torture_read_unlock(int idx)
1223 {
1224 	rcu_read_unlock_trace();
1225 }
1226 
1227 static void rcu_tasks_tracing_torture_deferred_free(struct rcu_torture *p)
1228 {
1229 	call_rcu_tasks_trace(&p->rtort_rcu, rcu_torture_cb);
1230 }
1231 
1232 static struct rcu_torture_ops tasks_tracing_ops = {
1233 	.ttype		= RCU_TASKS_TRACING_FLAVOR,
1234 	.init		= rcu_sync_torture_init,
1235 	.readlock	= tasks_tracing_torture_read_lock,
1236 	.read_delay	= srcu_read_delay,  /* just reuse srcu's version. */
1237 	.readunlock	= tasks_tracing_torture_read_unlock,
1238 	.readlock_held	= rcu_read_lock_trace_held,
1239 	.get_gp_seq	= rcu_no_completed,
1240 	.deferred_free	= rcu_tasks_tracing_torture_deferred_free,
1241 	.sync		= synchronize_rcu_tasks_trace,
1242 	.exp_sync	= synchronize_rcu_tasks_trace,
1243 	.exp_current	= rcu_tasks_trace_expedite_current,
1244 	.call		= call_rcu_tasks_trace,
1245 	.cb_barrier	= rcu_barrier_tasks_trace,
1246 	.cbflood_max	= 50000,
1247 	.irq_capable	= 1,
1248 	.slow_gps	= 1,
1249 	.name		= "tasks-tracing"
1250 };
1251 
1252 #define TASKS_TRACING_OPS &tasks_tracing_ops,
1253 
1254 #else // #ifdef CONFIG_TASKS_TRACE_RCU
1255 
1256 #define TASKS_TRACING_OPS
1257 
1258 #endif // #else #ifdef CONFIG_TASKS_TRACE_RCU
1259 
1260 
1261 static unsigned long rcutorture_seq_diff(unsigned long new, unsigned long old)
1262 {
1263 	if (!cur_ops->gp_diff)
1264 		return new - old;
1265 	return cur_ops->gp_diff(new, old);
1266 }
1267 
1268 /*
1269  * RCU torture priority-boost testing.  Runs one real-time thread per
1270  * CPU for moderate bursts, repeatedly starting grace periods and waiting
1271  * for them to complete.  If a given grace period takes too long, we assume
1272  * that priority inversion has occurred.
1273  */
1274 
1275 static int old_rt_runtime = -1;
1276 
1277 static void rcu_torture_disable_rt_throttle(void)
1278 {
1279 	/*
1280 	 * Disable RT throttling so that rcutorture's boost threads don't get
1281 	 * throttled. Only possible if rcutorture is built-in otherwise the
1282 	 * user should manually do this by setting the sched_rt_period_us and
1283 	 * sched_rt_runtime sysctls.
1284 	 */
1285 	if (!IS_BUILTIN(CONFIG_RCU_TORTURE_TEST) || old_rt_runtime != -1)
1286 		return;
1287 
1288 	old_rt_runtime = sysctl_sched_rt_runtime;
1289 	sysctl_sched_rt_runtime = -1;
1290 }
1291 
1292 static void rcu_torture_enable_rt_throttle(void)
1293 {
1294 	if (!IS_BUILTIN(CONFIG_RCU_TORTURE_TEST) || old_rt_runtime == -1)
1295 		return;
1296 
1297 	sysctl_sched_rt_runtime = old_rt_runtime;
1298 	old_rt_runtime = -1;
1299 }
1300 
1301 static bool rcu_torture_boost_failed(unsigned long gp_state, unsigned long *start)
1302 {
1303 	int cpu;
1304 	static int dbg_done;
1305 	unsigned long end = jiffies;
1306 	bool gp_done;
1307 	unsigned long j;
1308 	static unsigned long last_persist;
1309 	unsigned long lp;
1310 	unsigned long mininterval = test_boost_duration * HZ - HZ / 2;
1311 
1312 	if (end - *start > mininterval) {
1313 		// Recheck after checking time to avoid false positives.
1314 		smp_mb(); // Time check before grace-period check.
1315 		if (cur_ops->poll_gp_state(gp_state))
1316 			return false; // passed, though perhaps just barely
1317 		if (cur_ops->check_boost_failed && !cur_ops->check_boost_failed(gp_state, &cpu)) {
1318 			// At most one persisted message per boost test.
1319 			j = jiffies;
1320 			lp = READ_ONCE(last_persist);
1321 			if (time_after(j, lp + mininterval) &&
1322 			    cmpxchg(&last_persist, lp, j) == lp) {
1323 				if (cpu < 0)
1324 					pr_info("Boost inversion persisted: QS from all CPUs\n");
1325 				else
1326 					pr_info("Boost inversion persisted: No QS from CPU %d\n", cpu);
1327 			}
1328 			return false; // passed on a technicality
1329 		}
1330 		VERBOSE_TOROUT_STRING("rcu_torture_boost boosting failed");
1331 		n_rcu_torture_boost_failure++;
1332 		if (!xchg(&dbg_done, 1) && cur_ops->gp_kthread_dbg) {
1333 			pr_info("Boost inversion thread ->rt_priority %u gp_state %lu jiffies %lu\n",
1334 				current->rt_priority, gp_state, end - *start);
1335 			cur_ops->gp_kthread_dbg();
1336 			// Recheck after print to flag grace period ending during splat.
1337 			gp_done = cur_ops->poll_gp_state(gp_state);
1338 			pr_info("Boost inversion: GP %lu %s.\n", gp_state,
1339 				gp_done ? "ended already" : "still pending");
1340 
1341 		}
1342 
1343 		return true; // failed
1344 	} else if (cur_ops->check_boost_failed && !cur_ops->check_boost_failed(gp_state, NULL)) {
1345 		*start = jiffies;
1346 	}
1347 
1348 	return false; // passed
1349 }
1350 
1351 static int rcu_torture_boost(void *arg)
1352 {
1353 	unsigned long endtime;
1354 	unsigned long gp_state;
1355 	unsigned long gp_state_time;
1356 	unsigned long oldstarttime;
1357 	unsigned long booststarttime = get_torture_init_jiffies() + test_boost_holdoff * HZ;
1358 
1359 	if (test_boost_holdoff <= 0 || time_after(jiffies, booststarttime)) {
1360 		VERBOSE_TOROUT_STRING("rcu_torture_boost started");
1361 	} else {
1362 		VERBOSE_TOROUT_STRING("rcu_torture_boost started holdoff period");
1363 		while (time_before(jiffies, booststarttime)) {
1364 			schedule_timeout_idle(HZ);
1365 			if (kthread_should_stop())
1366 				goto cleanup;
1367 		}
1368 		VERBOSE_TOROUT_STRING("rcu_torture_boost finished holdoff period");
1369 	}
1370 
1371 	/* Set real-time priority. */
1372 	sched_set_fifo_low(current);
1373 
1374 	/* Each pass through the following loop does one boost-test cycle. */
1375 	do {
1376 		bool failed = false; // Test failed already in this test interval
1377 		bool gp_initiated = false;
1378 
1379 		if (kthread_should_stop())
1380 			goto checkwait;
1381 
1382 		/* Wait for the next test interval. */
1383 		oldstarttime = READ_ONCE(boost_starttime);
1384 		while (time_before(jiffies, oldstarttime)) {
1385 			schedule_timeout_interruptible(oldstarttime - jiffies);
1386 			if (stutter_wait("rcu_torture_boost"))
1387 				sched_set_fifo_low(current);
1388 			if (torture_must_stop())
1389 				goto checkwait;
1390 		}
1391 
1392 		// Do one boost-test interval.
1393 		endtime = oldstarttime + test_boost_duration * HZ;
1394 		while (time_before(jiffies, endtime)) {
1395 			// Has current GP gone too long?
1396 			if (gp_initiated && !failed && !cur_ops->poll_gp_state(gp_state))
1397 				failed = rcu_torture_boost_failed(gp_state, &gp_state_time);
1398 			// If we don't have a grace period in flight, start one.
1399 			if (!gp_initiated || cur_ops->poll_gp_state(gp_state)) {
1400 				gp_state = cur_ops->start_gp_poll();
1401 				gp_initiated = true;
1402 				gp_state_time = jiffies;
1403 			}
1404 			if (stutter_wait("rcu_torture_boost")) {
1405 				sched_set_fifo_low(current);
1406 				// If the grace period already ended,
1407 				// we don't know when that happened, so
1408 				// start over.
1409 				if (cur_ops->poll_gp_state(gp_state))
1410 					gp_initiated = false;
1411 			}
1412 			if (torture_must_stop())
1413 				goto checkwait;
1414 		}
1415 
1416 		// In case the grace period extended beyond the end of the loop.
1417 		if (gp_initiated && !failed && !cur_ops->poll_gp_state(gp_state))
1418 			rcu_torture_boost_failed(gp_state, &gp_state_time);
1419 
1420 		/*
1421 		 * Set the start time of the next test interval.
1422 		 * Yes, this is vulnerable to long delays, but such
1423 		 * delays simply cause a false negative for the next
1424 		 * interval.  Besides, we are running at RT priority,
1425 		 * so delays should be relatively rare.
1426 		 */
1427 		while (oldstarttime == READ_ONCE(boost_starttime) && !kthread_should_stop()) {
1428 			if (mutex_trylock(&boost_mutex)) {
1429 				if (oldstarttime == boost_starttime) {
1430 					WRITE_ONCE(boost_starttime,
1431 						   jiffies + test_boost_interval * HZ);
1432 					n_rcu_torture_boosts++;
1433 				}
1434 				mutex_unlock(&boost_mutex);
1435 				break;
1436 			}
1437 			schedule_timeout_uninterruptible(HZ / 20);
1438 		}
1439 
1440 		/* Go do the stutter. */
1441 checkwait:	if (stutter_wait("rcu_torture_boost"))
1442 			sched_set_fifo_low(current);
1443 	} while (!torture_must_stop());
1444 
1445 cleanup:
1446 	/* Clean up and exit. */
1447 	while (!kthread_should_stop()) {
1448 		torture_shutdown_absorb("rcu_torture_boost");
1449 		schedule_timeout_uninterruptible(HZ / 20);
1450 	}
1451 	torture_kthread_stopping("rcu_torture_boost");
1452 	return 0;
1453 }
1454 
1455 /*
1456  * RCU torture force-quiescent-state kthread.  Repeatedly induces
1457  * bursts of calls to force_quiescent_state(), increasing the probability
1458  * of occurrence of some important types of race conditions.
1459  */
1460 static int
1461 rcu_torture_fqs(void *arg)
1462 {
1463 	unsigned long fqs_resume_time;
1464 	int fqs_burst_remaining;
1465 	int oldnice = task_nice(current);
1466 
1467 	VERBOSE_TOROUT_STRING("rcu_torture_fqs task started");
1468 	do {
1469 		fqs_resume_time = jiffies + fqs_stutter * HZ;
1470 		while (time_before(jiffies, fqs_resume_time) &&
1471 		       !kthread_should_stop()) {
1472 			schedule_timeout_interruptible(HZ / 20);
1473 		}
1474 		fqs_burst_remaining = fqs_duration;
1475 		while (fqs_burst_remaining > 0 &&
1476 		       !kthread_should_stop()) {
1477 			cur_ops->fqs();
1478 			udelay(fqs_holdoff);
1479 			fqs_burst_remaining -= fqs_holdoff;
1480 		}
1481 		if (stutter_wait("rcu_torture_fqs"))
1482 			sched_set_normal(current, oldnice);
1483 	} while (!torture_must_stop());
1484 	torture_kthread_stopping("rcu_torture_fqs");
1485 	return 0;
1486 }
1487 
1488 // Used by writers to randomly choose from the available grace-period primitives.
1489 static int synctype[ARRAY_SIZE(rcu_torture_writer_state_names)] = { };
1490 static int nsynctypes;
1491 
1492 /*
1493  * Determine which grace-period primitives are available.
1494  */
1495 static void rcu_torture_write_types(void)
1496 {
1497 	bool gp_cond1 = gp_cond, gp_cond_exp1 = gp_cond_exp, gp_cond_full1 = gp_cond_full;
1498 	bool gp_cond_exp_full1 = gp_cond_exp_full, gp_exp1 = gp_exp, gp_poll_exp1 = gp_poll_exp;
1499 	bool gp_poll_exp_full1 = gp_poll_exp_full, gp_normal1 = gp_normal, gp_poll1 = gp_poll;
1500 	bool gp_poll_full1 = gp_poll_full, gp_sync1 = gp_sync;
1501 
1502 	/* Initialize synctype[] array.  If none set, take default. */
1503 	if (!gp_cond1 &&
1504 	    !gp_cond_exp1 &&
1505 	    !gp_cond_full1 &&
1506 	    !gp_cond_exp_full1 &&
1507 	    !gp_exp1 &&
1508 	    !gp_poll_exp1 &&
1509 	    !gp_poll_exp_full1 &&
1510 	    !gp_normal1 &&
1511 	    !gp_poll1 &&
1512 	    !gp_poll_full1 &&
1513 	    !gp_sync1) {
1514 		gp_cond1 = true;
1515 		gp_cond_exp1 = true;
1516 		gp_cond_full1 = true;
1517 		gp_cond_exp_full1 = true;
1518 		gp_exp1 = true;
1519 		gp_poll_exp1 = true;
1520 		gp_poll_exp_full1 = true;
1521 		gp_normal1 = true;
1522 		gp_poll1 = true;
1523 		gp_poll_full1 = true;
1524 		gp_sync1 = true;
1525 	}
1526 	if (gp_cond1 && cur_ops->get_gp_state && cur_ops->cond_sync) {
1527 		synctype[nsynctypes++] = RTWS_COND_GET;
1528 		pr_info("%s: Testing conditional GPs.\n", __func__);
1529 	} else if (gp_cond && (!cur_ops->get_gp_state || !cur_ops->cond_sync)) {
1530 		pr_alert("%s: gp_cond without primitives.\n", __func__);
1531 	}
1532 	if (gp_cond_exp1 && cur_ops->get_gp_state_exp && cur_ops->cond_sync_exp) {
1533 		synctype[nsynctypes++] = RTWS_COND_GET_EXP;
1534 		pr_info("%s: Testing conditional expedited GPs.\n", __func__);
1535 	} else if (gp_cond_exp && (!cur_ops->get_gp_state_exp || !cur_ops->cond_sync_exp)) {
1536 		pr_alert("%s: gp_cond_exp without primitives.\n", __func__);
1537 	}
1538 	if (gp_cond_full1 && cur_ops->get_gp_state && cur_ops->cond_sync_full) {
1539 		synctype[nsynctypes++] = RTWS_COND_GET_FULL;
1540 		pr_info("%s: Testing conditional full-state GPs.\n", __func__);
1541 	} else if (gp_cond_full && (!cur_ops->get_gp_state || !cur_ops->cond_sync_full)) {
1542 		pr_alert("%s: gp_cond_full without primitives.\n", __func__);
1543 	}
1544 	if (gp_cond_exp_full1 && cur_ops->get_gp_state_exp && cur_ops->cond_sync_exp_full) {
1545 		synctype[nsynctypes++] = RTWS_COND_GET_EXP_FULL;
1546 		pr_info("%s: Testing conditional full-state expedited GPs.\n", __func__);
1547 	} else if (gp_cond_exp_full &&
1548 		   (!cur_ops->get_gp_state_exp || !cur_ops->cond_sync_exp_full)) {
1549 		pr_alert("%s: gp_cond_exp_full without primitives.\n", __func__);
1550 	}
1551 	if (gp_exp1 && cur_ops->exp_sync) {
1552 		synctype[nsynctypes++] = RTWS_EXP_SYNC;
1553 		pr_info("%s: Testing expedited GPs.\n", __func__);
1554 	} else if (gp_exp && !cur_ops->exp_sync) {
1555 		pr_alert("%s: gp_exp without primitives.\n", __func__);
1556 	}
1557 	if (gp_normal1 && cur_ops->deferred_free) {
1558 		synctype[nsynctypes++] = RTWS_DEF_FREE;
1559 		pr_info("%s: Testing asynchronous GPs.\n", __func__);
1560 	} else if (gp_normal && !cur_ops->deferred_free) {
1561 		pr_alert("%s: gp_normal without primitives.\n", __func__);
1562 	}
1563 	if (gp_poll1 && cur_ops->get_comp_state && cur_ops->same_gp_state &&
1564 	    cur_ops->start_gp_poll && cur_ops->poll_gp_state) {
1565 		synctype[nsynctypes++] = RTWS_POLL_GET;
1566 		pr_info("%s: Testing polling GPs.\n", __func__);
1567 	} else if (gp_poll && (!cur_ops->start_gp_poll || !cur_ops->poll_gp_state)) {
1568 		pr_alert("%s: gp_poll without primitives.\n", __func__);
1569 	}
1570 	if (gp_poll_full1 && cur_ops->get_comp_state_full && cur_ops->same_gp_state_full
1571 	    && cur_ops->start_gp_poll_full && cur_ops->poll_gp_state_full) {
1572 		synctype[nsynctypes++] = RTWS_POLL_GET_FULL;
1573 		pr_info("%s: Testing polling full-state GPs.\n", __func__);
1574 	} else if (gp_poll_full && (!cur_ops->start_gp_poll_full || !cur_ops->poll_gp_state_full)) {
1575 		pr_alert("%s: gp_poll_full without primitives.\n", __func__);
1576 	}
1577 	if (gp_poll_exp1 && cur_ops->start_gp_poll_exp && cur_ops->poll_gp_state_exp) {
1578 		synctype[nsynctypes++] = RTWS_POLL_GET_EXP;
1579 		pr_info("%s: Testing polling expedited GPs.\n", __func__);
1580 	} else if (gp_poll_exp && (!cur_ops->start_gp_poll_exp || !cur_ops->poll_gp_state_exp)) {
1581 		pr_alert("%s: gp_poll_exp without primitives.\n", __func__);
1582 	}
1583 	if (gp_poll_exp_full1 && cur_ops->start_gp_poll_exp_full && cur_ops->poll_gp_state_full) {
1584 		synctype[nsynctypes++] = RTWS_POLL_GET_EXP_FULL;
1585 		pr_info("%s: Testing polling full-state expedited GPs.\n", __func__);
1586 	} else if (gp_poll_exp_full &&
1587 		   (!cur_ops->start_gp_poll_exp_full || !cur_ops->poll_gp_state_full)) {
1588 		pr_alert("%s: gp_poll_exp_full without primitives.\n", __func__);
1589 	}
1590 	if (gp_sync1 && cur_ops->sync) {
1591 		synctype[nsynctypes++] = RTWS_SYNC;
1592 		pr_info("%s: Testing normal GPs.\n", __func__);
1593 	} else if (gp_sync && !cur_ops->sync) {
1594 		pr_alert("%s: gp_sync without primitives.\n", __func__);
1595 	}
1596 	pr_alert("%s: Testing %d update types.\n", __func__, nsynctypes);
1597 	pr_info("%s: gp_cond_wi %d gp_cond_wi_exp %d gp_poll_wi %d gp_poll_wi_exp %d\n", __func__, gp_cond_wi, gp_cond_wi_exp, gp_poll_wi, gp_poll_wi_exp);
1598 }
1599 
1600 /*
1601  * Do the specified rcu_torture_writer() synchronous grace period,
1602  * while also testing out the polled APIs.  Note well that the single-CPU
1603  * grace-period optimizations must be accounted for.
1604  */
1605 static void do_rtws_sync(struct torture_random_state *trsp, void (*sync)(void))
1606 {
1607 	unsigned long cookie;
1608 	struct rcu_gp_oldstate cookie_full;
1609 	bool dopoll;
1610 	bool dopoll_full;
1611 	unsigned long r = torture_random(trsp);
1612 
1613 	dopoll = cur_ops->get_gp_state && cur_ops->poll_gp_state && !(r & 0x300);
1614 	dopoll_full = cur_ops->get_gp_state_full && cur_ops->poll_gp_state_full && !(r & 0xc00);
1615 	if (dopoll || dopoll_full)
1616 		cpus_read_lock();
1617 	if (dopoll)
1618 		cookie = cur_ops->get_gp_state();
1619 	if (dopoll_full)
1620 		cur_ops->get_gp_state_full(&cookie_full);
1621 	if (cur_ops->poll_need_2gp && cur_ops->poll_need_2gp(dopoll, dopoll_full))
1622 		sync();
1623 	sync();
1624 	WARN_ONCE(dopoll && !cur_ops->poll_gp_state(cookie),
1625 		  "%s: Cookie check 3 failed %pS() online %*pbl.",
1626 		  __func__, sync, cpumask_pr_args(cpu_online_mask));
1627 	WARN_ONCE(dopoll_full && !cur_ops->poll_gp_state_full(&cookie_full),
1628 		  "%s: Cookie check 4 failed %pS() online %*pbl",
1629 		  __func__, sync, cpumask_pr_args(cpu_online_mask));
1630 	if (dopoll || dopoll_full)
1631 		cpus_read_unlock();
1632 }
1633 
1634 /*
1635  * Do an rcu_barrier() to motivate lazy callbacks during a stutter
1636  * pause.  Without this, we can get false-positives rtort_pipe_count
1637  * splats.
1638  */
1639 static void rcu_torture_writer_work(struct work_struct *work)
1640 {
1641 	if (cur_ops->cb_barrier)
1642 		cur_ops->cb_barrier();
1643 }
1644 
1645 /*
1646  * RCU torture writer kthread.  Repeatedly substitutes a new structure
1647  * for that pointed to by rcu_torture_current, freeing the old structure
1648  * after a series of grace periods (the "pipeline").
1649  */
1650 static int
1651 rcu_torture_writer(void *arg)
1652 {
1653 	bool booting_still = false;
1654 	bool can_expedite = !rcu_gp_is_expedited() && !rcu_gp_is_normal();
1655 	unsigned long cookie;
1656 	struct rcu_gp_oldstate cookie_full;
1657 	int expediting = 0;
1658 	unsigned long gp_snap;
1659 	unsigned long gp_snap1;
1660 	struct rcu_gp_oldstate gp_snap_full;
1661 	struct rcu_gp_oldstate gp_snap1_full;
1662 	int i;
1663 	int idx;
1664 	unsigned long j;
1665 	struct work_struct lazy_work;
1666 	int oldnice = task_nice(current);
1667 	struct rcu_gp_oldstate *rgo = NULL;
1668 	int rgo_size = 0;
1669 	struct rcu_torture *rp;
1670 	struct rcu_torture *old_rp;
1671 	static DEFINE_TORTURE_RANDOM(rand);
1672 	unsigned long stallsdone = jiffies;
1673 	bool stutter_waited;
1674 	unsigned long *ulo = NULL;
1675 	int ulo_size = 0;
1676 
1677 	// If a new stall test is added, this must be adjusted.
1678 	if (stall_cpu_holdoff + stall_gp_kthread + stall_cpu)
1679 		stallsdone += (stall_cpu_holdoff + stall_gp_kthread + stall_cpu + 60) *
1680 			      HZ * (stall_cpu_repeat + 1);
1681 	VERBOSE_TOROUT_STRING("rcu_torture_writer task started");
1682 	if (!can_expedite)
1683 		pr_alert("%s" TORTURE_FLAG
1684 			 " GP expediting controlled from boot/sysfs for %s.\n",
1685 			 torture_type, cur_ops->name);
1686 	if (WARN_ONCE(nsynctypes == 0,
1687 		      "%s: No update-side primitives.\n", __func__)) {
1688 		/*
1689 		 * No updates primitives, so don't try updating.
1690 		 * The resulting test won't be testing much, hence the
1691 		 * above WARN_ONCE().
1692 		 */
1693 		rcu_torture_writer_state = RTWS_STOPPING;
1694 		torture_kthread_stopping("rcu_torture_writer");
1695 		return 0;
1696 	}
1697 	if (cur_ops->poll_active > 0) {
1698 		ulo = kcalloc(cur_ops->poll_active, sizeof(*ulo), GFP_KERNEL);
1699 		if (!WARN_ON(!ulo))
1700 			ulo_size = cur_ops->poll_active;
1701 	}
1702 	if (cur_ops->poll_active_full > 0) {
1703 		rgo = kzalloc_objs(*rgo, cur_ops->poll_active_full);
1704 		if (!WARN_ON(!rgo))
1705 			rgo_size = cur_ops->poll_active_full;
1706 	}
1707 
1708 	// If the system is still booting, let it finish.
1709 	j = jiffies;
1710 	while (!torture_must_stop() && !rcu_inkernel_boot_has_ended()) {
1711 		booting_still = true;
1712 		schedule_timeout_interruptible(HZ);
1713 	}
1714 	if (booting_still)
1715 		pr_alert("%s" TORTURE_FLAG " Waited %lu jiffies for boot to complete.\n",
1716 			 torture_type, jiffies - j);
1717 
1718 	if (IS_ENABLED(CONFIG_RCU_LAZY))
1719 		INIT_WORK_ONSTACK(&lazy_work, rcu_torture_writer_work);
1720 
1721 	do {
1722 		rcu_torture_writer_state = RTWS_FIXED_DELAY;
1723 		torture_hrtimeout_us(500, 1000, &rand);
1724 		rp = rcu_torture_alloc();
1725 		if (rp == NULL)
1726 			continue;
1727 		rp->rtort_pipe_count = 0;
1728 		ASSERT_EXCLUSIVE_WRITER(rp->rtort_pipe_count);
1729 		rcu_torture_writer_state = RTWS_DELAY;
1730 		udelay(torture_random(&rand) & 0x3ff);
1731 		rcu_torture_writer_state = RTWS_REPLACE;
1732 		old_rp = rcu_dereference_check(rcu_torture_current,
1733 					       current == writer_task);
1734 		rp->rtort_mbtest = 1;
1735 		rcu_assign_pointer(rcu_torture_current, rp);
1736 		smp_wmb(); /* Mods to old_rp must follow rcu_assign_pointer() */
1737 		if (old_rp) {
1738 			i = old_rp->rtort_pipe_count;
1739 			if (i > RCU_TORTURE_PIPE_LEN)
1740 				i = RCU_TORTURE_PIPE_LEN;
1741 			atomic_inc(&rcu_torture_wcount[i]);
1742 			WRITE_ONCE(old_rp->rtort_pipe_count,
1743 				   old_rp->rtort_pipe_count + 1);
1744 			ASSERT_EXCLUSIVE_WRITER(old_rp->rtort_pipe_count);
1745 
1746 			// Make sure readers block polled grace periods.
1747 			if (cur_ops->get_gp_state && cur_ops->poll_gp_state) {
1748 				idx = cur_ops->readlock();
1749 				cookie = cur_ops->get_gp_state();
1750 				WARN_ONCE(cur_ops->poll_gp_state(cookie),
1751 					  "%s: Cookie check 1 failed %s(%d) %lu->%lu\n",
1752 					  __func__,
1753 					  rcu_torture_writer_state_getname(),
1754 					  rcu_torture_writer_state,
1755 					  cookie, cur_ops->get_gp_state());
1756 				if (cur_ops->get_comp_state) {
1757 					cookie = cur_ops->get_comp_state();
1758 					WARN_ON_ONCE(!cur_ops->poll_gp_state(cookie));
1759 				}
1760 				cur_ops->readunlock(idx);
1761 			}
1762 			if (cur_ops->get_gp_state_full && cur_ops->poll_gp_state_full) {
1763 				idx = cur_ops->readlock();
1764 				cur_ops->get_gp_state_full(&cookie_full);
1765 				WARN_ONCE(cur_ops->poll_gp_state_full(&cookie_full),
1766 					  "%s: Cookie check 5 failed %s(%d) online %*pbl\n",
1767 					  __func__,
1768 					  rcu_torture_writer_state_getname(),
1769 					  rcu_torture_writer_state,
1770 					  cpumask_pr_args(cpu_online_mask));
1771 				if (cur_ops->get_comp_state_full) {
1772 					cur_ops->get_comp_state_full(&cookie_full);
1773 					WARN_ON_ONCE(!cur_ops->poll_gp_state_full(&cookie_full));
1774 				}
1775 				cur_ops->readunlock(idx);
1776 			}
1777 			switch (synctype[torture_random(&rand) % nsynctypes]) {
1778 			case RTWS_DEF_FREE:
1779 				rcu_torture_writer_state = RTWS_DEF_FREE;
1780 				cur_ops->deferred_free(old_rp);
1781 				break;
1782 			case RTWS_EXP_SYNC:
1783 				rcu_torture_writer_state = RTWS_EXP_SYNC;
1784 				do_rtws_sync(&rand, cur_ops->exp_sync);
1785 				rcu_torture_pipe_update(old_rp);
1786 				break;
1787 			case RTWS_COND_GET:
1788 				rcu_torture_writer_state = RTWS_COND_GET;
1789 				gp_snap = cur_ops->get_gp_state();
1790 				torture_hrtimeout_us(torture_random(&rand) % gp_cond_wi,
1791 						     1000, &rand);
1792 				rcu_torture_writer_state = RTWS_COND_SYNC;
1793 				cur_ops->cond_sync(gp_snap);
1794 				rcu_torture_pipe_update(old_rp);
1795 				break;
1796 			case RTWS_COND_GET_EXP:
1797 				rcu_torture_writer_state = RTWS_COND_GET_EXP;
1798 				gp_snap = cur_ops->get_gp_state_exp();
1799 				torture_hrtimeout_us(torture_random(&rand) % gp_cond_wi_exp,
1800 						     1000, &rand);
1801 				rcu_torture_writer_state = RTWS_COND_SYNC_EXP;
1802 				cur_ops->cond_sync_exp(gp_snap);
1803 				rcu_torture_pipe_update(old_rp);
1804 				break;
1805 			case RTWS_COND_GET_FULL:
1806 				rcu_torture_writer_state = RTWS_COND_GET_FULL;
1807 				cur_ops->get_gp_state_full(&gp_snap_full);
1808 				torture_hrtimeout_us(torture_random(&rand) % gp_cond_wi,
1809 						     1000, &rand);
1810 				rcu_torture_writer_state = RTWS_COND_SYNC_FULL;
1811 				cur_ops->cond_sync_full(&gp_snap_full);
1812 				rcu_torture_pipe_update(old_rp);
1813 				break;
1814 			case RTWS_COND_GET_EXP_FULL:
1815 				rcu_torture_writer_state = RTWS_COND_GET_EXP_FULL;
1816 				cur_ops->get_gp_state_full(&gp_snap_full);
1817 				torture_hrtimeout_us(torture_random(&rand) % gp_cond_wi_exp,
1818 						     1000, &rand);
1819 				rcu_torture_writer_state = RTWS_COND_SYNC_EXP_FULL;
1820 				cur_ops->cond_sync_exp_full(&gp_snap_full);
1821 				rcu_torture_pipe_update(old_rp);
1822 				break;
1823 			case RTWS_POLL_GET:
1824 				rcu_torture_writer_state = RTWS_POLL_GET;
1825 				for (i = 0; i < ulo_size; i++)
1826 					ulo[i] = cur_ops->get_comp_state();
1827 				gp_snap = cur_ops->start_gp_poll();
1828 				rcu_torture_writer_state = RTWS_POLL_WAIT;
1829 				if (cur_ops->exp_current && !(torture_random(&rand) & 0xff))
1830 					cur_ops->exp_current();
1831 				while (!cur_ops->poll_gp_state(gp_snap)) {
1832 					gp_snap1 = cur_ops->get_gp_state();
1833 					for (i = 0; i < ulo_size; i++)
1834 						if (cur_ops->poll_gp_state(ulo[i]) ||
1835 						    cur_ops->same_gp_state(ulo[i], gp_snap1)) {
1836 							ulo[i] = gp_snap1;
1837 							break;
1838 						}
1839 					WARN_ON_ONCE(ulo_size > 0 && i >= ulo_size);
1840 					torture_hrtimeout_us(torture_random(&rand) % gp_poll_wi,
1841 							     1000, &rand);
1842 				}
1843 				rcu_torture_pipe_update(old_rp);
1844 				break;
1845 			case RTWS_POLL_GET_FULL:
1846 				rcu_torture_writer_state = RTWS_POLL_GET_FULL;
1847 				for (i = 0; i < rgo_size; i++)
1848 					cur_ops->get_comp_state_full(&rgo[i]);
1849 				cur_ops->start_gp_poll_full(&gp_snap_full);
1850 				rcu_torture_writer_state = RTWS_POLL_WAIT_FULL;
1851 				if (cur_ops->exp_current && !(torture_random(&rand) & 0xff))
1852 					cur_ops->exp_current();
1853 				while (!cur_ops->poll_gp_state_full(&gp_snap_full)) {
1854 					cur_ops->get_gp_state_full(&gp_snap1_full);
1855 					for (i = 0; i < rgo_size; i++)
1856 						if (cur_ops->poll_gp_state_full(&rgo[i]) ||
1857 						    cur_ops->same_gp_state_full(&rgo[i],
1858 										&gp_snap1_full)) {
1859 							rgo[i] = gp_snap1_full;
1860 							break;
1861 						}
1862 					WARN_ON_ONCE(rgo_size > 0 && i >= rgo_size);
1863 					torture_hrtimeout_us(torture_random(&rand) % gp_poll_wi,
1864 							     1000, &rand);
1865 				}
1866 				rcu_torture_pipe_update(old_rp);
1867 				break;
1868 			case RTWS_POLL_GET_EXP:
1869 				rcu_torture_writer_state = RTWS_POLL_GET_EXP;
1870 				gp_snap = cur_ops->start_gp_poll_exp();
1871 				rcu_torture_writer_state = RTWS_POLL_WAIT_EXP;
1872 				while (!cur_ops->poll_gp_state_exp(gp_snap))
1873 					torture_hrtimeout_us(torture_random(&rand) % gp_poll_wi_exp,
1874 							     1000, &rand);
1875 				rcu_torture_pipe_update(old_rp);
1876 				break;
1877 			case RTWS_POLL_GET_EXP_FULL:
1878 				rcu_torture_writer_state = RTWS_POLL_GET_EXP_FULL;
1879 				cur_ops->start_gp_poll_exp_full(&gp_snap_full);
1880 				rcu_torture_writer_state = RTWS_POLL_WAIT_EXP_FULL;
1881 				while (!cur_ops->poll_gp_state_full(&gp_snap_full))
1882 					torture_hrtimeout_us(torture_random(&rand) % gp_poll_wi_exp,
1883 							     1000, &rand);
1884 				rcu_torture_pipe_update(old_rp);
1885 				break;
1886 			case RTWS_SYNC:
1887 				rcu_torture_writer_state = RTWS_SYNC;
1888 				do_rtws_sync(&rand, cur_ops->sync);
1889 				rcu_torture_pipe_update(old_rp);
1890 				break;
1891 			default:
1892 				WARN_ON_ONCE(1);
1893 				break;
1894 			}
1895 		}
1896 		WRITE_ONCE(rcu_torture_current_version,
1897 			   rcu_torture_current_version + 1);
1898 		/* Cycle through nesting levels of rcu_expedite_gp() calls. */
1899 		if (can_expedite &&
1900 		    !(torture_random(&rand) & 0xff & (!!expediting - 1))) {
1901 			WARN_ON_ONCE(expediting == 0 && rcu_gp_is_expedited());
1902 			if (expediting >= 0)
1903 				rcu_expedite_gp();
1904 			else
1905 				rcu_unexpedite_gp();
1906 			if (++expediting > 3)
1907 				expediting = -expediting;
1908 		} else if (!can_expedite) { /* Disabled during boot, recheck. */
1909 			can_expedite = !rcu_gp_is_expedited() &&
1910 				       !rcu_gp_is_normal();
1911 		}
1912 		rcu_torture_writer_state = RTWS_STUTTER;
1913 		if (IS_ENABLED(CONFIG_RCU_LAZY))
1914 			queue_work(system_percpu_wq, &lazy_work);
1915 		stutter_waited = stutter_wait("rcu_torture_writer");
1916 		if (stutter_waited &&
1917 		    !atomic_read(&rcu_fwd_cb_nodelay) &&
1918 		    !cur_ops->slow_gps &&
1919 		    !torture_must_stop() &&
1920 		    time_after(jiffies, stallsdone))
1921 			for (i = 0; i < ARRAY_SIZE(rcu_tortures); i++)
1922 				if (list_empty(&rcu_tortures[i].rtort_free) &&
1923 				    rcu_access_pointer(rcu_torture_current) != &rcu_tortures[i]) {
1924 					tracing_off();
1925 					if (cur_ops->gp_kthread_dbg)
1926 						cur_ops->gp_kthread_dbg();
1927 					WARN(1, "%s: rtort_pipe_count: %d\n", __func__, rcu_tortures[i].rtort_pipe_count);
1928 					rcu_ftrace_dump(DUMP_ALL);
1929 					break;
1930 				}
1931 		if (stutter_waited)
1932 			sched_set_normal(current, oldnice);
1933 	} while (!torture_must_stop());
1934 	rcu_torture_current = NULL;  // Let stats task know that we are done.
1935 	/* Reset expediting back to unexpedited. */
1936 	if (expediting > 0)
1937 		expediting = -expediting;
1938 	while (can_expedite && expediting++ < 0)
1939 		rcu_unexpedite_gp();
1940 	WARN_ON_ONCE(can_expedite && rcu_gp_is_expedited());
1941 	if (!can_expedite)
1942 		pr_alert("%s" TORTURE_FLAG
1943 			 " Dynamic grace-period expediting was disabled.\n",
1944 			 torture_type);
1945 
1946 	if (IS_ENABLED(CONFIG_RCU_LAZY)) {
1947 		cancel_work_sync(&lazy_work);
1948 		destroy_work_on_stack(&lazy_work);
1949 	}
1950 
1951 	kfree(ulo);
1952 	kfree(rgo);
1953 	rcu_torture_writer_state = RTWS_STOPPING;
1954 	torture_kthread_stopping("rcu_torture_writer");
1955 	return 0;
1956 }
1957 
1958 /*
1959  * RCU torture fake writer kthread.  Repeatedly calls sync, with a random
1960  * delay between calls.
1961  */
1962 static int
1963 rcu_torture_fakewriter(void *arg)
1964 {
1965 	unsigned long gp_snap;
1966 	struct rcu_gp_oldstate gp_snap_full;
1967 	DEFINE_TORTURE_RANDOM(rand);
1968 
1969 	VERBOSE_TOROUT_STRING("rcu_torture_fakewriter task started");
1970 	set_user_nice(current, MAX_NICE);
1971 
1972 	if (WARN_ONCE(nsynctypes == 0,
1973 		      "%s: No update-side primitives.\n", __func__)) {
1974 		/*
1975 		 * No updates primitives, so don't try updating.
1976 		 * The resulting test won't be testing much, hence the
1977 		 * above WARN_ONCE().
1978 		 */
1979 		torture_kthread_stopping("rcu_torture_fakewriter");
1980 		return 0;
1981 	}
1982 
1983 	do {
1984 		torture_hrtimeout_jiffies(torture_random(&rand) % 10, &rand);
1985 		if (cur_ops->cb_barrier != NULL &&
1986 		    torture_random(&rand) % (nrealfakewriters * 8) == 0) {
1987 			cur_ops->cb_barrier();
1988 		} else {
1989 			switch (synctype[torture_random(&rand) % nsynctypes]) {
1990 			case RTWS_DEF_FREE:
1991 				break;
1992 			case RTWS_EXP_SYNC:
1993 				cur_ops->exp_sync();
1994 				break;
1995 			case RTWS_COND_GET:
1996 				gp_snap = cur_ops->get_gp_state();
1997 				torture_hrtimeout_jiffies(torture_random(&rand) % 16, &rand);
1998 				cur_ops->cond_sync(gp_snap);
1999 				break;
2000 			case RTWS_COND_GET_EXP:
2001 				gp_snap = cur_ops->get_gp_state_exp();
2002 				torture_hrtimeout_jiffies(torture_random(&rand) % 16, &rand);
2003 				cur_ops->cond_sync_exp(gp_snap);
2004 				break;
2005 			case RTWS_COND_GET_FULL:
2006 				cur_ops->get_gp_state_full(&gp_snap_full);
2007 				torture_hrtimeout_jiffies(torture_random(&rand) % 16, &rand);
2008 				cur_ops->cond_sync_full(&gp_snap_full);
2009 				break;
2010 			case RTWS_COND_GET_EXP_FULL:
2011 				cur_ops->get_gp_state_full(&gp_snap_full);
2012 				torture_hrtimeout_jiffies(torture_random(&rand) % 16, &rand);
2013 				cur_ops->cond_sync_exp_full(&gp_snap_full);
2014 				break;
2015 			case RTWS_POLL_GET:
2016 				if (cur_ops->start_poll_irqsoff)
2017 					local_irq_disable();
2018 				gp_snap = cur_ops->start_gp_poll();
2019 				if (cur_ops->start_poll_irqsoff)
2020 					local_irq_enable();
2021 				while (!cur_ops->poll_gp_state(gp_snap)) {
2022 					torture_hrtimeout_jiffies(torture_random(&rand) % 16,
2023 								  &rand);
2024 				}
2025 				break;
2026 			case RTWS_POLL_GET_FULL:
2027 				if (cur_ops->start_poll_irqsoff)
2028 					local_irq_disable();
2029 				cur_ops->start_gp_poll_full(&gp_snap_full);
2030 				if (cur_ops->start_poll_irqsoff)
2031 					local_irq_enable();
2032 				while (!cur_ops->poll_gp_state_full(&gp_snap_full)) {
2033 					torture_hrtimeout_jiffies(torture_random(&rand) % 16,
2034 								  &rand);
2035 				}
2036 				break;
2037 			case RTWS_POLL_GET_EXP:
2038 				gp_snap = cur_ops->start_gp_poll_exp();
2039 				while (!cur_ops->poll_gp_state_exp(gp_snap)) {
2040 					torture_hrtimeout_jiffies(torture_random(&rand) % 16,
2041 								  &rand);
2042 				}
2043 				break;
2044 			case RTWS_POLL_GET_EXP_FULL:
2045 				cur_ops->start_gp_poll_exp_full(&gp_snap_full);
2046 				while (!cur_ops->poll_gp_state_full(&gp_snap_full)) {
2047 					torture_hrtimeout_jiffies(torture_random(&rand) % 16,
2048 								  &rand);
2049 				}
2050 				break;
2051 			case RTWS_SYNC:
2052 				cur_ops->sync();
2053 				break;
2054 			default:
2055 				WARN_ON_ONCE(1);
2056 				break;
2057 			}
2058 		}
2059 		stutter_wait("rcu_torture_fakewriter");
2060 	} while (!torture_must_stop());
2061 
2062 	torture_kthread_stopping("rcu_torture_fakewriter");
2063 	return 0;
2064 }
2065 
2066 static void rcu_torture_timer_cb(struct rcu_head *rhp)
2067 {
2068 	kfree(rhp);
2069 }
2070 
2071 // Set up and carry out testing of RCU's global memory ordering
2072 static void rcu_torture_reader_do_mbchk(long myid, struct rcu_torture *rtp,
2073 					struct torture_random_state *trsp)
2074 {
2075 	unsigned long loops;
2076 	int noc = torture_num_online_cpus();
2077 	int rdrchked;
2078 	int rdrchker;
2079 	struct rcu_torture_reader_check *rtrcp; // Me.
2080 	struct rcu_torture_reader_check *rtrcp_assigner; // Assigned us to do checking.
2081 	struct rcu_torture_reader_check *rtrcp_chked; // Reader being checked.
2082 	struct rcu_torture_reader_check *rtrcp_chker; // Reader doing checking when not me.
2083 
2084 	if (myid < 0)
2085 		return; // Don't try this from timer handlers.
2086 
2087 	// Increment my counter.
2088 	rtrcp = &rcu_torture_reader_mbchk[myid];
2089 	WRITE_ONCE(rtrcp->rtc_myloops, rtrcp->rtc_myloops + 1);
2090 
2091 	// Attempt to assign someone else some checking work.
2092 	rdrchked = torture_random(trsp) % nrealreaders;
2093 	rtrcp_chked = &rcu_torture_reader_mbchk[rdrchked];
2094 	rdrchker = torture_random(trsp) % nrealreaders;
2095 	rtrcp_chker = &rcu_torture_reader_mbchk[rdrchker];
2096 	if (rdrchked != myid && rdrchked != rdrchker && noc >= rdrchked && noc >= rdrchker &&
2097 	    smp_load_acquire(&rtrcp->rtc_chkrdr) < 0 && // Pairs with smp_store_release below.
2098 	    !READ_ONCE(rtp->rtort_chkp) &&
2099 	    !smp_load_acquire(&rtrcp_chker->rtc_assigner)) { // Pairs with smp_store_release below.
2100 		rtrcp->rtc_chkloops = READ_ONCE(rtrcp_chked->rtc_myloops);
2101 		WARN_ON_ONCE(rtrcp->rtc_chkrdr >= 0);
2102 		rtrcp->rtc_chkrdr = rdrchked;
2103 		WARN_ON_ONCE(rtrcp->rtc_ready); // This gets set after the grace period ends.
2104 		if (cmpxchg_relaxed(&rtrcp_chker->rtc_assigner, NULL, rtrcp) ||
2105 		    cmpxchg_relaxed(&rtp->rtort_chkp, NULL, rtrcp))
2106 			(void)cmpxchg_relaxed(&rtrcp_chker->rtc_assigner, rtrcp, NULL); // Back out.
2107 	}
2108 
2109 	// If assigned some completed work, do it!
2110 	rtrcp_assigner = READ_ONCE(rtrcp->rtc_assigner);
2111 	if (!rtrcp_assigner || !smp_load_acquire(&rtrcp_assigner->rtc_ready))
2112 		return; // No work or work not yet ready.
2113 	rdrchked = rtrcp_assigner->rtc_chkrdr;
2114 	if (WARN_ON_ONCE(rdrchked < 0))
2115 		return;
2116 	rtrcp_chked = &rcu_torture_reader_mbchk[rdrchked];
2117 	loops = READ_ONCE(rtrcp_chked->rtc_myloops);
2118 	atomic_inc(&n_rcu_torture_mbchk_tries);
2119 	if (ULONG_CMP_LT(loops, rtrcp_assigner->rtc_chkloops))
2120 		atomic_inc(&n_rcu_torture_mbchk_fail);
2121 	rtrcp_assigner->rtc_chkloops = loops + ULONG_MAX / 2;
2122 	rtrcp_assigner->rtc_ready = 0;
2123 	smp_store_release(&rtrcp->rtc_assigner, NULL); // Someone else can assign us work.
2124 	smp_store_release(&rtrcp_assigner->rtc_chkrdr, -1); // Assigner can again assign.
2125 }
2126 
2127 // Verify the specified RCUTORTURE_RDR* state.
2128 #define ROEC_ARGS "%s %s: Current %#x  To add %#x  To remove %#x  preempt_count() %#x\n", __func__, s, curstate, new, old, preempt_count()
2129 static void rcutorture_one_extend_check(char *s, int curstate, int new, int old)
2130 {
2131 	int mask;
2132 
2133 	if (!IS_ENABLED(CONFIG_RCU_TORTURE_TEST_CHK_RDR_STATE) || in_nmi())
2134 		return;
2135 
2136 	WARN_ONCE(!(curstate & RCUTORTURE_RDR_IRQ) && irqs_disabled() && !in_hardirq(), ROEC_ARGS);
2137 	WARN_ONCE((curstate & RCUTORTURE_RDR_IRQ) && !irqs_disabled(), ROEC_ARGS);
2138 
2139 	// If CONFIG_PREEMPT_COUNT=n, further checks are unreliable.
2140 	if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
2141 		return;
2142 
2143 	WARN_ONCE((curstate & (RCUTORTURE_RDR_BH | RCUTORTURE_RDR_RBH)) &&
2144 		  !softirq_count(), ROEC_ARGS);
2145 	WARN_ONCE((curstate & (RCUTORTURE_RDR_PREEMPT | RCUTORTURE_RDR_SCHED)) &&
2146 		  !(preempt_count() & PREEMPT_MASK), ROEC_ARGS);
2147 	WARN_ONCE(cur_ops->readlock_nesting &&
2148 		  (curstate & (RCUTORTURE_RDR_RCU_1 | RCUTORTURE_RDR_RCU_2)) &&
2149 		  cur_ops->readlock_nesting() == 0, ROEC_ARGS);
2150 
2151 	// Interrupt handlers have all sorts of stuff disabled, so ignore
2152 	// unintended disabling.
2153 	if (in_serving_softirq() || in_hardirq())
2154 		return;
2155 
2156 	WARN_ONCE(cur_ops->extendables &&
2157 		  !(curstate & (RCUTORTURE_RDR_BH | RCUTORTURE_RDR_RBH)) &&
2158 		  softirq_count(), ROEC_ARGS);
2159 
2160 	/*
2161 	 * non-preemptible RCU in a preemptible kernel uses preempt_disable()
2162 	 * as rcu_read_lock().
2163 	 */
2164 	mask = RCUTORTURE_RDR_PREEMPT | RCUTORTURE_RDR_SCHED;
2165 	if (!IS_ENABLED(CONFIG_PREEMPT_RCU))
2166 		mask |= RCUTORTURE_RDR_RCU_1 | RCUTORTURE_RDR_RCU_2;
2167 
2168 	WARN_ONCE(cur_ops->extendables && !(curstate & mask) &&
2169 		  (preempt_count() & PREEMPT_MASK), ROEC_ARGS);
2170 
2171 	/*
2172 	 * non-preemptible RCU in a preemptible kernel uses "preempt_count() &
2173 	 * PREEMPT_MASK" as ->readlock_nesting().
2174 	 */
2175 	mask = RCUTORTURE_RDR_RCU_1 | RCUTORTURE_RDR_RCU_2;
2176 	if (!IS_ENABLED(CONFIG_PREEMPT_RCU))
2177 		mask |= RCUTORTURE_RDR_PREEMPT | RCUTORTURE_RDR_SCHED;
2178 
2179 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && softirq_count())
2180 		mask |= RCUTORTURE_RDR_BH | RCUTORTURE_RDR_RBH;
2181 
2182 	WARN_ONCE(cur_ops->readlock_nesting && !(curstate & mask) &&
2183 		  cur_ops->readlock_nesting() > 0, ROEC_ARGS);
2184 }
2185 
2186 /*
2187  * Do one extension of an RCU read-side critical section using the
2188  * current reader state in readstate (set to zero for initial entry
2189  * to extended critical section), set the new state as specified by
2190  * newstate (set to zero for final exit from extended critical section),
2191  * and random-number-generator state in trsp.  If this is neither the
2192  * beginning or end of the critical section and if there was actually a
2193  * change, do a ->read_delay().
2194  */
2195 static void rcutorture_one_extend(int *readstate, int newstate, struct torture_random_state *trsp,
2196 				  struct rt_read_seg *rtrsp)
2197 {
2198 	bool first;
2199 	unsigned long flags;
2200 	int idxnew1 = -1;
2201 	int idxnew2 = -1;
2202 	int idxold1 = *readstate;
2203 	int idxold2 = idxold1;
2204 	int statesnew = ~*readstate & newstate;
2205 	int statesold = *readstate & ~newstate;
2206 
2207 	first = idxold1 == 0;
2208 	WARN_ON_ONCE(idxold2 < 0);
2209 	WARN_ON_ONCE(idxold2 & ~(RCUTORTURE_RDR_ALLBITS | RCUTORTURE_RDR_UPDOWN));
2210 	rcutorture_one_extend_check("before change", idxold1, statesnew, statesold);
2211 	rtrsp->rt_readstate = newstate;
2212 
2213 	/* First, put new protection in place to avoid critical-section gap. */
2214 	if (statesnew & RCUTORTURE_RDR_BH)
2215 		local_bh_disable();
2216 	if (statesnew & RCUTORTURE_RDR_RBH)
2217 		rcu_read_lock_bh();
2218 	if (statesnew & RCUTORTURE_RDR_IRQ)
2219 		local_irq_disable();
2220 	if (statesnew & RCUTORTURE_RDR_PREEMPT)
2221 		preempt_disable();
2222 	if (statesnew & RCUTORTURE_RDR_SCHED)
2223 		rcu_read_lock_sched();
2224 	if (statesnew & RCUTORTURE_RDR_RCU_1)
2225 		idxnew1 = (cur_ops->readlock() << RCUTORTURE_RDR_SHIFT_1) & RCUTORTURE_RDR_MASK_1;
2226 	if (statesnew & RCUTORTURE_RDR_RCU_2)
2227 		idxnew2 = (cur_ops->readlock() << RCUTORTURE_RDR_SHIFT_2) & RCUTORTURE_RDR_MASK_2;
2228 
2229 	// Complain unless both the old and the new protection is in place.
2230 	rcutorture_one_extend_check("during change", idxold1 | statesnew, statesnew, statesold);
2231 
2232 	// Sample CPU under both sets of protections to reduce confusion.
2233 	if (IS_ENABLED(CONFIG_RCU_TORTURE_TEST_LOG_CPU)) {
2234 		int cpu = raw_smp_processor_id();
2235 		rtrsp->rt_cpu = cpu;
2236 		if (!first) {
2237 			rtrsp[-1].rt_end_cpu = cpu;
2238 			if (cur_ops->reader_blocked)
2239 				rtrsp[-1].rt_preempted = cur_ops->reader_blocked();
2240 		}
2241 	}
2242 	// Sample grace-period sequence number, as good a place as any.
2243 	if (IS_ENABLED(CONFIG_RCU_TORTURE_TEST_LOG_GP) && cur_ops->gather_gp_seqs) {
2244 		rtrsp->rt_gp_seq = cur_ops->gather_gp_seqs();
2245 		rtrsp->rt_ts = ktime_get_mono_fast_ns();
2246 		if (!first)
2247 			rtrsp[-1].rt_gp_seq_end = rtrsp->rt_gp_seq;
2248 	}
2249 
2250 	/*
2251 	 * Next, remove old protection, in decreasing order of strength
2252 	 * to avoid unlock paths that aren't safe in the stronger
2253 	 * context. Namely: BH can not be enabled with disabled interrupts.
2254 	 * Additionally PREEMPT_RT requires that BH is enabled in preemptible
2255 	 * context.
2256 	 */
2257 	if (statesold & RCUTORTURE_RDR_IRQ)
2258 		local_irq_enable();
2259 	if (statesold & RCUTORTURE_RDR_PREEMPT)
2260 		preempt_enable();
2261 	if (statesold & RCUTORTURE_RDR_SCHED)
2262 		rcu_read_unlock_sched();
2263 	if (statesold & RCUTORTURE_RDR_BH)
2264 		local_bh_enable();
2265 	if (statesold & RCUTORTURE_RDR_RBH)
2266 		rcu_read_unlock_bh();
2267 	if (statesold & RCUTORTURE_RDR_RCU_2) {
2268 		cur_ops->readunlock((idxold2 & RCUTORTURE_RDR_MASK_2) >> RCUTORTURE_RDR_SHIFT_2);
2269 		WARN_ON_ONCE(idxnew2 != -1);
2270 		idxold2 = 0;
2271 	}
2272 	if (statesold & RCUTORTURE_RDR_RCU_1) {
2273 		bool lockit;
2274 
2275 		lockit = !cur_ops->no_pi_lock && !statesnew && !(torture_random(trsp) & 0xffff);
2276 		if (lockit)
2277 			raw_spin_lock_irqsave(&current->pi_lock, flags);
2278 		cur_ops->readunlock((idxold1 & RCUTORTURE_RDR_MASK_1) >> RCUTORTURE_RDR_SHIFT_1);
2279 		WARN_ON_ONCE(idxnew1 != -1);
2280 		idxold1 = 0;
2281 		if (lockit)
2282 			raw_spin_unlock_irqrestore(&current->pi_lock, flags);
2283 	}
2284 	if (statesold & RCUTORTURE_RDR_UPDOWN) {
2285 		cur_ops->up_read((idxold1 & RCUTORTURE_RDR_MASK_1) >> RCUTORTURE_RDR_SHIFT_1);
2286 		WARN_ON_ONCE(idxnew1 != -1);
2287 		idxold1 = 0;
2288 	}
2289 
2290 	/* Delay if neither beginning nor end and there was a change. */
2291 	if ((statesnew || statesold) && *readstate && newstate)
2292 		cur_ops->read_delay(trsp, rtrsp);
2293 
2294 	/* Update the reader state. */
2295 	if (idxnew1 == -1)
2296 		idxnew1 = idxold1 & RCUTORTURE_RDR_MASK_1;
2297 	WARN_ON_ONCE(idxnew1 < 0);
2298 	if (idxnew2 == -1)
2299 		idxnew2 = idxold2 & RCUTORTURE_RDR_MASK_2;
2300 	WARN_ON_ONCE(idxnew2 < 0);
2301 	*readstate = idxnew1 | idxnew2 | newstate;
2302 	WARN_ON_ONCE(*readstate < 0);
2303 	if (WARN_ON_ONCE(*readstate & ~RCUTORTURE_RDR_ALLBITS))
2304 		pr_info("Unexpected readstate value of %#x\n", *readstate);
2305 	rcutorture_one_extend_check("after change", *readstate, statesnew, statesold);
2306 }
2307 
2308 /* Return the biggest extendables mask given current RCU and boot parameters. */
2309 static int rcutorture_extend_mask_max(void)
2310 {
2311 	int mask;
2312 
2313 	WARN_ON_ONCE(extendables & ~RCUTORTURE_MAX_EXTEND);
2314 	mask = extendables & RCUTORTURE_MAX_EXTEND & cur_ops->extendables;
2315 	mask = mask | RCUTORTURE_RDR_RCU_1 | RCUTORTURE_RDR_RCU_2;
2316 	return mask;
2317 }
2318 
2319 /* Return a random protection state mask, but with at least one bit set. */
2320 static int
2321 rcutorture_extend_mask(int oldmask, struct torture_random_state *trsp)
2322 {
2323 	int mask = rcutorture_extend_mask_max();
2324 	unsigned long randmask1 = torture_random(trsp);
2325 	unsigned long randmask2 = randmask1 >> 3;
2326 	unsigned long preempts = RCUTORTURE_RDR_PREEMPT | RCUTORTURE_RDR_SCHED;
2327 	unsigned long preempts_irq = preempts | RCUTORTURE_RDR_IRQ;
2328 	unsigned long bhs = RCUTORTURE_RDR_BH | RCUTORTURE_RDR_RBH;
2329 
2330 	WARN_ON_ONCE(mask >> RCUTORTURE_RDR_SHIFT_1);  // Can't have reader idx bits.
2331 	/* Mostly only one bit (need preemption!), sometimes lots of bits. */
2332 	if (!(randmask1 & 0x7))
2333 		mask = mask & randmask2;
2334 	else
2335 		mask = mask & (1 << (randmask2 % RCUTORTURE_RDR_NBITS));
2336 
2337 	// Can't have nested RCU reader without outer RCU reader.
2338 	if (!(mask & RCUTORTURE_RDR_RCU_1) && (mask & RCUTORTURE_RDR_RCU_2)) {
2339 		if (oldmask & RCUTORTURE_RDR_RCU_1)
2340 			mask &= ~RCUTORTURE_RDR_RCU_2;
2341 		else
2342 			mask |= RCUTORTURE_RDR_RCU_1;
2343 	}
2344 
2345 	/*
2346 	 * Can't enable bh w/irq disabled.
2347 	 */
2348 	if (mask & RCUTORTURE_RDR_IRQ)
2349 		mask |= oldmask & bhs;
2350 
2351 	/*
2352 	 * Ideally these sequences would be detected in debug builds
2353 	 * (regardless of RT), but until then don't stop testing
2354 	 * them on non-RT.
2355 	 */
2356 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
2357 		/* Can't modify BH in atomic context */
2358 		if (oldmask & preempts_irq)
2359 			mask &= ~bhs;
2360 		if ((oldmask | mask) & preempts_irq)
2361 			mask |= oldmask & bhs;
2362 	}
2363 
2364 	return mask ?: RCUTORTURE_RDR_RCU_1;
2365 }
2366 
2367 /*
2368  * Do a randomly selected number of extensions of an existing RCU read-side
2369  * critical section.
2370  */
2371 static struct rt_read_seg *
2372 rcutorture_loop_extend(int *readstate, struct torture_random_state *trsp, struct rt_read_seg *rtrsp)
2373 {
2374 	int i;
2375 	int j;
2376 	int mask = rcutorture_extend_mask_max();
2377 
2378 	WARN_ON_ONCE(!*readstate); /* -Existing- RCU read-side critsect! */
2379 	if (!((mask - 1) & mask))
2380 		return rtrsp;  /* Current RCU reader not extendable. */
2381 	/* Bias towards larger numbers of loops. */
2382 	i = torture_random(trsp);
2383 	i = ((i | (i >> 3)) & RCUTORTURE_RDR_MAX_LOOPS) + 1;
2384 	for (j = 0; j < i; j++) {
2385 		mask = rcutorture_extend_mask(*readstate, trsp);
2386 		WARN_ON_ONCE(mask & RCUTORTURE_RDR_UPDOWN);
2387 		rcutorture_one_extend(readstate, mask, trsp, &rtrsp[j]);
2388 	}
2389 	return &rtrsp[j];
2390 }
2391 
2392 struct rcu_torture_one_read_state {
2393 	bool checkpolling;
2394 	unsigned long cookie;
2395 	struct rcu_gp_oldstate cookie_full;
2396 	unsigned long started;
2397 	struct rcu_torture *p;
2398 	int readstate;
2399 	struct rt_read_seg rtseg[RCUTORTURE_RDR_MAX_SEGS];
2400 	struct rt_read_seg *rtrsp;
2401 	unsigned long long ts;
2402 };
2403 
2404 static void init_rcu_torture_one_read_state(struct rcu_torture_one_read_state *rtorsp,
2405 					    struct torture_random_state *trsp)
2406 {
2407 	memset(rtorsp, 0, sizeof(*rtorsp));
2408 	rtorsp->checkpolling = !(torture_random(trsp) & 0xfff);
2409 	rtorsp->rtrsp = &rtorsp->rtseg[0];
2410 }
2411 
2412 /*
2413  * Set up the first segment of a series of overlapping read-side
2414  * critical sections.  The caller must have actually initiated the
2415  * outermost read-side critical section.
2416  */
2417 static bool rcu_torture_one_read_start(struct rcu_torture_one_read_state *rtorsp,
2418 				       struct torture_random_state *trsp, long myid)
2419 {
2420 	if (rtorsp->checkpolling) {
2421 		if (cur_ops->get_gp_state && cur_ops->poll_gp_state)
2422 			rtorsp->cookie = cur_ops->get_gp_state();
2423 		if (cur_ops->get_gp_state_full && cur_ops->poll_gp_state_full)
2424 			cur_ops->get_gp_state_full(&rtorsp->cookie_full);
2425 	}
2426 	rtorsp->started = cur_ops->get_gp_seq();
2427 	rtorsp->ts = rcu_trace_clock_local();
2428 	rtorsp->p = rcu_dereference_check(rcu_torture_current,
2429 					  !cur_ops->readlock_held || cur_ops->readlock_held() ||
2430 					  (rtorsp->readstate & RCUTORTURE_RDR_UPDOWN));
2431 	if (rtorsp->p == NULL) {
2432 		/* Wait for rcu_torture_writer to get underway */
2433 		rcutorture_one_extend(&rtorsp->readstate, 0, trsp, rtorsp->rtrsp);
2434 		return false;
2435 	}
2436 	if (rtorsp->p->rtort_mbtest == 0)
2437 		atomic_inc(&n_rcu_torture_mberror);
2438 	rcu_torture_reader_do_mbchk(myid, rtorsp->p, trsp);
2439 	return true;
2440 }
2441 
2442 /*
2443  * Complete the last segment of a series of overlapping read-side
2444  * critical sections and check for errors.
2445  */
2446 static void rcu_torture_one_read_end(struct rcu_torture_one_read_state *rtorsp,
2447 				     struct torture_random_state *trsp)
2448 {
2449 	int i;
2450 	unsigned long completed;
2451 	int pipe_count;
2452 	bool preempted = false;
2453 	struct rt_read_seg *rtrsp1;
2454 
2455 	preempt_disable();
2456 	pipe_count = READ_ONCE(rtorsp->p->rtort_pipe_count);
2457 	if (pipe_count > RCU_TORTURE_PIPE_LEN) {
2458 		// Should not happen in a correct RCU implementation,
2459 		// happens quite often for torture_type=busted.
2460 		pipe_count = RCU_TORTURE_PIPE_LEN;
2461 	}
2462 	completed = cur_ops->get_gp_seq();
2463 	if (pipe_count > 1) {
2464 		do_trace_rcu_torture_read(cur_ops->name, &rtorsp->p->rtort_rcu,
2465 					  rtorsp->ts, rtorsp->started, completed);
2466 		rcu_ftrace_dump(DUMP_ALL);
2467 	}
2468 	__this_cpu_inc(rcu_torture_count[pipe_count]);
2469 	completed = rcutorture_seq_diff(completed, rtorsp->started);
2470 	if (completed > RCU_TORTURE_PIPE_LEN) {
2471 		/* Should not happen, but... */
2472 		completed = RCU_TORTURE_PIPE_LEN;
2473 	}
2474 	__this_cpu_inc(rcu_torture_batch[completed]);
2475 	preempt_enable();
2476 	if (rtorsp->checkpolling) {
2477 		if (cur_ops->get_gp_state && cur_ops->poll_gp_state)
2478 			WARN_ONCE(cur_ops->poll_gp_state(rtorsp->cookie),
2479 				  "%s: Cookie check 2 failed %s(%d) %lu->%lu\n",
2480 				  __func__,
2481 				  rcu_torture_writer_state_getname(),
2482 				  rcu_torture_writer_state,
2483 				  rtorsp->cookie, cur_ops->get_gp_state());
2484 		if (cur_ops->get_gp_state_full && cur_ops->poll_gp_state_full)
2485 			WARN_ONCE(cur_ops->poll_gp_state_full(&rtorsp->cookie_full),
2486 				  "%s: Cookie check 6 failed %s(%d) online %*pbl\n",
2487 				  __func__,
2488 				  rcu_torture_writer_state_getname(),
2489 				  rcu_torture_writer_state,
2490 				  cpumask_pr_args(cpu_online_mask));
2491 	}
2492 	if (cur_ops->reader_blocked)
2493 		preempted = cur_ops->reader_blocked();
2494 	rcutorture_one_extend(&rtorsp->readstate, 0, trsp, rtorsp->rtrsp);
2495 	WARN_ON_ONCE(rtorsp->readstate);
2496 	// This next splat is expected behavior if leakpointer, especially
2497 	// for CONFIG_RCU_STRICT_GRACE_PERIOD=y kernels.
2498 	WARN_ON_ONCE(leakpointer && READ_ONCE(rtorsp->p->rtort_pipe_count) > 1);
2499 
2500 	/* If error or close call, record the sequence of reader protections. */
2501 	if ((pipe_count > 1 || completed > 1) && !xchg(&err_segs_recorded, 1)) {
2502 		i = 0;
2503 		for (rtrsp1 = &rtorsp->rtseg[0]; rtrsp1 < rtorsp->rtrsp; rtrsp1++)
2504 			err_segs[i++] = *rtrsp1;
2505 		rt_read_nsegs = i;
2506 		rt_read_preempted = preempted;
2507 	}
2508 }
2509 
2510 /*
2511  * Do one read-side critical section, returning false if there was
2512  * no data to read.  Can be invoked both from process context and
2513  * from a timer handler.
2514  */
2515 static bool rcu_torture_one_read(struct torture_random_state *trsp, long myid)
2516 {
2517 	int newstate;
2518 	struct rcu_torture_one_read_state rtors;
2519 
2520 	WARN_ON_ONCE(!rcu_is_watching());
2521 	init_rcu_torture_one_read_state(&rtors, trsp);
2522 	newstate = rcutorture_extend_mask(rtors.readstate, trsp);
2523 	WARN_ON_ONCE(newstate & RCUTORTURE_RDR_UPDOWN);
2524 	rcutorture_one_extend(&rtors.readstate, newstate, trsp, rtors.rtrsp++);
2525 	if (!rcu_torture_one_read_start(&rtors, trsp, myid))
2526 		return false;
2527 	rtors.rtrsp = rcutorture_loop_extend(&rtors.readstate, trsp, rtors.rtrsp);
2528 	rcu_torture_one_read_end(&rtors, trsp);
2529 	return true;
2530 }
2531 
2532 static DEFINE_TORTURE_RANDOM_PERCPU(rcu_torture_timer_rand);
2533 
2534 /*
2535  * RCU torture reader from timer handler.  Dereferences rcu_torture_current,
2536  * incrementing the corresponding element of the pipeline array.  The
2537  * counter in the element should never be greater than 1, otherwise, the
2538  * RCU implementation is broken.
2539  */
2540 static void rcu_torture_timer(struct timer_list *unused)
2541 {
2542 	WARN_ON_ONCE(!in_serving_softirq());
2543 	WARN_ON_ONCE(in_hardirq());
2544 	WARN_ON_ONCE(in_nmi());
2545 	atomic_long_inc(&n_rcu_torture_timers);
2546 	(void)rcu_torture_one_read(this_cpu_ptr(&rcu_torture_timer_rand), -1);
2547 
2548 	/* Test call_rcu() invocation from interrupt handler. */
2549 	if (cur_ops->call) {
2550 		struct rcu_head *rhp = kmalloc_obj(*rhp, GFP_NOWAIT);
2551 
2552 		if (rhp)
2553 			cur_ops->call(rhp, rcu_torture_timer_cb);
2554 	}
2555 }
2556 
2557 /*
2558  * RCU torture reader kthread.  Repeatedly dereferences rcu_torture_current,
2559  * incrementing the corresponding element of the pipeline array.  The
2560  * counter in the element should never be greater than 1, otherwise, the
2561  * RCU implementation is broken.
2562  */
2563 static int
2564 rcu_torture_reader(void *arg)
2565 {
2566 	unsigned long lastsleep = jiffies;
2567 	long myid = (long)arg;
2568 	int mynumonline = myid;
2569 	DEFINE_TORTURE_RANDOM(rand);
2570 	struct timer_list t;
2571 
2572 	VERBOSE_TOROUT_STRING("rcu_torture_reader task started");
2573 	set_user_nice(current, MAX_NICE);
2574 	if (irqreader && cur_ops->irq_capable)
2575 		timer_setup_on_stack(&t, rcu_torture_timer, 0);
2576 	tick_dep_set_task(current, TICK_DEP_BIT_RCU);  // CPU bound, so need tick.
2577 	do {
2578 		if (irqreader && cur_ops->irq_capable) {
2579 			if (!timer_pending(&t))
2580 				mod_timer(&t, jiffies + 1);
2581 		}
2582 		if (!rcu_torture_one_read(&rand, myid) && !torture_must_stop())
2583 			schedule_timeout_interruptible(HZ);
2584 		if (time_after(jiffies, lastsleep) && !torture_must_stop()) {
2585 			torture_hrtimeout_us(500, 1000, &rand);
2586 			lastsleep = jiffies + 10;
2587 		}
2588 		while (!torture_must_stop() &&
2589 		       (torture_num_online_cpus() < mynumonline || !rcu_inkernel_boot_has_ended()))
2590 			schedule_timeout_interruptible(HZ / 5);
2591 		stutter_wait("rcu_torture_reader");
2592 	} while (!torture_must_stop());
2593 	if (irqreader && cur_ops->irq_capable) {
2594 		timer_delete_sync(&t);
2595 		timer_destroy_on_stack(&t);
2596 	}
2597 	tick_dep_clear_task(current, TICK_DEP_BIT_RCU);
2598 	torture_kthread_stopping("rcu_torture_reader");
2599 	return 0;
2600 }
2601 
2602 struct rcu_torture_one_read_state_updown {
2603 	struct hrtimer rtorsu_hrt;
2604 	bool rtorsu_inuse;
2605 	ktime_t rtorsu_kt;
2606 	int rtorsu_cpu;
2607 	unsigned long rtorsu_j;
2608 	unsigned long rtorsu_ndowns;
2609 	unsigned long rtorsu_nups;
2610 	unsigned long rtorsu_nmigrates;
2611 	struct torture_random_state rtorsu_trs;
2612 	struct rcu_torture_one_read_state rtorsu_rtors;
2613 };
2614 
2615 static struct rcu_torture_one_read_state_updown *updownreaders;
2616 static DEFINE_TORTURE_RANDOM(rcu_torture_updown_rand);
2617 static int rcu_torture_updown(void *arg);
2618 
2619 static enum hrtimer_restart rcu_torture_updown_hrt(struct hrtimer *hrtp)
2620 {
2621 	int cpu = raw_smp_processor_id();
2622 	struct rcu_torture_one_read_state_updown *rtorsup;
2623 
2624 	rtorsup = container_of(hrtp, struct rcu_torture_one_read_state_updown, rtorsu_hrt);
2625 	rcu_torture_one_read_end(&rtorsup->rtorsu_rtors, &rtorsup->rtorsu_trs);
2626 	WARN_ONCE(rtorsup->rtorsu_nups >= rtorsup->rtorsu_ndowns, "%s: Up without matching down #%zu.\n", __func__, rtorsup - updownreaders);
2627 	WRITE_ONCE(rtorsup->rtorsu_nups, rtorsup->rtorsu_nups + 1);
2628 	WRITE_ONCE(rtorsup->rtorsu_nmigrates,
2629 		   rtorsup->rtorsu_nmigrates + (cpu != rtorsup->rtorsu_cpu));
2630 	smp_store_release(&rtorsup->rtorsu_inuse, false);
2631 	return HRTIMER_NORESTART;
2632 }
2633 
2634 static int rcu_torture_updown_init(void)
2635 {
2636 	int i;
2637 	struct torture_random_state *rand = &rcu_torture_updown_rand;
2638 	int ret;
2639 
2640 	if (n_up_down < 0)
2641 		return 0;
2642 	if (!srcu_torture_have_up_down()) {
2643 		VERBOSE_TOROUT_STRING("rcu_torture_updown_init: Disabling up/down reader tests due to lack of primitives");
2644 		return 0;
2645 	}
2646 	updownreaders = kzalloc_objs(*updownreaders, n_up_down);
2647 	if (!updownreaders) {
2648 		VERBOSE_TOROUT_STRING("rcu_torture_updown_init: Out of memory, disabling up/down reader tests");
2649 		return -ENOMEM;
2650 	}
2651 	for (i = 0; i < n_up_down; i++) {
2652 		init_rcu_torture_one_read_state(&updownreaders[i].rtorsu_rtors, rand);
2653 		hrtimer_setup(&updownreaders[i].rtorsu_hrt, rcu_torture_updown_hrt, CLOCK_MONOTONIC,
2654 			      HRTIMER_MODE_REL | HRTIMER_MODE_HARD);
2655 		torture_random_init(&updownreaders[i].rtorsu_trs);
2656 		init_rcu_torture_one_read_state(&updownreaders[i].rtorsu_rtors,
2657 						&updownreaders[i].rtorsu_trs);
2658 	}
2659 	ret = torture_create_kthread(rcu_torture_updown, rand, updown_task);
2660 	if (ret) {
2661 		kfree(updownreaders);
2662 		updownreaders = NULL;
2663 	}
2664 	return ret;
2665 }
2666 
2667 static void rcu_torture_updown_cleanup(void)
2668 {
2669 	struct rcu_torture_one_read_state_updown *rtorsup;
2670 
2671 	for (rtorsup = updownreaders; rtorsup < &updownreaders[n_up_down]; rtorsup++) {
2672 		if (!smp_load_acquire(&rtorsup->rtorsu_inuse))
2673 			continue;
2674 		if (hrtimer_cancel(&rtorsup->rtorsu_hrt) || WARN_ON_ONCE(rtorsup->rtorsu_inuse)) {
2675 			rcu_torture_one_read_end(&rtorsup->rtorsu_rtors, &rtorsup->rtorsu_trs);
2676 			WARN_ONCE(rtorsup->rtorsu_nups >= rtorsup->rtorsu_ndowns, "%s: Up without matching down #%zu.\n", __func__, rtorsup - updownreaders);
2677 			WRITE_ONCE(rtorsup->rtorsu_nups, rtorsup->rtorsu_nups + 1);
2678 			smp_store_release(&rtorsup->rtorsu_inuse, false);
2679 		}
2680 
2681 	}
2682 	kfree(updownreaders);
2683 	updownreaders = NULL;
2684 }
2685 
2686 // Do one reader for rcu_torture_updown().
2687 static void rcu_torture_updown_one(struct rcu_torture_one_read_state_updown *rtorsup)
2688 {
2689 	int idx;
2690 	int rawidx;
2691 	ktime_t t;
2692 
2693 	init_rcu_torture_one_read_state(&rtorsup->rtorsu_rtors, &rtorsup->rtorsu_trs);
2694 	rawidx = cur_ops->down_read();
2695 	WRITE_ONCE(rtorsup->rtorsu_ndowns, rtorsup->rtorsu_ndowns + 1);
2696 	idx = (rawidx << RCUTORTURE_RDR_SHIFT_1) & RCUTORTURE_RDR_MASK_1;
2697 	rtorsup->rtorsu_rtors.readstate = idx | RCUTORTURE_RDR_UPDOWN;
2698 	rtorsup->rtorsu_rtors.rtrsp++;
2699 	rtorsup->rtorsu_cpu = raw_smp_processor_id();
2700 	if (!rcu_torture_one_read_start(&rtorsup->rtorsu_rtors, &rtorsup->rtorsu_trs, -1)) {
2701 		WARN_ONCE(rtorsup->rtorsu_nups >= rtorsup->rtorsu_ndowns, "%s: Up without matching down #%zu.\n", __func__, rtorsup - updownreaders);
2702 		WRITE_ONCE(rtorsup->rtorsu_nups, rtorsup->rtorsu_nups + 1);
2703 		schedule_timeout_idle(HZ);
2704 		return;
2705 	}
2706 	smp_store_release(&rtorsup->rtorsu_inuse, true);
2707 	t = torture_random(&rtorsup->rtorsu_trs) & 0xfffff; // One per million.
2708 	if (t < 10 * 1000)
2709 		t = 200 * 1000 * 1000;
2710 	hrtimer_start(&rtorsup->rtorsu_hrt, t, HRTIMER_MODE_REL | HRTIMER_MODE_HARD);
2711 	smp_mb(); // Sample jiffies after posting hrtimer.
2712 	rtorsup->rtorsu_j = jiffies;  // Not used by hrtimer handler.
2713 	rtorsup->rtorsu_kt = t;
2714 }
2715 
2716 /*
2717  * RCU torture up/down reader kthread, starting RCU readers in kthread
2718  * context and ending them in hrtimer handlers.  Otherwise similar to
2719  * rcu_torture_reader().
2720  */
2721 static int
2722 rcu_torture_updown(void *arg)
2723 {
2724 	unsigned long j;
2725 	struct rcu_torture_one_read_state_updown *rtorsup;
2726 
2727 	VERBOSE_TOROUT_STRING("rcu_torture_updown task started");
2728 	do {
2729 		for (rtorsup = updownreaders; rtorsup < &updownreaders[n_up_down]; rtorsup++) {
2730 			if (torture_must_stop())
2731 				break;
2732 			j = smp_load_acquire(&jiffies); // Time before ->rtorsu_inuse.
2733 			if (smp_load_acquire(&rtorsup->rtorsu_inuse)) {
2734 				WARN_ONCE(time_after(j, rtorsup->rtorsu_j + 1 + HZ * 10),
2735 					  "hrtimer queued at jiffies %lu for %lld ns took %lu jiffies\n", rtorsup->rtorsu_j, rtorsup->rtorsu_kt, j - rtorsup->rtorsu_j);
2736 				continue;
2737 			}
2738 			rcu_torture_updown_one(rtorsup);
2739 		}
2740 		torture_hrtimeout_ms(1, 1000, &rcu_torture_updown_rand);
2741 		stutter_wait("rcu_torture_updown");
2742 	} while (!torture_must_stop());
2743 	rcu_torture_updown_cleanup();
2744 	torture_kthread_stopping("rcu_torture_updown");
2745 	return 0;
2746 }
2747 
2748 /*
2749  * Randomly Toggle CPUs' callback-offload state.  This uses hrtimers to
2750  * increase race probabilities and fuzzes the interval between toggling.
2751  */
2752 static int rcu_nocb_toggle(void *arg)
2753 {
2754 	int cpu;
2755 	int maxcpu = -1;
2756 	int oldnice = task_nice(current);
2757 	long r;
2758 	DEFINE_TORTURE_RANDOM(rand);
2759 	ktime_t toggle_delay;
2760 	unsigned long toggle_fuzz;
2761 	ktime_t toggle_interval = ms_to_ktime(nocbs_toggle);
2762 
2763 	VERBOSE_TOROUT_STRING("rcu_nocb_toggle task started");
2764 	while (!rcu_inkernel_boot_has_ended())
2765 		schedule_timeout_interruptible(HZ / 10);
2766 	for_each_possible_cpu(cpu)
2767 		maxcpu = cpu;
2768 	WARN_ON(maxcpu < 0);
2769 	if (toggle_interval > ULONG_MAX)
2770 		toggle_fuzz = ULONG_MAX >> 3;
2771 	else
2772 		toggle_fuzz = toggle_interval >> 3;
2773 	if (toggle_fuzz <= 0)
2774 		toggle_fuzz = NSEC_PER_USEC;
2775 	do {
2776 		r = torture_random(&rand);
2777 		cpu = (r >> 1) % (maxcpu + 1);
2778 		if (r & 0x1) {
2779 			rcu_nocb_cpu_offload(cpu);
2780 			atomic_long_inc(&n_nocb_offload);
2781 		} else {
2782 			rcu_nocb_cpu_deoffload(cpu);
2783 			atomic_long_inc(&n_nocb_deoffload);
2784 		}
2785 		toggle_delay = torture_random(&rand) % toggle_fuzz + toggle_interval;
2786 		set_current_state(TASK_INTERRUPTIBLE);
2787 		schedule_hrtimeout(&toggle_delay, HRTIMER_MODE_REL);
2788 		if (stutter_wait("rcu_nocb_toggle"))
2789 			sched_set_normal(current, oldnice);
2790 	} while (!torture_must_stop());
2791 	torture_kthread_stopping("rcu_nocb_toggle");
2792 	return 0;
2793 }
2794 
2795 /*
2796  * Print torture statistics.  Caller must ensure that there is only
2797  * one call to this function at a given time!!!  This is normally
2798  * accomplished by relying on the module system to only have one copy
2799  * of the module loaded, and then by giving the rcu_torture_stats
2800  * kthread full control (or the init/cleanup functions when rcu_torture_stats
2801  * thread is not running).
2802  */
2803 static void
2804 rcu_torture_stats_print(void)
2805 {
2806 	int cpu;
2807 	int i;
2808 	long pipesummary[RCU_TORTURE_PIPE_LEN + 1] = { 0 };
2809 	long batchsummary[RCU_TORTURE_PIPE_LEN + 1] = { 0 };
2810 	long n_gpwraps = 0;
2811 	unsigned long ndowns = 0;
2812 	unsigned long nunexpired = 0;
2813 	unsigned long nmigrates = 0;
2814 	unsigned long nups = 0;
2815 	struct rcu_torture *rtcp;
2816 	static unsigned long rtcv_snap = ULONG_MAX;
2817 	static bool splatted;
2818 	struct task_struct *wtp;
2819 
2820 	for_each_possible_cpu(cpu) {
2821 		for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++) {
2822 			pipesummary[i] += READ_ONCE(per_cpu(rcu_torture_count, cpu)[i]);
2823 			batchsummary[i] += READ_ONCE(per_cpu(rcu_torture_batch, cpu)[i]);
2824 		}
2825 		if (cur_ops->get_gpwrap_count)
2826 			n_gpwraps += cur_ops->get_gpwrap_count(cpu);
2827 	}
2828 	if (updownreaders) {
2829 		for (i = 0; i < n_up_down; i++) {
2830 			ndowns += READ_ONCE(updownreaders[i].rtorsu_ndowns);
2831 			nups += READ_ONCE(updownreaders[i].rtorsu_nups);
2832 			nunexpired += READ_ONCE(updownreaders[i].rtorsu_inuse);
2833 			nmigrates += READ_ONCE(updownreaders[i].rtorsu_nmigrates);
2834 		}
2835 	}
2836 	for (i = RCU_TORTURE_PIPE_LEN; i >= 0; i--) {
2837 		if (pipesummary[i] != 0)
2838 			break;
2839 	} // The value of variable "i" is used later, so don't clobber it!
2840 
2841 	pr_alert("%s%s ", torture_type, TORTURE_FLAG);
2842 	rtcp = rcu_access_pointer(rcu_torture_current);
2843 	pr_cont("rtc: %p %s: %lu tfle: %d rta: %d rtaf: %d rtf: %d ",
2844 		rtcp,
2845 		rtcp && !rcu_stall_is_suppressed_at_boot() ? "ver" : "VER",
2846 		rcu_torture_current_version,
2847 		list_empty(&rcu_torture_freelist),
2848 		atomic_read(&n_rcu_torture_alloc),
2849 		atomic_read(&n_rcu_torture_alloc_fail),
2850 		atomic_read(&n_rcu_torture_free));
2851 	pr_cont("rtmbe: %d rtmbkf: %d/%d rtbe: %ld rtbke: %ld ",
2852 		atomic_read(&n_rcu_torture_mberror),
2853 		atomic_read(&n_rcu_torture_mbchk_fail), atomic_read(&n_rcu_torture_mbchk_tries),
2854 		n_rcu_torture_barrier_error,
2855 		n_rcu_torture_boost_ktrerror);
2856 	pr_cont("rtbf: %ld rtb: %ld nt: %ld ",
2857 		n_rcu_torture_boost_failure,
2858 		n_rcu_torture_boosts,
2859 		atomic_long_read(&n_rcu_torture_timers));
2860 	if (updownreaders)
2861 		pr_cont("ndowns: %lu nups: %lu nhrt: %lu nmigrates: %lu ", ndowns, nups, nunexpired,  nmigrates);
2862 	torture_onoff_stats();
2863 	pr_cont("barrier: %ld/%ld:%ld ",
2864 		data_race(n_barrier_successes),
2865 		data_race(n_barrier_attempts),
2866 		data_race(n_rcu_torture_barrier_error));
2867 	pr_cont("read-exits: %ld ", data_race(n_read_exits)); // Statistic.
2868 	pr_cont("nocb-toggles: %ld:%ld ",
2869 		atomic_long_read(&n_nocb_offload), atomic_long_read(&n_nocb_deoffload));
2870 	pr_cont("gpwraps: %ld\n", n_gpwraps);
2871 
2872 	pr_alert("%s%s ", torture_type, TORTURE_FLAG);
2873 	if (atomic_read(&n_rcu_torture_mberror) ||
2874 	    atomic_read(&n_rcu_torture_mbchk_fail) ||
2875 	    n_rcu_torture_barrier_error || n_rcu_torture_boost_ktrerror ||
2876 	    n_rcu_torture_boost_failure || i > 1) {
2877 		pr_cont("%s", "!!! ");
2878 		atomic_inc(&n_rcu_torture_error);
2879 		WARN_ON_ONCE(atomic_read(&n_rcu_torture_mberror));
2880 		WARN_ON_ONCE(atomic_read(&n_rcu_torture_mbchk_fail));
2881 		WARN_ON_ONCE(n_rcu_torture_barrier_error);  // rcu_barrier()
2882 		WARN_ON_ONCE(n_rcu_torture_boost_ktrerror); // no boost kthread
2883 		WARN_ON_ONCE(n_rcu_torture_boost_failure); // boost failed (TIMER_SOFTIRQ RT prio?)
2884 		WARN_ON_ONCE(i > 1); // Too-short grace period
2885 	}
2886 	pr_cont("Reader Pipe: ");
2887 	for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++)
2888 		pr_cont(" %ld", pipesummary[i]);
2889 	pr_cont("\n");
2890 
2891 	pr_alert("%s%s ", torture_type, TORTURE_FLAG);
2892 	pr_cont("Reader Batch: ");
2893 	for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++)
2894 		pr_cont(" %ld", batchsummary[i]);
2895 	pr_cont("\n");
2896 
2897 	pr_alert("%s%s ", torture_type, TORTURE_FLAG);
2898 	pr_cont("Free-Block Circulation: ");
2899 	for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++) {
2900 		pr_cont(" %d", atomic_read(&rcu_torture_wcount[i]));
2901 	}
2902 	pr_cont("\n");
2903 
2904 	if (cur_ops->stats)
2905 		cur_ops->stats();
2906 	if (rtcv_snap == rcu_torture_current_version &&
2907 	    rcu_access_pointer(rcu_torture_current) &&
2908 	    !rcu_stall_is_suppressed() &&
2909 	    rcu_inkernel_boot_has_ended()) {
2910 		int __maybe_unused flags = 0;
2911 		unsigned long __maybe_unused gp_seq = 0;
2912 
2913 		if (cur_ops->get_gp_data)
2914 			cur_ops->get_gp_data(&flags, &gp_seq);
2915 		wtp = READ_ONCE(writer_task);
2916 		pr_alert("??? Writer stall state %s(%d) g%lu f%#x ->state %#x cpu %d\n",
2917 			 rcu_torture_writer_state_getname(),
2918 			 rcu_torture_writer_state, gp_seq, flags,
2919 			 wtp == NULL ? ~0U : wtp->__state,
2920 			 wtp == NULL ? -1 : (int)task_cpu(wtp));
2921 		if (!splatted && wtp) {
2922 			sched_show_task(wtp);
2923 			splatted = true;
2924 		}
2925 		if (cur_ops->gp_kthread_dbg)
2926 			cur_ops->gp_kthread_dbg();
2927 		rcu_ftrace_dump(DUMP_ALL);
2928 	}
2929 	rtcv_snap = rcu_torture_current_version;
2930 }
2931 
2932 /*
2933  * Periodically prints torture statistics, if periodic statistics printing
2934  * was specified via the stat_interval module parameter.
2935  */
2936 static int
2937 rcu_torture_stats(void *arg)
2938 {
2939 	VERBOSE_TOROUT_STRING("rcu_torture_stats task started");
2940 	do {
2941 		schedule_timeout_interruptible(stat_interval * HZ);
2942 		rcu_torture_stats_print();
2943 		torture_shutdown_absorb("rcu_torture_stats");
2944 	} while (!torture_must_stop());
2945 	torture_kthread_stopping("rcu_torture_stats");
2946 	return 0;
2947 }
2948 
2949 /* Test mem_dump_obj() and friends.  */
2950 static void rcu_torture_mem_dump_obj(void)
2951 {
2952 	struct rcu_head *rhp;
2953 	struct kmem_cache *kcp;
2954 	static int z;
2955 
2956 	kcp = kmem_cache_create("rcuscale", 136, 8, SLAB_STORE_USER, NULL);
2957 	if (WARN_ON_ONCE(!kcp))
2958 		return;
2959 	rhp = kmem_cache_alloc(kcp, GFP_KERNEL);
2960 	if (WARN_ON_ONCE(!rhp)) {
2961 		kmem_cache_destroy(kcp);
2962 		return;
2963 	}
2964 	pr_alert("mem_dump_obj() slab test: rcu_torture_stats = %px, &rhp = %px, rhp = %px, &z = %px\n", stats_task, &rhp, rhp, &z);
2965 	pr_alert("mem_dump_obj(ZERO_SIZE_PTR):");
2966 	mem_dump_obj(ZERO_SIZE_PTR);
2967 	pr_alert("mem_dump_obj(NULL):");
2968 	mem_dump_obj(NULL);
2969 	pr_alert("mem_dump_obj(%px):", &rhp);
2970 	mem_dump_obj(&rhp);
2971 	pr_alert("mem_dump_obj(%px):", rhp);
2972 	mem_dump_obj(rhp);
2973 	pr_alert("mem_dump_obj(%px):", &rhp->func);
2974 	mem_dump_obj(&rhp->func);
2975 	pr_alert("mem_dump_obj(%px):", &z);
2976 	mem_dump_obj(&z);
2977 	kmem_cache_free(kcp, rhp);
2978 	kmem_cache_destroy(kcp);
2979 	rhp = kmalloc_obj(*rhp);
2980 	if (WARN_ON_ONCE(!rhp))
2981 		return;
2982 	pr_alert("mem_dump_obj() kmalloc test: rcu_torture_stats = %px, &rhp = %px, rhp = %px\n", stats_task, &rhp, rhp);
2983 	pr_alert("mem_dump_obj(kmalloc %px):", rhp);
2984 	mem_dump_obj(rhp);
2985 	pr_alert("mem_dump_obj(kmalloc %px):", &rhp->func);
2986 	mem_dump_obj(&rhp->func);
2987 	kfree(rhp);
2988 	rhp = vmalloc(4096);
2989 	if (WARN_ON_ONCE(!rhp))
2990 		return;
2991 	pr_alert("mem_dump_obj() vmalloc test: rcu_torture_stats = %px, &rhp = %px, rhp = %px\n", stats_task, &rhp, rhp);
2992 	pr_alert("mem_dump_obj(vmalloc %px):", rhp);
2993 	mem_dump_obj(rhp);
2994 	pr_alert("mem_dump_obj(vmalloc %px):", &rhp->func);
2995 	mem_dump_obj(&rhp->func);
2996 	vfree(rhp);
2997 }
2998 
2999 static void
3000 rcu_torture_print_module_parms(struct rcu_torture_ops *cur_ops, const char *tag)
3001 {
3002 	pr_alert("%s" TORTURE_FLAG
3003 		 "--- %s: nreaders=%d nfakewriters=%d "
3004 		 "stat_interval=%d verbose=%d test_no_idle_hz=%d "
3005 		 "shuffle_interval=%d stutter=%d irqreader=%d "
3006 		 "fqs_duration=%d fqs_holdoff=%d fqs_stutter=%d "
3007 		 "test_boost=%d/%d test_boost_interval=%d "
3008 		 "test_boost_duration=%d test_boost_holdoff=%d shutdown_secs=%d "
3009 		 "stall_cpu=%d stall_cpu_holdoff=%d stall_cpu_irqsoff=%d "
3010 		 "stall_cpu_block=%d stall_cpu_repeat=%d "
3011 		 "n_barrier_cbs=%d "
3012 		 "onoff_interval=%d onoff_holdoff=%d "
3013 		 "read_exit_delay=%d read_exit_burst=%d "
3014 		 "reader_flavor=%x "
3015 		 "nocbs_nthreads=%d nocbs_toggle=%d "
3016 		 "test_nmis=%d "
3017 		 "preempt_duration=%d preempt_interval=%d n_up_down=%d\n",
3018 		 torture_type, tag, nrealreaders, nrealfakewriters,
3019 		 stat_interval, verbose, test_no_idle_hz, shuffle_interval,
3020 		 stutter, irqreader, fqs_duration, fqs_holdoff, fqs_stutter,
3021 		 test_boost, cur_ops->can_boost,
3022 		 test_boost_interval, test_boost_duration, test_boost_holdoff, shutdown_secs,
3023 		 stall_cpu, stall_cpu_holdoff, stall_cpu_irqsoff,
3024 		 stall_cpu_block, stall_cpu_repeat,
3025 		 n_barrier_cbs,
3026 		 onoff_interval, onoff_holdoff,
3027 		 read_exit_delay, read_exit_burst,
3028 		 reader_flavor,
3029 		 nocbs_nthreads, nocbs_toggle,
3030 		 test_nmis,
3031 		 preempt_duration, preempt_interval, n_up_down);
3032 }
3033 
3034 static int rcutorture_booster_cleanup(unsigned int cpu)
3035 {
3036 	struct task_struct *t;
3037 
3038 	if (boost_tasks[cpu] == NULL)
3039 		return 0;
3040 	mutex_lock(&boost_mutex);
3041 	t = boost_tasks[cpu];
3042 	boost_tasks[cpu] = NULL;
3043 	rcu_torture_enable_rt_throttle();
3044 	mutex_unlock(&boost_mutex);
3045 
3046 	/* This must be outside of the mutex, otherwise deadlock! */
3047 	torture_stop_kthread(rcu_torture_boost, t);
3048 	return 0;
3049 }
3050 
3051 static int rcutorture_booster_init(unsigned int cpu)
3052 {
3053 	int retval;
3054 
3055 	if (boost_tasks[cpu] != NULL)
3056 		return 0;  /* Already created, nothing more to do. */
3057 
3058 	// Testing RCU priority boosting requires rcutorture do
3059 	// some serious abuse.  Counter this by running ksoftirqd
3060 	// at higher priority.
3061 	if (IS_BUILTIN(CONFIG_RCU_TORTURE_TEST)) {
3062 		struct sched_param sp;
3063 		struct task_struct *t;
3064 
3065 		t = per_cpu(ksoftirqd, cpu);
3066 		WARN_ON_ONCE(!t);
3067 		sp.sched_priority = 2;
3068 		sched_setscheduler_nocheck(t, SCHED_FIFO, &sp);
3069 #ifdef CONFIG_IRQ_FORCED_THREADING
3070 		if (force_irqthreads()) {
3071 			t = per_cpu(ktimerd, cpu);
3072 			WARN_ON_ONCE(!t);
3073 			sp.sched_priority = 2;
3074 			sched_setscheduler_nocheck(t, SCHED_FIFO, &sp);
3075 		}
3076 #endif
3077 	}
3078 
3079 	/* Don't allow time recalculation while creating a new task. */
3080 	mutex_lock(&boost_mutex);
3081 	rcu_torture_disable_rt_throttle();
3082 	VERBOSE_TOROUT_STRING("Creating rcu_torture_boost task");
3083 	boost_tasks[cpu] = kthread_run_on_cpu(rcu_torture_boost, NULL,
3084 					      cpu, "rcu_torture_boost_%u");
3085 	if (IS_ERR(boost_tasks[cpu])) {
3086 		retval = PTR_ERR(boost_tasks[cpu]);
3087 		VERBOSE_TOROUT_STRING("rcu_torture_boost task create failed");
3088 		n_rcu_torture_boost_ktrerror++;
3089 		boost_tasks[cpu] = NULL;
3090 		mutex_unlock(&boost_mutex);
3091 		return retval;
3092 	}
3093 	mutex_unlock(&boost_mutex);
3094 	return 0;
3095 }
3096 
3097 static int rcu_torture_stall_nf(struct notifier_block *nb, unsigned long v, void *ptr)
3098 {
3099 	pr_info("%s: v=%lu, duration=%lu.\n", __func__, v, (unsigned long)ptr);
3100 	return NOTIFY_OK;
3101 }
3102 
3103 static struct notifier_block rcu_torture_stall_block = {
3104 	.notifier_call = rcu_torture_stall_nf,
3105 };
3106 
3107 /*
3108  * CPU-stall kthread.  It waits as specified by stall_cpu_holdoff, then
3109  * induces a CPU stall for the time specified by stall_cpu.  If a new
3110  * stall test is added, stallsdone in rcu_torture_writer() must be adjusted.
3111  */
3112 static void rcu_torture_stall_one(int rep, int irqsoff)
3113 {
3114 	int idx;
3115 	unsigned long stop_at;
3116 
3117 	if (stall_cpu_holdoff > 0) {
3118 		VERBOSE_TOROUT_STRING("rcu_torture_stall begin holdoff");
3119 		schedule_timeout_interruptible(stall_cpu_holdoff * HZ);
3120 		VERBOSE_TOROUT_STRING("rcu_torture_stall end holdoff");
3121 	}
3122 	if (!kthread_should_stop() && stall_gp_kthread > 0) {
3123 		VERBOSE_TOROUT_STRING("rcu_torture_stall begin GP stall");
3124 		rcu_gp_set_torture_wait(stall_gp_kthread * HZ);
3125 		for (idx = 0; idx < stall_gp_kthread + 2; idx++) {
3126 			if (kthread_should_stop())
3127 				break;
3128 			schedule_timeout_uninterruptible(HZ);
3129 		}
3130 	}
3131 	if (!kthread_should_stop() && stall_cpu > 0) {
3132 		VERBOSE_TOROUT_STRING("rcu_torture_stall begin CPU stall");
3133 		stop_at = ktime_get_seconds() + stall_cpu;
3134 		/* RCU CPU stall is expected behavior in following code. */
3135 		idx = cur_ops->readlock();
3136 		if (irqsoff)
3137 			local_irq_disable();
3138 		else if (!stall_cpu_block)
3139 			preempt_disable();
3140 		pr_alert("%s start stall episode %d on CPU %d.\n",
3141 			  __func__, rep + 1, raw_smp_processor_id());
3142 		while (ULONG_CMP_LT((unsigned long)ktime_get_seconds(), stop_at) &&
3143 		       !kthread_should_stop())
3144 			if (stall_cpu_block) {
3145 #ifdef CONFIG_PREEMPTION
3146 				preempt_schedule();
3147 #else
3148 				schedule_timeout_uninterruptible(HZ);
3149 #endif
3150 			} else if (stall_no_softlockup) {
3151 				touch_softlockup_watchdog();
3152 			}
3153 		if (irqsoff)
3154 			local_irq_enable();
3155 		else if (!stall_cpu_block)
3156 			preempt_enable();
3157 		cur_ops->readunlock(idx);
3158 	}
3159 }
3160 
3161 /*
3162  * CPU-stall kthread.  Invokes rcu_torture_stall_one() once, and then as many
3163  * additional times as specified by the stall_cpu_repeat module parameter.
3164  * Note that stall_cpu_irqsoff is ignored on the second and subsequent
3165  * stall.
3166  */
3167 static int rcu_torture_stall(void *args)
3168 {
3169 	int i;
3170 	int repeat = stall_cpu_repeat;
3171 	int ret;
3172 
3173 	VERBOSE_TOROUT_STRING("rcu_torture_stall task started");
3174 	if (repeat < 0) {
3175 		repeat = 0;
3176 		WARN_ON_ONCE(IS_BUILTIN(CONFIG_RCU_TORTURE_TEST));
3177 	}
3178 	if (rcu_cpu_stall_notifiers) {
3179 		ret = rcu_stall_chain_notifier_register(&rcu_torture_stall_block);
3180 		if (ret)
3181 			pr_info("%s: rcu_stall_chain_notifier_register() returned %d, %sexpected.\n",
3182 				__func__, ret, !IS_ENABLED(CONFIG_RCU_STALL_COMMON) ? "un" : "");
3183 	}
3184 	for (i = 0; i <= repeat; i++) {
3185 		if (kthread_should_stop())
3186 			break;
3187 		rcu_torture_stall_one(i, i == 0 ? stall_cpu_irqsoff : 0);
3188 	}
3189 	pr_alert("%s end.\n", __func__);
3190 	if (rcu_cpu_stall_notifiers && !ret) {
3191 		ret = rcu_stall_chain_notifier_unregister(&rcu_torture_stall_block);
3192 		if (ret)
3193 			pr_info("%s: rcu_stall_chain_notifier_unregister() returned %d.\n", __func__, ret);
3194 	}
3195 	torture_shutdown_absorb("rcu_torture_stall");
3196 	while (!kthread_should_stop())
3197 		schedule_timeout_interruptible(10 * HZ);
3198 	return 0;
3199 }
3200 
3201 /* Spawn CPU-stall kthread, if stall_cpu specified. */
3202 static int __init rcu_torture_stall_init(void)
3203 {
3204 	if (stall_cpu <= 0 && stall_gp_kthread <= 0)
3205 		return 0;
3206 	return torture_create_kthread(rcu_torture_stall, NULL, stall_task);
3207 }
3208 
3209 /* State structure for forward-progress self-propagating RCU callback. */
3210 struct fwd_cb_state {
3211 	struct rcu_head rh;
3212 	int stop;
3213 };
3214 
3215 /*
3216  * Forward-progress self-propagating RCU callback function.  Because
3217  * callbacks run from softirq, this function is an implicit RCU read-side
3218  * critical section.
3219  */
3220 static void rcu_torture_fwd_prog_cb(struct rcu_head *rhp)
3221 {
3222 	struct fwd_cb_state *fcsp = container_of(rhp, struct fwd_cb_state, rh);
3223 
3224 	if (READ_ONCE(fcsp->stop)) {
3225 		WRITE_ONCE(fcsp->stop, 2);
3226 		return;
3227 	}
3228 	cur_ops->call(&fcsp->rh, rcu_torture_fwd_prog_cb);
3229 }
3230 
3231 /* State for continuous-flood RCU callbacks. */
3232 struct rcu_fwd_cb {
3233 	struct rcu_head rh;
3234 	struct rcu_fwd_cb *rfc_next;
3235 	struct rcu_fwd *rfc_rfp;
3236 	int rfc_gps;
3237 };
3238 
3239 #define MAX_FWD_CB_JIFFIES	(8 * HZ) /* Maximum CB test duration. */
3240 #define MIN_FWD_CB_LAUNDERS	3	/* This many CB invocations to count. */
3241 #define MIN_FWD_CBS_LAUNDERED	100	/* Number of counted CBs. */
3242 #define FWD_CBS_HIST_DIV	10	/* Histogram buckets/second. */
3243 #define N_LAUNDERS_HIST (2 * MAX_FWD_CB_JIFFIES / (HZ / FWD_CBS_HIST_DIV))
3244 
3245 struct rcu_launder_hist {
3246 	long n_launders;
3247 	unsigned long launder_gp_seq;
3248 };
3249 
3250 struct rcu_fwd {
3251 	spinlock_t rcu_fwd_lock;
3252 	struct rcu_fwd_cb *rcu_fwd_cb_head;
3253 	struct rcu_fwd_cb **rcu_fwd_cb_tail;
3254 	long n_launders_cb;
3255 	unsigned long rcu_fwd_startat;
3256 	struct rcu_launder_hist n_launders_hist[N_LAUNDERS_HIST];
3257 	unsigned long rcu_launder_gp_seq_start;
3258 	int rcu_fwd_id;
3259 };
3260 
3261 static DEFINE_MUTEX(rcu_fwd_mutex);
3262 static struct rcu_fwd *rcu_fwds;
3263 static unsigned long rcu_fwd_seq;
3264 static atomic_long_t rcu_fwd_max_cbs;
3265 static bool rcu_fwd_emergency_stop;
3266 
3267 static void rcu_torture_fwd_cb_hist(struct rcu_fwd *rfp)
3268 {
3269 	unsigned long gps;
3270 	unsigned long gps_old;
3271 	int i;
3272 	int j;
3273 
3274 	for (i = ARRAY_SIZE(rfp->n_launders_hist) - 1; i > 0; i--)
3275 		if (rfp->n_launders_hist[i].n_launders > 0)
3276 			break;
3277 	pr_alert("%s: Callback-invocation histogram %d (duration %lu jiffies):",
3278 		 __func__, rfp->rcu_fwd_id, jiffies - rfp->rcu_fwd_startat);
3279 	gps_old = rfp->rcu_launder_gp_seq_start;
3280 	for (j = 0; j <= i; j++) {
3281 		gps = rfp->n_launders_hist[j].launder_gp_seq;
3282 		pr_cont(" %ds/%d: %ld:%ld",
3283 			j + 1, FWD_CBS_HIST_DIV,
3284 			rfp->n_launders_hist[j].n_launders,
3285 			rcutorture_seq_diff(gps, gps_old));
3286 		gps_old = gps;
3287 	}
3288 	pr_cont("\n");
3289 }
3290 
3291 /* Callback function for continuous-flood RCU callbacks. */
3292 static void rcu_torture_fwd_cb_cr(struct rcu_head *rhp)
3293 {
3294 	unsigned long flags;
3295 	int i;
3296 	struct rcu_fwd_cb *rfcp = container_of(rhp, struct rcu_fwd_cb, rh);
3297 	struct rcu_fwd_cb **rfcpp;
3298 	struct rcu_fwd *rfp = rfcp->rfc_rfp;
3299 
3300 	rfcp->rfc_next = NULL;
3301 	rfcp->rfc_gps++;
3302 	spin_lock_irqsave(&rfp->rcu_fwd_lock, flags);
3303 	rfcpp = rfp->rcu_fwd_cb_tail;
3304 	rfp->rcu_fwd_cb_tail = &rfcp->rfc_next;
3305 	smp_store_release(rfcpp, rfcp);
3306 	WRITE_ONCE(rfp->n_launders_cb, rfp->n_launders_cb + 1);
3307 	i = ((jiffies - rfp->rcu_fwd_startat) / (HZ / FWD_CBS_HIST_DIV));
3308 	if (i >= ARRAY_SIZE(rfp->n_launders_hist))
3309 		i = ARRAY_SIZE(rfp->n_launders_hist) - 1;
3310 	rfp->n_launders_hist[i].n_launders++;
3311 	rfp->n_launders_hist[i].launder_gp_seq = cur_ops->get_gp_seq();
3312 	spin_unlock_irqrestore(&rfp->rcu_fwd_lock, flags);
3313 }
3314 
3315 // Give the scheduler a chance, even on nohz_full CPUs.
3316 static void rcu_torture_fwd_prog_cond_resched(unsigned long iter)
3317 {
3318 	if (IS_ENABLED(CONFIG_PREEMPTION) && IS_ENABLED(CONFIG_NO_HZ_FULL)) {
3319 		// Real call_rcu() floods hit userspace, so emulate that.
3320 		if (need_resched() || (iter & 0xfff))
3321 			schedule();
3322 		return;
3323 	}
3324 	// No userspace emulation: CB invocation throttles call_rcu()
3325 	cond_resched();
3326 }
3327 
3328 /*
3329  * Free all callbacks on the rcu_fwd_cb_head list, either because the
3330  * test is over or because we hit an OOM event.
3331  */
3332 static unsigned long rcu_torture_fwd_prog_cbfree(struct rcu_fwd *rfp)
3333 {
3334 	unsigned long flags;
3335 	unsigned long freed = 0;
3336 	struct rcu_fwd_cb *rfcp;
3337 
3338 	for (;;) {
3339 		spin_lock_irqsave(&rfp->rcu_fwd_lock, flags);
3340 		rfcp = rfp->rcu_fwd_cb_head;
3341 		if (!rfcp) {
3342 			spin_unlock_irqrestore(&rfp->rcu_fwd_lock, flags);
3343 			break;
3344 		}
3345 		rfp->rcu_fwd_cb_head = rfcp->rfc_next;
3346 		if (!rfp->rcu_fwd_cb_head)
3347 			rfp->rcu_fwd_cb_tail = &rfp->rcu_fwd_cb_head;
3348 		spin_unlock_irqrestore(&rfp->rcu_fwd_lock, flags);
3349 		kfree(rfcp);
3350 		freed++;
3351 		rcu_torture_fwd_prog_cond_resched(freed);
3352 		if (tick_nohz_full_enabled()) {
3353 			local_irq_save(flags);
3354 			rcu_momentary_eqs();
3355 			local_irq_restore(flags);
3356 		}
3357 	}
3358 	return freed;
3359 }
3360 
3361 /* Carry out need_resched()/cond_resched() forward-progress testing. */
3362 static void rcu_torture_fwd_prog_nr(struct rcu_fwd *rfp,
3363 				    int *tested, int *tested_tries)
3364 {
3365 	unsigned long cver;
3366 	unsigned long dur;
3367 	struct fwd_cb_state fcs;
3368 	unsigned long gps;
3369 	int idx;
3370 	int sd;
3371 	int sd4;
3372 	bool selfpropcb = false;
3373 	unsigned long stopat;
3374 	static DEFINE_TORTURE_RANDOM(trs);
3375 
3376 	pr_alert("%s: Starting forward-progress test %d\n", __func__, rfp->rcu_fwd_id);
3377 	if (!cur_ops->sync)
3378 		return; // Cannot do need_resched() forward progress testing without ->sync.
3379 	if (cur_ops->call && cur_ops->cb_barrier) {
3380 		init_rcu_head_on_stack(&fcs.rh);
3381 		selfpropcb = true;
3382 	}
3383 
3384 	/* Tight loop containing cond_resched(). */
3385 	atomic_inc(&rcu_fwd_cb_nodelay);
3386 	cur_ops->sync(); /* Later readers see above write. */
3387 	if  (selfpropcb) {
3388 		WRITE_ONCE(fcs.stop, 0);
3389 		cur_ops->call(&fcs.rh, rcu_torture_fwd_prog_cb);
3390 	}
3391 	cver = READ_ONCE(rcu_torture_current_version);
3392 	gps = cur_ops->get_gp_seq();
3393 	sd = cur_ops->stall_dur() + 1;
3394 	sd4 = (sd + fwd_progress_div - 1) / fwd_progress_div;
3395 	dur = sd4 + torture_random(&trs) % (sd - sd4);
3396 	WRITE_ONCE(rfp->rcu_fwd_startat, jiffies);
3397 	stopat = rfp->rcu_fwd_startat + dur;
3398 	while (time_before(jiffies, stopat) &&
3399 	       !shutdown_time_arrived() &&
3400 	       !READ_ONCE(rcu_fwd_emergency_stop) && !torture_must_stop()) {
3401 		idx = cur_ops->readlock();
3402 		udelay(10);
3403 		cur_ops->readunlock(idx);
3404 		if (!fwd_progress_need_resched || need_resched())
3405 			cond_resched();
3406 	}
3407 	(*tested_tries)++;
3408 	if (!time_before(jiffies, stopat) &&
3409 	    !shutdown_time_arrived() &&
3410 	    !READ_ONCE(rcu_fwd_emergency_stop) && !torture_must_stop()) {
3411 		(*tested)++;
3412 		cver = READ_ONCE(rcu_torture_current_version) - cver;
3413 		gps = rcutorture_seq_diff(cur_ops->get_gp_seq(), gps);
3414 		WARN_ON(!cver && gps < 2);
3415 		pr_alert("%s: %d Duration %ld cver %ld gps %ld\n", __func__,
3416 			 rfp->rcu_fwd_id, dur, cver, gps);
3417 	}
3418 	if (selfpropcb) {
3419 		WRITE_ONCE(fcs.stop, 1);
3420 		cur_ops->sync(); /* Wait for running CB to complete. */
3421 		pr_alert("%s: Waiting for CBs: %pS() %d\n", __func__, cur_ops->cb_barrier, rfp->rcu_fwd_id);
3422 		cur_ops->cb_barrier(); /* Wait for queued callbacks. */
3423 	}
3424 
3425 	if (selfpropcb) {
3426 		WARN_ON(READ_ONCE(fcs.stop) != 2);
3427 		destroy_rcu_head_on_stack(&fcs.rh);
3428 	}
3429 	schedule_timeout_uninterruptible(HZ / 10); /* Let kthreads recover. */
3430 	atomic_dec(&rcu_fwd_cb_nodelay);
3431 }
3432 
3433 /* Carry out call_rcu() forward-progress testing. */
3434 static void rcu_torture_fwd_prog_cr(struct rcu_fwd *rfp)
3435 {
3436 	unsigned long cver;
3437 	unsigned long flags;
3438 	unsigned long gps;
3439 	int i;
3440 	long n_launders;
3441 	long n_launders_cb_snap;
3442 	long n_launders_sa;
3443 	long n_max_cbs;
3444 	long n_max_gps;
3445 	struct rcu_fwd_cb *rfcp;
3446 	struct rcu_fwd_cb *rfcpn;
3447 	unsigned long stopat;
3448 	unsigned long stoppedat;
3449 
3450 	pr_alert("%s: Starting forward-progress test %d\n", __func__, rfp->rcu_fwd_id);
3451 	if (READ_ONCE(rcu_fwd_emergency_stop))
3452 		return; /* Get out of the way quickly, no GP wait! */
3453 	if (!cur_ops->call)
3454 		return; /* Can't do call_rcu() fwd prog without ->call. */
3455 
3456 	/* Loop continuously posting RCU callbacks. */
3457 	atomic_inc(&rcu_fwd_cb_nodelay);
3458 	cur_ops->sync(); /* Later readers see above write. */
3459 	WRITE_ONCE(rfp->rcu_fwd_startat, jiffies);
3460 	stopat = rfp->rcu_fwd_startat + MAX_FWD_CB_JIFFIES;
3461 	n_launders = 0;
3462 	rfp->n_launders_cb = 0; // Hoist initialization for multi-kthread
3463 	n_launders_sa = 0;
3464 	n_max_cbs = 0;
3465 	n_max_gps = 0;
3466 	for (i = 0; i < ARRAY_SIZE(rfp->n_launders_hist); i++)
3467 		rfp->n_launders_hist[i].n_launders = 0;
3468 	cver = READ_ONCE(rcu_torture_current_version);
3469 	gps = cur_ops->get_gp_seq();
3470 	rfp->rcu_launder_gp_seq_start = gps;
3471 	tick_dep_set_task(current, TICK_DEP_BIT_RCU);  // CPU bound, so need tick.
3472 	while (time_before(jiffies, stopat) &&
3473 	       !shutdown_time_arrived() &&
3474 	       !READ_ONCE(rcu_fwd_emergency_stop) && !torture_must_stop()) {
3475 		rfcp = READ_ONCE(rfp->rcu_fwd_cb_head);
3476 		rfcpn = NULL;
3477 		if (rfcp)
3478 			rfcpn = READ_ONCE(rfcp->rfc_next);
3479 		if (rfcpn) {
3480 			if (rfcp->rfc_gps >= MIN_FWD_CB_LAUNDERS &&
3481 			    ++n_max_gps >= MIN_FWD_CBS_LAUNDERED)
3482 				break;
3483 			rfp->rcu_fwd_cb_head = rfcpn;
3484 			n_launders++;
3485 			n_launders_sa++;
3486 		} else if (!cur_ops->cbflood_max || cur_ops->cbflood_max > n_max_cbs) {
3487 			rfcp = kmalloc_obj(*rfcp);
3488 			if (WARN_ON_ONCE(!rfcp)) {
3489 				schedule_timeout_interruptible(1);
3490 				continue;
3491 			}
3492 			n_max_cbs++;
3493 			n_launders_sa = 0;
3494 			rfcp->rfc_gps = 0;
3495 			rfcp->rfc_rfp = rfp;
3496 		} else {
3497 			rfcp = NULL;
3498 		}
3499 		if (rfcp)
3500 			cur_ops->call(&rfcp->rh, rcu_torture_fwd_cb_cr);
3501 		rcu_torture_fwd_prog_cond_resched(n_launders + n_max_cbs);
3502 		if (tick_nohz_full_enabled()) {
3503 			local_irq_save(flags);
3504 			rcu_momentary_eqs();
3505 			local_irq_restore(flags);
3506 		}
3507 	}
3508 	stoppedat = jiffies;
3509 	n_launders_cb_snap = READ_ONCE(rfp->n_launders_cb);
3510 	cver = READ_ONCE(rcu_torture_current_version) - cver;
3511 	gps = rcutorture_seq_diff(cur_ops->get_gp_seq(), gps);
3512 	pr_alert("%s: Waiting for CBs: %pS() %d\n", __func__, cur_ops->cb_barrier, rfp->rcu_fwd_id);
3513 	cur_ops->cb_barrier(); /* Wait for callbacks to be invoked. */
3514 	(void)rcu_torture_fwd_prog_cbfree(rfp);
3515 
3516 	if (!torture_must_stop() && !READ_ONCE(rcu_fwd_emergency_stop) &&
3517 	    !shutdown_time_arrived()) {
3518 		if (WARN_ON(n_max_gps < MIN_FWD_CBS_LAUNDERED) && cur_ops->gp_kthread_dbg)
3519 			cur_ops->gp_kthread_dbg();
3520 		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 #online %u\n",
3521 			 __func__,
3522 			 stoppedat - rfp->rcu_fwd_startat, jiffies - stoppedat,
3523 			 n_launders + n_max_cbs - n_launders_cb_snap,
3524 			 n_launders, n_launders_sa,
3525 			 n_max_gps, n_max_cbs, cver, gps, num_online_cpus());
3526 		atomic_long_add(n_max_cbs, &rcu_fwd_max_cbs);
3527 		mutex_lock(&rcu_fwd_mutex); // Serialize histograms.
3528 		rcu_torture_fwd_cb_hist(rfp);
3529 		mutex_unlock(&rcu_fwd_mutex);
3530 	}
3531 	schedule_timeout_uninterruptible(HZ); /* Let CBs drain. */
3532 	tick_dep_clear_task(current, TICK_DEP_BIT_RCU);
3533 	atomic_dec(&rcu_fwd_cb_nodelay);
3534 }
3535 
3536 
3537 /*
3538  * OOM notifier, but this only prints diagnostic information for the
3539  * current forward-progress test.
3540  */
3541 static int rcutorture_oom_notify(struct notifier_block *self,
3542 				 unsigned long notused, void *nfreed)
3543 {
3544 	int i;
3545 	long ncbs;
3546 	struct rcu_fwd *rfp;
3547 
3548 	mutex_lock(&rcu_fwd_mutex);
3549 	rfp = rcu_fwds;
3550 	if (!rfp) {
3551 		mutex_unlock(&rcu_fwd_mutex);
3552 		return NOTIFY_OK;
3553 	}
3554 	WARN(1, "%s invoked upon OOM during forward-progress testing.\n",
3555 	     __func__);
3556 	for (i = 0; i < fwd_progress; i++) {
3557 		rcu_torture_fwd_cb_hist(&rfp[i]);
3558 		rcu_fwd_progress_check(1 + (jiffies - READ_ONCE(rfp[i].rcu_fwd_startat)) / 2);
3559 	}
3560 	WRITE_ONCE(rcu_fwd_emergency_stop, true);
3561 	smp_mb(); /* Emergency stop before free and wait to avoid hangs. */
3562 	ncbs = 0;
3563 	for (i = 0; i < fwd_progress; i++)
3564 		ncbs += rcu_torture_fwd_prog_cbfree(&rfp[i]);
3565 	pr_info("%s: Freed %lu RCU callbacks.\n", __func__, ncbs);
3566 	cur_ops->cb_barrier();
3567 	ncbs = 0;
3568 	for (i = 0; i < fwd_progress; i++)
3569 		ncbs += rcu_torture_fwd_prog_cbfree(&rfp[i]);
3570 	pr_info("%s: Freed %lu RCU callbacks.\n", __func__, ncbs);
3571 	cur_ops->cb_barrier();
3572 	ncbs = 0;
3573 	for (i = 0; i < fwd_progress; i++)
3574 		ncbs += rcu_torture_fwd_prog_cbfree(&rfp[i]);
3575 	pr_info("%s: Freed %lu RCU callbacks.\n", __func__, ncbs);
3576 	smp_mb(); /* Frees before return to avoid redoing OOM. */
3577 	(*(unsigned long *)nfreed)++; /* Forward progress CBs freed! */
3578 	pr_info("%s returning after OOM processing.\n", __func__);
3579 	mutex_unlock(&rcu_fwd_mutex);
3580 	return NOTIFY_OK;
3581 }
3582 
3583 static struct notifier_block rcutorture_oom_nb = {
3584 	.notifier_call = rcutorture_oom_notify
3585 };
3586 
3587 /* Carry out grace-period forward-progress testing. */
3588 static int rcu_torture_fwd_prog(void *args)
3589 {
3590 	bool firsttime = true;
3591 	long max_cbs;
3592 	int oldnice = task_nice(current);
3593 	unsigned long oldseq = READ_ONCE(rcu_fwd_seq);
3594 	struct rcu_fwd *rfp = args;
3595 	int tested = 0;
3596 	int tested_tries = 0;
3597 
3598 	VERBOSE_TOROUT_STRING("rcu_torture_fwd_progress task started");
3599 	while (!rcu_inkernel_boot_has_ended())
3600 		schedule_timeout_interruptible(HZ / 10);
3601 	rcu_bind_current_to_nocb();
3602 	if (!IS_ENABLED(CONFIG_SMP) || !IS_ENABLED(CONFIG_RCU_BOOST))
3603 		set_user_nice(current, MAX_NICE);
3604 	do {
3605 		if (!rfp->rcu_fwd_id) {
3606 			schedule_timeout_interruptible(fwd_progress_holdoff * HZ);
3607 			WRITE_ONCE(rcu_fwd_emergency_stop, false);
3608 			if (!firsttime) {
3609 				max_cbs = atomic_long_xchg(&rcu_fwd_max_cbs, 0);
3610 				pr_alert("%s n_max_cbs: %ld\n", __func__, max_cbs);
3611 			}
3612 			firsttime = false;
3613 			WRITE_ONCE(rcu_fwd_seq, rcu_fwd_seq + 1);
3614 		} else {
3615 			while (READ_ONCE(rcu_fwd_seq) == oldseq && !torture_must_stop())
3616 				schedule_timeout_interruptible(HZ / 20);
3617 			oldseq = READ_ONCE(rcu_fwd_seq);
3618 		}
3619 		pr_alert("%s: Starting forward-progress test %d\n", __func__, rfp->rcu_fwd_id);
3620 		if (rcu_inkernel_boot_has_ended() && torture_num_online_cpus() > rfp->rcu_fwd_id)
3621 			rcu_torture_fwd_prog_cr(rfp);
3622 		if ((cur_ops->stall_dur && cur_ops->stall_dur() > 0) &&
3623 		    (!IS_ENABLED(CONFIG_TINY_RCU) ||
3624 		     (rcu_inkernel_boot_has_ended() &&
3625 		      torture_num_online_cpus() > rfp->rcu_fwd_id)))
3626 			rcu_torture_fwd_prog_nr(rfp, &tested, &tested_tries);
3627 
3628 		/* Avoid slow periods, better to test when busy. */
3629 		if (stutter_wait("rcu_torture_fwd_prog"))
3630 			sched_set_normal(current, oldnice);
3631 	} while (!torture_must_stop());
3632 	/* Short runs might not contain a valid forward-progress attempt. */
3633 	if (!rfp->rcu_fwd_id) {
3634 		WARN_ON(!tested && tested_tries >= 5);
3635 		pr_alert("%s: tested %d tested_tries %d\n", __func__, tested, tested_tries);
3636 	}
3637 	torture_kthread_stopping("rcu_torture_fwd_prog");
3638 	return 0;
3639 }
3640 
3641 /* If forward-progress checking is requested and feasible, spawn the thread. */
3642 static int __init rcu_torture_fwd_prog_init(void)
3643 {
3644 	int i;
3645 	int ret = 0;
3646 	struct rcu_fwd *rfp;
3647 
3648 	if (!fwd_progress)
3649 		return 0; /* Not requested, so don't do it. */
3650 	if (fwd_progress >= nr_cpu_ids) {
3651 		VERBOSE_TOROUT_STRING("rcu_torture_fwd_prog_init: Limiting fwd_progress to # CPUs.\n");
3652 		fwd_progress = nr_cpu_ids;
3653 	} else if (fwd_progress < 0) {
3654 		fwd_progress = nr_cpu_ids;
3655 	}
3656 	if ((!cur_ops->sync && !cur_ops->call) ||
3657 	    (!cur_ops->cbflood_max && (!cur_ops->stall_dur || cur_ops->stall_dur() <= 0)) ||
3658 	    cur_ops == &rcu_busted_ops) {
3659 		VERBOSE_TOROUT_STRING("rcu_torture_fwd_prog_init: Disabled, unsupported by RCU flavor under test");
3660 		fwd_progress = 0;
3661 		return 0;
3662 	}
3663 	if (stall_cpu > 0 || (preempt_duration > 0 && IS_ENABLED(CONFIG_RCU_NOCB_CPU))) {
3664 		VERBOSE_TOROUT_STRING("rcu_torture_fwd_prog_init: Disabled, conflicts with CPU-stall and/or preemption testing");
3665 		fwd_progress = 0;
3666 		if (IS_MODULE(CONFIG_RCU_TORTURE_TEST))
3667 			return -EINVAL; /* In module, can fail back to user. */
3668 		WARN_ON(1); /* Make sure rcutorture scripting notices conflict. */
3669 		return 0;
3670 	}
3671 	if (fwd_progress_holdoff <= 0)
3672 		fwd_progress_holdoff = 1;
3673 	if (fwd_progress_div <= 0)
3674 		fwd_progress_div = 4;
3675 	rfp = kzalloc_objs(*rfp, fwd_progress);
3676 	fwd_prog_tasks = kzalloc_objs(*fwd_prog_tasks, fwd_progress);
3677 	if (!rfp || !fwd_prog_tasks) {
3678 		kfree(rfp);
3679 		kfree(fwd_prog_tasks);
3680 		fwd_prog_tasks = NULL;
3681 		fwd_progress = 0;
3682 		return -ENOMEM;
3683 	}
3684 	for (i = 0; i < fwd_progress; i++) {
3685 		spin_lock_init(&rfp[i].rcu_fwd_lock);
3686 		rfp[i].rcu_fwd_cb_tail = &rfp[i].rcu_fwd_cb_head;
3687 		rfp[i].rcu_fwd_id = i;
3688 	}
3689 	mutex_lock(&rcu_fwd_mutex);
3690 	rcu_fwds = rfp;
3691 	mutex_unlock(&rcu_fwd_mutex);
3692 	register_oom_notifier(&rcutorture_oom_nb);
3693 	for (i = 0; i < fwd_progress; i++) {
3694 		ret = torture_create_kthread(rcu_torture_fwd_prog, &rcu_fwds[i], fwd_prog_tasks[i]);
3695 		if (ret) {
3696 			fwd_progress = i;
3697 			return ret;
3698 		}
3699 	}
3700 	return 0;
3701 }
3702 
3703 static void rcu_torture_fwd_prog_cleanup(void)
3704 {
3705 	int i;
3706 	struct rcu_fwd *rfp;
3707 
3708 	if (!rcu_fwds || !fwd_prog_tasks)
3709 		return;
3710 	for (i = 0; i < fwd_progress; i++)
3711 		torture_stop_kthread(rcu_torture_fwd_prog, fwd_prog_tasks[i]);
3712 	unregister_oom_notifier(&rcutorture_oom_nb);
3713 	mutex_lock(&rcu_fwd_mutex);
3714 	rfp = rcu_fwds;
3715 	rcu_fwds = NULL;
3716 	mutex_unlock(&rcu_fwd_mutex);
3717 	kfree(rfp);
3718 	kfree(fwd_prog_tasks);
3719 	fwd_prog_tasks = NULL;
3720 }
3721 
3722 /* Callback function for RCU barrier testing. */
3723 static void rcu_torture_barrier_cbf(struct rcu_head *rcu)
3724 {
3725 	atomic_inc(&barrier_cbs_invoked);
3726 }
3727 
3728 /* IPI handler to get callback posted on desired CPU, if online. */
3729 static int rcu_torture_barrier1cb(void *rcu_void)
3730 {
3731 	struct rcu_head *rhp = rcu_void;
3732 
3733 	cur_ops->call(rhp, rcu_torture_barrier_cbf);
3734 	return 0;
3735 }
3736 
3737 /* kthread function to register callbacks used to test RCU barriers. */
3738 static int rcu_torture_barrier_cbs(void *arg)
3739 {
3740 	long myid = (long)arg;
3741 	bool lastphase = false;
3742 	bool newphase;
3743 	struct rcu_head rcu;
3744 
3745 	init_rcu_head_on_stack(&rcu);
3746 	VERBOSE_TOROUT_STRING("rcu_torture_barrier_cbs task started");
3747 	set_user_nice(current, MAX_NICE);
3748 	do {
3749 		wait_event(barrier_cbs_wq[myid],
3750 			   (newphase =
3751 			    smp_load_acquire(&barrier_phase)) != lastphase ||
3752 			   torture_must_stop());
3753 		lastphase = newphase;
3754 		if (torture_must_stop())
3755 			break;
3756 		/*
3757 		 * The above smp_load_acquire() ensures barrier_phase load
3758 		 * is ordered before the following ->call().
3759 		 */
3760 		if (smp_call_on_cpu(myid, rcu_torture_barrier1cb, &rcu, 1))
3761 			cur_ops->call(&rcu, rcu_torture_barrier_cbf);
3762 
3763 		if (atomic_dec_and_test(&barrier_cbs_count))
3764 			wake_up(&barrier_wq);
3765 	} while (!torture_must_stop());
3766 	if (cur_ops->cb_barrier != NULL)
3767 		cur_ops->cb_barrier();
3768 	destroy_rcu_head_on_stack(&rcu);
3769 	torture_kthread_stopping("rcu_torture_barrier_cbs");
3770 	return 0;
3771 }
3772 
3773 /* kthread function to drive and coordinate RCU barrier testing. */
3774 static int rcu_torture_barrier(void *arg)
3775 {
3776 	int i;
3777 
3778 	VERBOSE_TOROUT_STRING("rcu_torture_barrier task starting");
3779 	do {
3780 		atomic_set(&barrier_cbs_invoked, 0);
3781 		atomic_set(&barrier_cbs_count, n_barrier_cbs);
3782 		/* Ensure barrier_phase ordered after prior assignments. */
3783 		smp_store_release(&barrier_phase, !barrier_phase);
3784 		for (i = 0; i < n_barrier_cbs; i++)
3785 			wake_up(&barrier_cbs_wq[i]);
3786 		wait_event(barrier_wq,
3787 			   atomic_read(&barrier_cbs_count) == 0 ||
3788 			   torture_must_stop());
3789 		if (torture_must_stop())
3790 			break;
3791 		n_barrier_attempts++;
3792 		cur_ops->cb_barrier(); /* Implies smp_mb() for wait_event(). */
3793 		if (atomic_read(&barrier_cbs_invoked) != n_barrier_cbs) {
3794 			n_rcu_torture_barrier_error++;
3795 			pr_err("barrier_cbs_invoked = %d, n_barrier_cbs = %d\n",
3796 			       atomic_read(&barrier_cbs_invoked),
3797 			       n_barrier_cbs);
3798 			WARN_ON(1);
3799 			// Wait manually for the remaining callbacks
3800 			i = 0;
3801 			do {
3802 				if (WARN_ON(i++ > HZ))
3803 					i = INT_MIN;
3804 				schedule_timeout_interruptible(1);
3805 				cur_ops->cb_barrier();
3806 			} while (atomic_read(&barrier_cbs_invoked) !=
3807 				 n_barrier_cbs &&
3808 				 !torture_must_stop());
3809 			smp_mb(); // Can't trust ordering if broken.
3810 			if (!torture_must_stop())
3811 				pr_err("Recovered: barrier_cbs_invoked = %d\n",
3812 				       atomic_read(&barrier_cbs_invoked));
3813 		} else {
3814 			n_barrier_successes++;
3815 		}
3816 		schedule_timeout_interruptible(HZ / 10);
3817 	} while (!torture_must_stop());
3818 	torture_kthread_stopping("rcu_torture_barrier");
3819 	return 0;
3820 }
3821 
3822 /* Initialize RCU barrier testing. */
3823 static int rcu_torture_barrier_init(void)
3824 {
3825 	int i;
3826 	int ret;
3827 
3828 	if (n_barrier_cbs <= 0)
3829 		return 0;
3830 	if (cur_ops->call == NULL || cur_ops->cb_barrier == NULL) {
3831 		pr_alert("%s" TORTURE_FLAG
3832 			 " Call or barrier ops missing for %s,\n",
3833 			 torture_type, cur_ops->name);
3834 		pr_alert("%s" TORTURE_FLAG
3835 			 " RCU barrier testing omitted from run.\n",
3836 			 torture_type);
3837 		return 0;
3838 	}
3839 	atomic_set(&barrier_cbs_count, 0);
3840 	atomic_set(&barrier_cbs_invoked, 0);
3841 	barrier_cbs_tasks =
3842 		kzalloc_objs(barrier_cbs_tasks[0], n_barrier_cbs);
3843 	barrier_cbs_wq =
3844 		kzalloc_objs(barrier_cbs_wq[0], n_barrier_cbs);
3845 	if (barrier_cbs_tasks == NULL || !barrier_cbs_wq)
3846 		return -ENOMEM;
3847 	for (i = 0; i < n_barrier_cbs; i++) {
3848 		init_waitqueue_head(&barrier_cbs_wq[i]);
3849 		ret = torture_create_kthread(rcu_torture_barrier_cbs,
3850 					     (void *)(long)i,
3851 					     barrier_cbs_tasks[i]);
3852 		if (ret)
3853 			return ret;
3854 	}
3855 	return torture_create_kthread(rcu_torture_barrier, NULL, barrier_task);
3856 }
3857 
3858 /* Clean up after RCU barrier testing. */
3859 static void rcu_torture_barrier_cleanup(void)
3860 {
3861 	int i;
3862 
3863 	torture_stop_kthread(rcu_torture_barrier, barrier_task);
3864 	if (barrier_cbs_tasks != NULL) {
3865 		for (i = 0; i < n_barrier_cbs; i++)
3866 			torture_stop_kthread(rcu_torture_barrier_cbs,
3867 					     barrier_cbs_tasks[i]);
3868 		kfree(barrier_cbs_tasks);
3869 		barrier_cbs_tasks = NULL;
3870 	}
3871 	if (barrier_cbs_wq != NULL) {
3872 		kfree(barrier_cbs_wq);
3873 		barrier_cbs_wq = NULL;
3874 	}
3875 }
3876 
3877 static bool rcu_torture_can_boost(void)
3878 {
3879 	static int boost_warn_once;
3880 	int prio;
3881 
3882 	if (!(test_boost == 1 && cur_ops->can_boost) && test_boost != 2)
3883 		return false;
3884 	if (!cur_ops->start_gp_poll || !cur_ops->poll_gp_state)
3885 		return false;
3886 
3887 	prio = rcu_get_gp_kthreads_prio();
3888 	if (!prio)
3889 		return false;
3890 
3891 	if (prio < 2) {
3892 		if (boost_warn_once == 1)
3893 			return false;
3894 
3895 		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);
3896 		boost_warn_once = 1;
3897 		return false;
3898 	}
3899 
3900 	return true;
3901 }
3902 
3903 static bool read_exit_child_stop;
3904 static bool read_exit_child_stopped;
3905 static wait_queue_head_t read_exit_wq;
3906 
3907 // Child kthread which just does an rcutorture reader and exits.
3908 static int rcu_torture_read_exit_child(void *trsp_in)
3909 {
3910 	struct torture_random_state *trsp = trsp_in;
3911 
3912 	set_user_nice(current, MAX_NICE);
3913 	// Minimize time between reading and exiting.
3914 	while (!kthread_should_stop())
3915 		schedule_timeout_uninterruptible(HZ / 20);
3916 	(void)rcu_torture_one_read(trsp, -1);
3917 	return 0;
3918 }
3919 
3920 // Parent kthread which creates and destroys read-exit child kthreads.
3921 static int rcu_torture_read_exit(void *unused)
3922 {
3923 	bool errexit = false;
3924 	int i;
3925 	struct task_struct *tsp;
3926 	DEFINE_TORTURE_RANDOM(trs);
3927 
3928 	// Allocate and initialize.
3929 	set_user_nice(current, MAX_NICE);
3930 	VERBOSE_TOROUT_STRING("rcu_torture_read_exit: Start of test");
3931 
3932 	// Each pass through this loop does one read-exit episode.
3933 	do {
3934 		VERBOSE_TOROUT_STRING("rcu_torture_read_exit: Start of episode");
3935 		for (i = 0; i < read_exit_burst; i++) {
3936 			if (READ_ONCE(read_exit_child_stop))
3937 				break;
3938 			stutter_wait("rcu_torture_read_exit");
3939 			// Spawn child.
3940 			tsp = kthread_run(rcu_torture_read_exit_child,
3941 					  &trs, "%s", "rcu_torture_read_exit_child");
3942 			if (IS_ERR(tsp)) {
3943 				TOROUT_ERRSTRING("out of memory");
3944 				errexit = true;
3945 				break;
3946 			}
3947 			cond_resched();
3948 			kthread_stop(tsp);
3949 			n_read_exits++;
3950 		}
3951 		VERBOSE_TOROUT_STRING("rcu_torture_read_exit: End of episode");
3952 		rcu_barrier(); // Wait for task_struct free, avoid OOM.
3953 		i = 0;
3954 		for (; !errexit && !READ_ONCE(read_exit_child_stop) && i < read_exit_delay; i++)
3955 			schedule_timeout_uninterruptible(HZ);
3956 	} while (!errexit && !READ_ONCE(read_exit_child_stop));
3957 
3958 	// Clean up and exit.
3959 	smp_store_release(&read_exit_child_stopped, true); // After reaping.
3960 	smp_mb(); // Store before wakeup.
3961 	wake_up(&read_exit_wq);
3962 	while (!torture_must_stop())
3963 		schedule_timeout_uninterruptible(HZ / 20);
3964 	torture_kthread_stopping("rcu_torture_read_exit");
3965 	return 0;
3966 }
3967 
3968 static int rcu_torture_read_exit_init(void)
3969 {
3970 	if (read_exit_burst <= 0)
3971 		return 0;
3972 	init_waitqueue_head(&read_exit_wq);
3973 	read_exit_child_stop = false;
3974 	read_exit_child_stopped = false;
3975 	return torture_create_kthread(rcu_torture_read_exit, NULL,
3976 				      read_exit_task);
3977 }
3978 
3979 static void rcu_torture_read_exit_cleanup(void)
3980 {
3981 	if (!read_exit_task)
3982 		return;
3983 	WRITE_ONCE(read_exit_child_stop, true);
3984 	smp_mb(); // Above write before wait.
3985 	wait_event(read_exit_wq, smp_load_acquire(&read_exit_child_stopped));
3986 	torture_stop_kthread(rcutorture_read_exit, read_exit_task);
3987 }
3988 
3989 static void rcutorture_test_nmis(int n)
3990 {
3991 #if IS_BUILTIN(CONFIG_RCU_TORTURE_TEST)
3992 	int cpu;
3993 	int dumpcpu;
3994 	int i;
3995 
3996 	for (i = 0; i < n; i++) {
3997 		preempt_disable();
3998 		cpu = smp_processor_id();
3999 		dumpcpu = cpu + 1;
4000 		if (dumpcpu >= nr_cpu_ids)
4001 			dumpcpu = 0;
4002 		pr_alert("%s: CPU %d invoking dump_cpu_task(%d)\n", __func__, cpu, dumpcpu);
4003 		dump_cpu_task(dumpcpu);
4004 		preempt_enable();
4005 		schedule_timeout_uninterruptible(15 * HZ);
4006 	}
4007 #else // #if IS_BUILTIN(CONFIG_RCU_TORTURE_TEST)
4008 	WARN_ONCE(n, "Non-zero rcutorture.test_nmis=%d permitted only when rcutorture is built in.\n", test_nmis);
4009 #endif // #else // #if IS_BUILTIN(CONFIG_RCU_TORTURE_TEST)
4010 }
4011 
4012 // Randomly preempt online CPUs.
4013 static int rcu_torture_preempt(void *unused)
4014 {
4015 	int cpu = -1;
4016 	DEFINE_TORTURE_RANDOM(rand);
4017 
4018 	schedule_timeout_idle(stall_cpu_holdoff);
4019 	do {
4020 		// Wait for preempt_interval ms with up to 100us fuzz.
4021 		torture_hrtimeout_ms(preempt_interval, 100, &rand);
4022 		// Select online CPU.
4023 		cpu = cpumask_next(cpu, cpu_online_mask);
4024 		if (cpu >= nr_cpu_ids)
4025 			cpu = cpumask_next(-1, cpu_online_mask);
4026 		WARN_ON_ONCE(cpu >= nr_cpu_ids);
4027 		// Move to that CPU, if can't do so, retry later.
4028 		if (torture_sched_setaffinity(current->pid, cpumask_of(cpu), false))
4029 			continue;
4030 		// Preempt at high-ish priority, then reset to normal.
4031 		sched_set_fifo(current);
4032 		torture_sched_setaffinity(current->pid, cpu_present_mask, true);
4033 		mdelay(preempt_duration);
4034 		sched_set_normal(current, 0);
4035 		stutter_wait("rcu_torture_preempt");
4036 	} while (!torture_must_stop());
4037 	torture_kthread_stopping("rcu_torture_preempt");
4038 	return 0;
4039 }
4040 
4041 static enum cpuhp_state rcutor_hp;
4042 
4043 static struct hrtimer gpwrap_lag_timer;
4044 static bool gpwrap_lag_active;
4045 
4046 /* Timer handler for toggling RCU grace-period sequence overflow test lag value */
4047 static enum hrtimer_restart rcu_gpwrap_lag_timer(struct hrtimer *timer)
4048 {
4049 	ktime_t next_delay;
4050 
4051 	if (gpwrap_lag_active) {
4052 		pr_alert("rcu-torture: Disabling gpwrap lag (value=0)\n");
4053 		cur_ops->set_gpwrap_lag(0);
4054 		gpwrap_lag_active = false;
4055 		next_delay = ktime_set((gpwrap_lag_cycle_mins - gpwrap_lag_active_mins) * 60, 0);
4056 	} else {
4057 		pr_alert("rcu-torture: Enabling gpwrap lag (value=%d)\n", gpwrap_lag_gps);
4058 		cur_ops->set_gpwrap_lag(gpwrap_lag_gps);
4059 		gpwrap_lag_active = true;
4060 		next_delay = ktime_set(gpwrap_lag_active_mins * 60, 0);
4061 	}
4062 
4063 	if (torture_must_stop_irq())
4064 		return HRTIMER_NORESTART;
4065 
4066 	hrtimer_forward_now(timer, next_delay);
4067 	return HRTIMER_RESTART;
4068 }
4069 
4070 static int rcu_gpwrap_lag_init(void)
4071 {
4072 	if (!gpwrap_lag)
4073 		return 0;
4074 
4075 	if (gpwrap_lag_cycle_mins <= 0 || gpwrap_lag_active_mins <= 0) {
4076 		pr_alert("rcu-torture: lag timing parameters must be positive\n");
4077 		return -EINVAL;
4078 	}
4079 
4080 	hrtimer_setup(&gpwrap_lag_timer, rcu_gpwrap_lag_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
4081 	gpwrap_lag_active = false;
4082 	hrtimer_start(&gpwrap_lag_timer,
4083 		      ktime_set((gpwrap_lag_cycle_mins - gpwrap_lag_active_mins) * 60, 0), HRTIMER_MODE_REL);
4084 
4085 	return 0;
4086 }
4087 
4088 static void rcu_gpwrap_lag_cleanup(void)
4089 {
4090 	hrtimer_cancel(&gpwrap_lag_timer);
4091 	cur_ops->set_gpwrap_lag(0);
4092 	gpwrap_lag_active = false;
4093 }
4094 static void
4095 rcu_torture_cleanup(void)
4096 {
4097 	int firsttime;
4098 	int flags = 0;
4099 	unsigned long gp_seq = 0;
4100 	int i;
4101 	int j;
4102 
4103 	if (torture_cleanup_begin()) {
4104 		if (cur_ops->cb_barrier != NULL) {
4105 			pr_info("%s: Invoking %pS().\n", __func__, cur_ops->cb_barrier);
4106 			cur_ops->cb_barrier();
4107 		}
4108 		if (cur_ops->gp_slow_unregister)
4109 			cur_ops->gp_slow_unregister(NULL);
4110 		return;
4111 	}
4112 	if (!cur_ops) {
4113 		torture_cleanup_end();
4114 		return;
4115 	}
4116 
4117 	rcutorture_test_nmis(test_nmis);
4118 
4119 	if (cur_ops->gp_kthread_dbg)
4120 		cur_ops->gp_kthread_dbg();
4121 	torture_stop_kthread(rcu_torture_preempt, preempt_task);
4122 	rcu_torture_read_exit_cleanup();
4123 	rcu_torture_barrier_cleanup();
4124 	rcu_torture_fwd_prog_cleanup();
4125 	torture_stop_kthread(rcu_torture_stall, stall_task);
4126 	torture_stop_kthread(rcu_torture_writer, writer_task);
4127 
4128 	if (nocb_tasks) {
4129 		for (i = 0; i < nrealnocbers; i++)
4130 			torture_stop_kthread(rcu_nocb_toggle, nocb_tasks[i]);
4131 		kfree(nocb_tasks);
4132 		nocb_tasks = NULL;
4133 	}
4134 
4135 	if (updown_task) {
4136 		torture_stop_kthread(rcu_torture_updown, updown_task);
4137 		updown_task = NULL;
4138 	}
4139 	if (reader_tasks) {
4140 		for (i = 0; i < nrealreaders; i++)
4141 			torture_stop_kthread(rcu_torture_reader,
4142 					     reader_tasks[i]);
4143 		kfree(reader_tasks);
4144 		reader_tasks = NULL;
4145 	}
4146 	kfree(rcu_torture_reader_mbchk);
4147 	rcu_torture_reader_mbchk = NULL;
4148 
4149 	if (fakewriter_tasks) {
4150 		for (i = 0; i < nrealfakewriters; i++)
4151 			torture_stop_kthread(rcu_torture_fakewriter,
4152 					     fakewriter_tasks[i]);
4153 		kfree(fakewriter_tasks);
4154 		fakewriter_tasks = NULL;
4155 	}
4156 
4157 	if (cur_ops->get_gp_data)
4158 		cur_ops->get_gp_data(&flags, &gp_seq);
4159 	pr_alert("%s:  End-test grace-period state: g%ld f%#x total-gps=%ld\n",
4160 		 cur_ops->name, (long)gp_seq, flags,
4161 		 rcutorture_seq_diff(gp_seq, start_gp_seq));
4162 	torture_stop_kthread(rcu_torture_stats, stats_task);
4163 	torture_stop_kthread(rcu_torture_fqs, fqs_task);
4164 	if (rcu_torture_can_boost() && rcutor_hp >= 0)
4165 		cpuhp_remove_state(rcutor_hp);
4166 
4167 	/*
4168 	 * Wait for all RCU callbacks to fire, then do torture-type-specific
4169 	 * cleanup operations.
4170 	 */
4171 	if (cur_ops->cb_barrier != NULL) {
4172 		pr_info("%s: Invoking %pS().\n", __func__, cur_ops->cb_barrier);
4173 		cur_ops->cb_barrier();
4174 	}
4175 	if (cur_ops->cleanup != NULL)
4176 		cur_ops->cleanup();
4177 
4178 	rcu_torture_mem_dump_obj();
4179 
4180 	rcu_torture_stats_print();  /* -After- the stats thread is stopped! */
4181 
4182 	if (err_segs_recorded) {
4183 		pr_alert("Failure/close-call rcutorture reader segments:\n");
4184 		if (rt_read_nsegs == 0)
4185 			pr_alert("\t: No segments recorded!!!\n");
4186 		firsttime = 1;
4187 		for (i = 0; i < rt_read_nsegs; i++) {
4188 			if (IS_ENABLED(CONFIG_RCU_TORTURE_TEST_LOG_GP))
4189 				pr_alert("\t%lluus ", div64_u64(err_segs[i].rt_ts, 1000ULL));
4190 			else
4191 				pr_alert("\t");
4192 			pr_cont("%d: %#4x", i, err_segs[i].rt_readstate);
4193 			if (err_segs[i].rt_delay_jiffies != 0) {
4194 				pr_cont("%s%ldjiffies", firsttime ? "" : "+",
4195 					err_segs[i].rt_delay_jiffies);
4196 				firsttime = 0;
4197 			}
4198 			if (IS_ENABLED(CONFIG_RCU_TORTURE_TEST_LOG_CPU)) {
4199 				pr_cont(" CPU %2d", err_segs[i].rt_cpu);
4200 				if (err_segs[i].rt_cpu != err_segs[i].rt_end_cpu)
4201 					pr_cont("->%-2d", err_segs[i].rt_end_cpu);
4202 				else
4203 					pr_cont(" ...");
4204 			}
4205 			if (IS_ENABLED(CONFIG_RCU_TORTURE_TEST_LOG_GP) &&
4206 			    cur_ops->gather_gp_seqs && cur_ops->format_gp_seqs) {
4207 				char buf1[20+1];
4208 				char buf2[20+1];
4209 				char sepchar = '-';
4210 
4211 				cur_ops->format_gp_seqs(err_segs[i].rt_gp_seq,
4212 							buf1, ARRAY_SIZE(buf1));
4213 				cur_ops->format_gp_seqs(err_segs[i].rt_gp_seq_end,
4214 							buf2, ARRAY_SIZE(buf2));
4215 				if (err_segs[i].rt_gp_seq == err_segs[i].rt_gp_seq_end) {
4216 					if (buf2[0]) {
4217 						for (j = 0; buf2[j]; j++)
4218 							buf2[j] = '.';
4219 						if (j)
4220 							buf2[j - 1] = ' ';
4221 					}
4222 					sepchar = ' ';
4223 				}
4224 				pr_cont(" %s%c%s", buf1, sepchar, buf2);
4225 			}
4226 			if (err_segs[i].rt_delay_ms != 0) {
4227 				pr_cont(" %s%ldms", firsttime ? "" : "+",
4228 					err_segs[i].rt_delay_ms);
4229 				firsttime = 0;
4230 			}
4231 			if (err_segs[i].rt_delay_us != 0) {
4232 				pr_cont(" %s%ldus", firsttime ? "" : "+",
4233 					err_segs[i].rt_delay_us);
4234 				firsttime = 0;
4235 			}
4236 			pr_cont("%s", err_segs[i].rt_preempted ? " preempted" : "");
4237 			if (err_segs[i].rt_readstate & RCUTORTURE_RDR_BH)
4238 				pr_cont(" BH");
4239 			if (err_segs[i].rt_readstate & RCUTORTURE_RDR_IRQ)
4240 				pr_cont(" IRQ");
4241 			if (err_segs[i].rt_readstate & RCUTORTURE_RDR_PREEMPT)
4242 				pr_cont(" PREEMPT");
4243 			if (err_segs[i].rt_readstate & RCUTORTURE_RDR_RBH)
4244 				pr_cont(" RBH");
4245 			if (err_segs[i].rt_readstate & RCUTORTURE_RDR_SCHED)
4246 				pr_cont(" SCHED");
4247 			if (err_segs[i].rt_readstate & RCUTORTURE_RDR_RCU_1)
4248 				pr_cont(" RCU_1");
4249 			if (err_segs[i].rt_readstate & RCUTORTURE_RDR_RCU_2)
4250 				pr_cont(" RCU_2");
4251 			pr_cont("\n");
4252 
4253 		}
4254 		if (rt_read_preempted)
4255 			pr_alert("\tReader was preempted.\n");
4256 	}
4257 	if (atomic_read(&n_rcu_torture_error) || n_rcu_torture_barrier_error)
4258 		rcu_torture_print_module_parms(cur_ops, "End of test: FAILURE");
4259 	else if (torture_onoff_failures())
4260 		rcu_torture_print_module_parms(cur_ops,
4261 					       "End of test: RCU_HOTPLUG");
4262 	else
4263 		rcu_torture_print_module_parms(cur_ops, "End of test: SUCCESS");
4264 	torture_cleanup_end();
4265 	if (cur_ops->gp_slow_unregister)
4266 		cur_ops->gp_slow_unregister(NULL);
4267 
4268 	if (gpwrap_lag && cur_ops->set_gpwrap_lag)
4269 		rcu_gpwrap_lag_cleanup();
4270 }
4271 
4272 static void rcu_torture_leak_cb(struct rcu_head *rhp)
4273 {
4274 }
4275 
4276 static void rcu_torture_err_cb(struct rcu_head *rhp)
4277 {
4278 	/*
4279 	 * This -might- happen due to race conditions, but is unlikely.
4280 	 * The scenario that leads to this happening is that the
4281 	 * first of the pair of duplicate callbacks is queued,
4282 	 * someone else starts a grace period that includes that
4283 	 * callback, then the second of the pair must wait for the
4284 	 * next grace period.  Unlikely, but can happen.  If it
4285 	 * does happen, the debug-objects subsystem won't have splatted.
4286 	 */
4287 	pr_alert("%s: duplicated callback was invoked.\n", KBUILD_MODNAME);
4288 }
4289 
4290 /*
4291  * Verify that double-free causes debug-objects to complain, but only
4292  * if CONFIG_DEBUG_OBJECTS_RCU_HEAD=y.  Otherwise, say that the test
4293  * cannot be carried out.
4294  */
4295 static void rcu_test_debug_objects(void)
4296 {
4297 	struct rcu_head rh1;
4298 	struct rcu_head rh2;
4299 	int idx;
4300 
4301 	if (!IS_ENABLED(CONFIG_DEBUG_OBJECTS_RCU_HEAD)) {
4302 		pr_alert("%s: !CONFIG_DEBUG_OBJECTS_RCU_HEAD, not testing duplicate call_%s()\n",
4303 					KBUILD_MODNAME, cur_ops->name);
4304 		return;
4305 	}
4306 
4307 	if (WARN_ON_ONCE(cur_ops->debug_objects &&
4308 			(!cur_ops->call || !cur_ops->cb_barrier)))
4309 		return;
4310 
4311 	struct rcu_head *rhp = kmalloc_obj(*rhp);
4312 
4313 	init_rcu_head_on_stack(&rh1);
4314 	init_rcu_head_on_stack(&rh2);
4315 	pr_alert("%s: WARN: Duplicate call_%s() test starting.\n", KBUILD_MODNAME, cur_ops->name);
4316 
4317 	/* Try to queue the rh2 pair of callbacks for the same grace period. */
4318 	idx = cur_ops->readlock(); /* Make it impossible to finish a grace period. */
4319 	cur_ops->call(&rh1, rcu_torture_leak_cb); /* Start grace period. */
4320 	cur_ops->call(&rh2, rcu_torture_leak_cb);
4321 	cur_ops->call(&rh2, rcu_torture_err_cb); /* Duplicate callback. */
4322 	if (rhp) {
4323 		cur_ops->call(rhp, rcu_torture_leak_cb);
4324 		cur_ops->call(rhp, rcu_torture_err_cb); /* Another duplicate callback. */
4325 	}
4326 	cur_ops->readunlock(idx);
4327 
4328 	/* Wait for them all to get done so we can safely return. */
4329 	cur_ops->cb_barrier();
4330 	pr_alert("%s: WARN: Duplicate call_%s() test complete.\n", KBUILD_MODNAME, cur_ops->name);
4331 	destroy_rcu_head_on_stack(&rh1);
4332 	destroy_rcu_head_on_stack(&rh2);
4333 	kfree(rhp);
4334 }
4335 
4336 static void rcutorture_sync(void)
4337 {
4338 	static unsigned long n;
4339 
4340 	if (cur_ops->sync && !(++n & 0xfff))
4341 		cur_ops->sync();
4342 }
4343 
4344 static DEFINE_MUTEX(mut0);
4345 static DEFINE_MUTEX(mut1);
4346 static DEFINE_MUTEX(mut2);
4347 static DEFINE_MUTEX(mut3);
4348 static DEFINE_MUTEX(mut4);
4349 static DEFINE_MUTEX(mut5);
4350 static DEFINE_MUTEX(mut6);
4351 static DEFINE_MUTEX(mut7);
4352 static DEFINE_MUTEX(mut8);
4353 static DEFINE_MUTEX(mut9);
4354 
4355 static DECLARE_RWSEM(rwsem0);
4356 static DECLARE_RWSEM(rwsem1);
4357 static DECLARE_RWSEM(rwsem2);
4358 static DECLARE_RWSEM(rwsem3);
4359 static DECLARE_RWSEM(rwsem4);
4360 static DECLARE_RWSEM(rwsem5);
4361 static DECLARE_RWSEM(rwsem6);
4362 static DECLARE_RWSEM(rwsem7);
4363 static DECLARE_RWSEM(rwsem8);
4364 static DECLARE_RWSEM(rwsem9);
4365 
4366 DEFINE_STATIC_SRCU(srcu0);
4367 DEFINE_STATIC_SRCU(srcu1);
4368 DEFINE_STATIC_SRCU(srcu2);
4369 DEFINE_STATIC_SRCU(srcu3);
4370 DEFINE_STATIC_SRCU(srcu4);
4371 DEFINE_STATIC_SRCU(srcu5);
4372 DEFINE_STATIC_SRCU(srcu6);
4373 DEFINE_STATIC_SRCU(srcu7);
4374 DEFINE_STATIC_SRCU(srcu8);
4375 DEFINE_STATIC_SRCU(srcu9);
4376 
4377 static int srcu_lockdep_next(const char *f, const char *fl, const char *fs, const char *fu, int i,
4378 			     int cyclelen, int deadlock)
4379 {
4380 	int j = i + 1;
4381 
4382 	if (j >= cyclelen)
4383 		j = deadlock ? 0 : -1;
4384 	if (j >= 0)
4385 		pr_info("%s: %s(%d), %s(%d), %s(%d)\n", f, fl, i, fs, j, fu, i);
4386 	else
4387 		pr_info("%s: %s(%d), %s(%d)\n", f, fl, i, fu, i);
4388 	return j;
4389 }
4390 
4391 // Test lockdep on SRCU-based deadlock scenarios.
4392 static void rcu_torture_init_srcu_lockdep(void)
4393 {
4394 	int cyclelen;
4395 	int deadlock;
4396 	bool err = false;
4397 	int i;
4398 	int j;
4399 	int idx;
4400 	struct mutex *muts[] = { &mut0, &mut1, &mut2, &mut3, &mut4,
4401 				 &mut5, &mut6, &mut7, &mut8, &mut9 };
4402 	struct rw_semaphore *rwsems[] = { &rwsem0, &rwsem1, &rwsem2, &rwsem3, &rwsem4,
4403 					  &rwsem5, &rwsem6, &rwsem7, &rwsem8, &rwsem9 };
4404 	struct srcu_struct *srcus[] = { &srcu0, &srcu1, &srcu2, &srcu3, &srcu4,
4405 					&srcu5, &srcu6, &srcu7, &srcu8, &srcu9 };
4406 	int testtype;
4407 
4408 	if (!test_srcu_lockdep)
4409 		return;
4410 
4411 	deadlock = test_srcu_lockdep / 1000;
4412 	testtype = (test_srcu_lockdep / 10) % 100;
4413 	cyclelen = test_srcu_lockdep % 10;
4414 	WARN_ON_ONCE(ARRAY_SIZE(muts) != ARRAY_SIZE(srcus));
4415 	if (WARN_ONCE(deadlock != !!deadlock,
4416 		      "%s: test_srcu_lockdep=%d and deadlock digit %d must be zero or one.\n",
4417 		      __func__, test_srcu_lockdep, deadlock))
4418 		err = true;
4419 	if (WARN_ONCE(cyclelen <= 0,
4420 		      "%s: test_srcu_lockdep=%d and cycle-length digit %d must be greater than zero.\n",
4421 		      __func__, test_srcu_lockdep, cyclelen))
4422 		err = true;
4423 	if (err)
4424 		goto err_out;
4425 
4426 	if (testtype == 0) {
4427 		pr_info("%s: test_srcu_lockdep = %05d: SRCU %d-way %sdeadlock.\n",
4428 			__func__, test_srcu_lockdep, cyclelen, deadlock ? "" : "non-");
4429 		if (deadlock && cyclelen == 1)
4430 			pr_info("%s: Expect hang.\n", __func__);
4431 		for (i = 0; i < cyclelen; i++) {
4432 			j = srcu_lockdep_next(__func__, "srcu_read_lock", "synchronize_srcu",
4433 					      "srcu_read_unlock", i, cyclelen, deadlock);
4434 			idx = srcu_read_lock(srcus[i]);
4435 			if (j >= 0)
4436 				synchronize_srcu(srcus[j]);
4437 			srcu_read_unlock(srcus[i], idx);
4438 		}
4439 		return;
4440 	}
4441 
4442 	if (testtype == 1) {
4443 		pr_info("%s: test_srcu_lockdep = %05d: SRCU/mutex %d-way %sdeadlock.\n",
4444 			__func__, test_srcu_lockdep, cyclelen, deadlock ? "" : "non-");
4445 		for (i = 0; i < cyclelen; i++) {
4446 			pr_info("%s: srcu_read_lock(%d), mutex_lock(%d), mutex_unlock(%d), srcu_read_unlock(%d)\n",
4447 				__func__, i, i, i, i);
4448 			idx = srcu_read_lock(srcus[i]);
4449 			mutex_lock(muts[i]);
4450 			mutex_unlock(muts[i]);
4451 			srcu_read_unlock(srcus[i], idx);
4452 
4453 			j = srcu_lockdep_next(__func__, "mutex_lock", "synchronize_srcu",
4454 					      "mutex_unlock", i, cyclelen, deadlock);
4455 			mutex_lock(muts[i]);
4456 			if (j >= 0)
4457 				synchronize_srcu(srcus[j]);
4458 			mutex_unlock(muts[i]);
4459 		}
4460 		return;
4461 	}
4462 
4463 	if (testtype == 2) {
4464 		pr_info("%s: test_srcu_lockdep = %05d: SRCU/rwsem %d-way %sdeadlock.\n",
4465 			__func__, test_srcu_lockdep, cyclelen, deadlock ? "" : "non-");
4466 		for (i = 0; i < cyclelen; i++) {
4467 			pr_info("%s: srcu_read_lock(%d), down_read(%d), up_read(%d), srcu_read_unlock(%d)\n",
4468 				__func__, i, i, i, i);
4469 			idx = srcu_read_lock(srcus[i]);
4470 			down_read(rwsems[i]);
4471 			up_read(rwsems[i]);
4472 			srcu_read_unlock(srcus[i], idx);
4473 
4474 			j = srcu_lockdep_next(__func__, "down_write", "synchronize_srcu",
4475 					      "up_write", i, cyclelen, deadlock);
4476 			down_write(rwsems[i]);
4477 			if (j >= 0)
4478 				synchronize_srcu(srcus[j]);
4479 			up_write(rwsems[i]);
4480 		}
4481 		return;
4482 	}
4483 
4484 #ifdef CONFIG_TASKS_TRACE_RCU
4485 	if (testtype == 3) {
4486 		pr_info("%s: test_srcu_lockdep = %05d: SRCU and Tasks Trace RCU %d-way %sdeadlock.\n",
4487 			__func__, test_srcu_lockdep, cyclelen, deadlock ? "" : "non-");
4488 		if (deadlock && cyclelen == 1)
4489 			pr_info("%s: Expect hang.\n", __func__);
4490 		for (i = 0; i < cyclelen; i++) {
4491 			char *fl = i == 0 ? "rcu_read_lock_trace" : "srcu_read_lock";
4492 			char *fs = i == cyclelen - 1 ? "synchronize_rcu_tasks_trace"
4493 						     : "synchronize_srcu";
4494 			char *fu = i == 0 ? "rcu_read_unlock_trace" : "srcu_read_unlock";
4495 
4496 			j = srcu_lockdep_next(__func__, fl, fs, fu, i, cyclelen, deadlock);
4497 			if (i == 0)
4498 				rcu_read_lock_trace();
4499 			else
4500 				idx = srcu_read_lock(srcus[i]);
4501 			if (j >= 0) {
4502 				if (i == cyclelen - 1)
4503 					synchronize_rcu_tasks_trace();
4504 				else
4505 					synchronize_srcu(srcus[j]);
4506 			}
4507 			if (i == 0)
4508 				rcu_read_unlock_trace();
4509 			else
4510 				srcu_read_unlock(srcus[i], idx);
4511 		}
4512 		return;
4513 	}
4514 #endif // #ifdef CONFIG_TASKS_TRACE_RCU
4515 
4516 err_out:
4517 	pr_info("%s: test_srcu_lockdep = %05d does nothing.\n", __func__, test_srcu_lockdep);
4518 	pr_info("%s: test_srcu_lockdep = DNNL.\n", __func__);
4519 	pr_info("%s: D: Deadlock if nonzero.\n", __func__);
4520 	pr_info("%s: NN: Test number, 0=SRCU, 1=SRCU/mutex, 2=SRCU/rwsem, 3=SRCU/Tasks Trace RCU.\n", __func__);
4521 	pr_info("%s: L: Cycle length.\n", __func__);
4522 	if (!IS_ENABLED(CONFIG_TASKS_TRACE_RCU))
4523 		pr_info("%s: NN=3 disallowed because kernel is built with CONFIG_TASKS_TRACE_RCU=n\n", __func__);
4524 }
4525 
4526 static int __init
4527 rcu_torture_init(void)
4528 {
4529 	long i;
4530 	int cpu;
4531 	int firsterr = 0;
4532 	int flags = 0;
4533 	unsigned long gp_seq = 0;
4534 	static struct rcu_torture_ops *torture_ops[] = {
4535 		&rcu_ops, &rcu_busted_ops, &srcu_ops, &srcud_ops, &busted_srcud_ops,
4536 		TASKS_OPS TASKS_RUDE_OPS TASKS_TRACING_OPS
4537 		&trivial_ops, TRIVIAL_PREEMPT_OPS
4538 	};
4539 
4540 	if (!torture_init_begin(torture_type, verbose))
4541 		return -EBUSY;
4542 
4543 	/* Process args and tell the world that the torturer is on the job. */
4544 	for (i = 0; i < ARRAY_SIZE(torture_ops); i++) {
4545 		cur_ops = torture_ops[i];
4546 		if (strcmp(torture_type, cur_ops->name) == 0)
4547 			break;
4548 	}
4549 	if (i == ARRAY_SIZE(torture_ops)) {
4550 		pr_alert("rcu-torture: invalid torture type: \"%s\"\n",
4551 			 torture_type);
4552 		pr_alert("rcu-torture types:");
4553 		for (i = 0; i < ARRAY_SIZE(torture_ops); i++)
4554 			pr_cont(" %s", torture_ops[i]->name);
4555 		pr_cont("\n");
4556 		firsterr = -EINVAL;
4557 		cur_ops = NULL;
4558 		goto unwind;
4559 	}
4560 	if (cur_ops->fqs == NULL && fqs_duration != 0) {
4561 		pr_alert("rcu-torture: ->fqs NULL and non-zero fqs_duration, fqs disabled.\n");
4562 		fqs_duration = 0;
4563 	}
4564 	if (nocbs_nthreads != 0 && (cur_ops != &rcu_ops ||
4565 				    !IS_ENABLED(CONFIG_RCU_NOCB_CPU))) {
4566 		pr_alert("rcu-torture types: %s and CONFIG_RCU_NOCB_CPU=%d, nocb toggle disabled.\n",
4567 			 cur_ops->name, IS_ENABLED(CONFIG_RCU_NOCB_CPU));
4568 		nocbs_nthreads = 0;
4569 	}
4570 	if (cur_ops->init)
4571 		cur_ops->init();
4572 
4573 	rcu_torture_init_srcu_lockdep();
4574 
4575 	if (nfakewriters >= 0) {
4576 		nrealfakewriters = nfakewriters;
4577 	} else {
4578 		nrealfakewriters = num_online_cpus() - 2 - nfakewriters;
4579 		if (nrealfakewriters <= 0)
4580 			nrealfakewriters = 1;
4581 	}
4582 
4583 	if (nreaders >= 0) {
4584 		nrealreaders = nreaders;
4585 	} else {
4586 		nrealreaders = num_online_cpus() - 2 - nreaders;
4587 		if (nrealreaders <= 0)
4588 			nrealreaders = 1;
4589 	}
4590 	rcu_torture_print_module_parms(cur_ops, "Start of test");
4591 	if (cur_ops->get_gp_data)
4592 		cur_ops->get_gp_data(&flags, &gp_seq);
4593 	start_gp_seq = gp_seq;
4594 	pr_alert("%s:  Start-test grace-period state: g%ld f%#x\n",
4595 		 cur_ops->name, (long)gp_seq, flags);
4596 
4597 	/* Set up the freelist. */
4598 
4599 	INIT_LIST_HEAD(&rcu_torture_freelist);
4600 	for (i = 0; i < ARRAY_SIZE(rcu_tortures); i++) {
4601 		rcu_tortures[i].rtort_mbtest = 0;
4602 		list_add_tail(&rcu_tortures[i].rtort_free,
4603 			      &rcu_torture_freelist);
4604 	}
4605 
4606 	/* Initialize the statistics so that each run gets its own numbers. */
4607 
4608 	rcu_torture_current = NULL;
4609 	rcu_torture_current_version = 0;
4610 	atomic_set(&n_rcu_torture_alloc, 0);
4611 	atomic_set(&n_rcu_torture_alloc_fail, 0);
4612 	atomic_set(&n_rcu_torture_free, 0);
4613 	atomic_set(&n_rcu_torture_mberror, 0);
4614 	atomic_set(&n_rcu_torture_mbchk_fail, 0);
4615 	atomic_set(&n_rcu_torture_mbchk_tries, 0);
4616 	atomic_set(&n_rcu_torture_error, 0);
4617 	n_rcu_torture_barrier_error = 0;
4618 	n_rcu_torture_boost_ktrerror = 0;
4619 	n_rcu_torture_boost_failure = 0;
4620 	n_rcu_torture_boosts = 0;
4621 	for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++)
4622 		atomic_set(&rcu_torture_wcount[i], 0);
4623 	for_each_possible_cpu(cpu) {
4624 		for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++) {
4625 			per_cpu(rcu_torture_count, cpu)[i] = 0;
4626 			per_cpu(rcu_torture_batch, cpu)[i] = 0;
4627 		}
4628 	}
4629 	err_segs_recorded = 0;
4630 	rt_read_nsegs = 0;
4631 
4632 	/* Start up the kthreads. */
4633 
4634 	rcu_torture_write_types();
4635 	if (nrealfakewriters > 0) {
4636 		fakewriter_tasks = kzalloc_objs(fakewriter_tasks[0],
4637 						nrealfakewriters);
4638 		if (fakewriter_tasks == NULL) {
4639 			TOROUT_ERRSTRING("out of memory");
4640 			firsterr = -ENOMEM;
4641 			goto unwind;
4642 		}
4643 	}
4644 	for (i = 0; i < nrealfakewriters; i++) {
4645 		firsterr = torture_create_kthread(rcu_torture_fakewriter,
4646 						  NULL, fakewriter_tasks[i]);
4647 		if (torture_init_error(firsterr))
4648 			goto unwind;
4649 	}
4650 	reader_tasks = kzalloc_objs(reader_tasks[0], nrealreaders);
4651 	rcu_torture_reader_mbchk = kzalloc_objs(*rcu_torture_reader_mbchk,
4652 						nrealreaders);
4653 	if (!reader_tasks || !rcu_torture_reader_mbchk) {
4654 		TOROUT_ERRSTRING("out of memory");
4655 		firsterr = -ENOMEM;
4656 		goto unwind;
4657 	}
4658 	for (i = 0; i < nrealreaders; i++) {
4659 		rcu_torture_reader_mbchk[i].rtc_chkrdr = -1;
4660 		firsterr = torture_create_kthread(rcu_torture_reader, (void *)i,
4661 						  reader_tasks[i]);
4662 		if (torture_init_error(firsterr))
4663 			goto unwind;
4664 	}
4665 
4666 	firsterr = torture_create_kthread(rcu_torture_writer, NULL,
4667 					  writer_task);
4668 	if (torture_init_error(firsterr))
4669 		goto unwind;
4670 
4671 	firsterr = rcu_torture_updown_init();
4672 	if (torture_init_error(firsterr))
4673 		goto unwind;
4674 	nrealnocbers = nocbs_nthreads;
4675 	if (WARN_ON(nrealnocbers < 0))
4676 		nrealnocbers = 1;
4677 	if (WARN_ON(nocbs_toggle < 0))
4678 		nocbs_toggle = HZ;
4679 	if (nrealnocbers > 0) {
4680 		nocb_tasks = kzalloc_objs(nocb_tasks[0], nrealnocbers);
4681 		if (nocb_tasks == NULL) {
4682 			TOROUT_ERRSTRING("out of memory");
4683 			firsterr = -ENOMEM;
4684 			goto unwind;
4685 		}
4686 	} else {
4687 		nocb_tasks = NULL;
4688 	}
4689 	for (i = 0; i < nrealnocbers; i++) {
4690 		firsterr = torture_create_kthread(rcu_nocb_toggle, NULL, nocb_tasks[i]);
4691 		if (torture_init_error(firsterr))
4692 			goto unwind;
4693 	}
4694 	if (stat_interval > 0) {
4695 		firsterr = torture_create_kthread(rcu_torture_stats, NULL,
4696 						  stats_task);
4697 		if (torture_init_error(firsterr))
4698 			goto unwind;
4699 	}
4700 	if (test_no_idle_hz && shuffle_interval > 0) {
4701 		firsterr = torture_shuffle_init(shuffle_interval * HZ);
4702 		if (torture_init_error(firsterr))
4703 			goto unwind;
4704 	}
4705 	if (stutter < 0)
4706 		stutter = 0;
4707 	if (stutter) {
4708 		int t;
4709 
4710 		t = cur_ops->stall_dur ? cur_ops->stall_dur() : stutter * HZ;
4711 		firsterr = torture_stutter_init(stutter * HZ, t);
4712 		if (torture_init_error(firsterr))
4713 			goto unwind;
4714 	}
4715 	if (fqs_duration < 0)
4716 		fqs_duration = 0;
4717 	if (fqs_holdoff < 0)
4718 		fqs_holdoff = 0;
4719 	if (fqs_duration && fqs_holdoff) {
4720 		/* Create the fqs thread */
4721 		firsterr = torture_create_kthread(rcu_torture_fqs, NULL,
4722 						  fqs_task);
4723 		if (torture_init_error(firsterr))
4724 			goto unwind;
4725 	}
4726 	if (test_boost_interval < 1)
4727 		test_boost_interval = 1;
4728 	if (test_boost_duration < 2)
4729 		test_boost_duration = 2;
4730 	if (rcu_torture_can_boost()) {
4731 
4732 		boost_starttime = jiffies + test_boost_interval * HZ;
4733 
4734 		firsterr = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "RCU_TORTURE",
4735 					     rcutorture_booster_init,
4736 					     rcutorture_booster_cleanup);
4737 		rcutor_hp = firsterr;
4738 		if (torture_init_error(firsterr))
4739 			goto unwind;
4740 	}
4741 	shutdown_jiffies = jiffies + shutdown_secs * HZ;
4742 	firsterr = torture_shutdown_init(shutdown_secs, rcu_torture_cleanup);
4743 	if (torture_init_error(firsterr))
4744 		goto unwind;
4745 	firsterr = torture_onoff_init(onoff_holdoff * HZ, onoff_interval,
4746 				      rcutorture_sync);
4747 	if (torture_init_error(firsterr))
4748 		goto unwind;
4749 	firsterr = rcu_torture_stall_init();
4750 	if (torture_init_error(firsterr))
4751 		goto unwind;
4752 	firsterr = rcu_torture_fwd_prog_init();
4753 	if (torture_init_error(firsterr))
4754 		goto unwind;
4755 	firsterr = rcu_torture_barrier_init();
4756 	if (torture_init_error(firsterr))
4757 		goto unwind;
4758 	firsterr = rcu_torture_read_exit_init();
4759 	if (torture_init_error(firsterr))
4760 		goto unwind;
4761 	if (preempt_duration > 0) {
4762 		firsterr = torture_create_kthread(rcu_torture_preempt, NULL, preempt_task);
4763 		if (torture_init_error(firsterr))
4764 			goto unwind;
4765 	}
4766 	if (object_debug)
4767 		rcu_test_debug_objects();
4768 
4769 	if (cur_ops->gp_slow_register && !WARN_ON_ONCE(!cur_ops->gp_slow_unregister))
4770 		cur_ops->gp_slow_register(&rcu_fwd_cb_nodelay);
4771 
4772 	if (gpwrap_lag && cur_ops->set_gpwrap_lag) {
4773 		firsterr = rcu_gpwrap_lag_init();
4774 		if (torture_init_error(firsterr))
4775 			goto unwind;
4776 	}
4777 
4778 	torture_init_end();
4779 	return 0;
4780 
4781 unwind:
4782 	torture_init_end();
4783 	rcu_torture_cleanup();
4784 	if (shutdown_secs) {
4785 		WARN_ON(!IS_MODULE(CONFIG_RCU_TORTURE_TEST));
4786 		kernel_power_off();
4787 	}
4788 	return firsterr;
4789 }
4790 
4791 module_init(rcu_torture_init);
4792 module_exit(rcu_torture_cleanup);
4793