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