6a4558532eac5f4004b55dee074e60ca97f8a060
[platform/kernel/linux-rpi.git] / kernel / rcu / rcutorture.c
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.txt
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.h>
24 #include <linux/interrupt.h>
25 #include <linux/sched/signal.h>
26 #include <uapi/linux/sched/types.h>
27 #include <linux/atomic.h>
28 #include <linux/bitops.h>
29 #include <linux/completion.h>
30 #include <linux/moduleparam.h>
31 #include <linux/percpu.h>
32 #include <linux/notifier.h>
33 #include <linux/reboot.h>
34 #include <linux/freezer.h>
35 #include <linux/cpu.h>
36 #include <linux/delay.h>
37 #include <linux/stat.h>
38 #include <linux/srcu.h>
39 #include <linux/slab.h>
40 #include <linux/trace_clock.h>
41 #include <asm/byteorder.h>
42 #include <linux/torture.h>
43 #include <linux/vmalloc.h>
44 #include <linux/sched/debug.h>
45 #include <linux/sched/sysctl.h>
46 #include <linux/oom.h>
47
48 #include "rcu.h"
49
50 MODULE_LICENSE("GPL");
51 MODULE_AUTHOR("Paul E. McKenney <paulmck@linux.ibm.com> and Josh Triplett <josh@joshtriplett.org>");
52
53
54 /* Bits for ->extendables field, extendables param, and related definitions. */
55 #define RCUTORTURE_RDR_SHIFT     8      /* Put SRCU index in upper bits. */
56 #define RCUTORTURE_RDR_MASK      ((1 << RCUTORTURE_RDR_SHIFT) - 1)
57 #define RCUTORTURE_RDR_BH        0x01   /* Extend readers by disabling bh. */
58 #define RCUTORTURE_RDR_IRQ       0x02   /*  ... disabling interrupts. */
59 #define RCUTORTURE_RDR_PREEMPT   0x04   /*  ... disabling preemption. */
60 #define RCUTORTURE_RDR_RBH       0x08   /*  ... rcu_read_lock_bh(). */
61 #define RCUTORTURE_RDR_SCHED     0x10   /*  ... rcu_read_lock_sched(). */
62 #define RCUTORTURE_RDR_RCU       0x20   /*  ... entering another RCU reader. */
63 #define RCUTORTURE_RDR_NBITS     6      /* Number of bits defined above. */
64 #define RCUTORTURE_MAX_EXTEND    \
65         (RCUTORTURE_RDR_BH | RCUTORTURE_RDR_IRQ | RCUTORTURE_RDR_PREEMPT | \
66          RCUTORTURE_RDR_RBH | RCUTORTURE_RDR_SCHED)
67 #define RCUTORTURE_RDR_MAX_LOOPS 0x7    /* Maximum reader extensions. */
68                                         /* Must be power of two minus one. */
69 #define RCUTORTURE_RDR_MAX_SEGS (RCUTORTURE_RDR_MAX_LOOPS + 3)
70
71 torture_param(int, extendables, RCUTORTURE_MAX_EXTEND,
72               "Extend readers by disabling bh (1), irqs (2), or preempt (4)");
73 torture_param(int, fqs_duration, 0,
74               "Duration of fqs bursts (us), 0 to disable");
75 torture_param(int, fqs_holdoff, 0, "Holdoff time within fqs bursts (us)");
76 torture_param(int, fqs_stutter, 3, "Wait time between fqs bursts (s)");
77 torture_param(bool, fwd_progress, 1, "Test grace-period forward progress");
78 torture_param(int, fwd_progress_div, 4, "Fraction of CPU stall to wait");
79 torture_param(int, fwd_progress_holdoff, 60,
80               "Time between forward-progress tests (s)");
81 torture_param(bool, fwd_progress_need_resched, 1,
82               "Hide cond_resched() behind need_resched()");
83 torture_param(bool, gp_cond, false, "Use conditional/async GP wait primitives");
84 torture_param(bool, gp_exp, false, "Use expedited GP wait primitives");
85 torture_param(bool, gp_normal, false,
86              "Use normal (non-expedited) GP wait primitives");
87 torture_param(bool, gp_sync, false, "Use synchronous GP wait primitives");
88 torture_param(int, irqreader, 1, "Allow RCU readers from irq handlers");
89 torture_param(int, n_barrier_cbs, 0,
90              "# of callbacks/kthreads for barrier testing");
91 torture_param(int, nfakewriters, 4, "Number of RCU fake writer threads");
92 torture_param(int, nreaders, -1, "Number of RCU reader threads");
93 torture_param(int, object_debug, 0,
94              "Enable debug-object double call_rcu() testing");
95 torture_param(int, onoff_holdoff, 0, "Time after boot before CPU hotplugs (s)");
96 torture_param(int, onoff_interval, 0,
97              "Time between CPU hotplugs (jiffies), 0=disable");
98 torture_param(int, shuffle_interval, 3, "Number of seconds between shuffles");
99 torture_param(int, shutdown_secs, 0, "Shutdown time (s), <= zero to disable.");
100 torture_param(int, stall_cpu, 0, "Stall duration (s), zero to disable.");
101 torture_param(int, stall_cpu_holdoff, 10,
102              "Time to wait before starting stall (s).");
103 torture_param(int, stall_cpu_irqsoff, 0, "Disable interrupts while stalling.");
104 torture_param(int, stat_interval, 60,
105              "Number of seconds between stats printk()s");
106 torture_param(int, stutter, 5, "Number of seconds to run/halt test");
107 torture_param(int, test_boost, 1, "Test RCU prio boost: 0=no, 1=maybe, 2=yes.");
108 torture_param(int, test_boost_duration, 4,
109              "Duration of each boost test, seconds.");
110 torture_param(int, test_boost_interval, 7,
111              "Interval between boost tests, seconds.");
112 torture_param(bool, test_no_idle_hz, true,
113              "Test support for tickless idle CPUs");
114 torture_param(int, verbose, 1,
115              "Enable verbose debugging printk()s");
116
117 static char *torture_type = "rcu";
118 module_param(torture_type, charp, 0444);
119 MODULE_PARM_DESC(torture_type, "Type of RCU to torture (rcu, srcu, ...)");
120
121 static int nrealreaders;
122 static struct task_struct *writer_task;
123 static struct task_struct **fakewriter_tasks;
124 static struct task_struct **reader_tasks;
125 static struct task_struct *stats_task;
126 static struct task_struct *fqs_task;
127 static struct task_struct *boost_tasks[NR_CPUS];
128 static struct task_struct *stall_task;
129 static struct task_struct *fwd_prog_task;
130 static struct task_struct **barrier_cbs_tasks;
131 static struct task_struct *barrier_task;
132
133 #define RCU_TORTURE_PIPE_LEN 10
134
135 struct rcu_torture {
136         struct rcu_head rtort_rcu;
137         int rtort_pipe_count;
138         struct list_head rtort_free;
139         int rtort_mbtest;
140 };
141
142 static LIST_HEAD(rcu_torture_freelist);
143 static struct rcu_torture __rcu *rcu_torture_current;
144 static unsigned long rcu_torture_current_version;
145 static struct rcu_torture rcu_tortures[10 * RCU_TORTURE_PIPE_LEN];
146 static DEFINE_SPINLOCK(rcu_torture_lock);
147 static DEFINE_PER_CPU(long [RCU_TORTURE_PIPE_LEN + 1], rcu_torture_count);
148 static DEFINE_PER_CPU(long [RCU_TORTURE_PIPE_LEN + 1], rcu_torture_batch);
149 static atomic_t rcu_torture_wcount[RCU_TORTURE_PIPE_LEN + 1];
150 static atomic_t n_rcu_torture_alloc;
151 static atomic_t n_rcu_torture_alloc_fail;
152 static atomic_t n_rcu_torture_free;
153 static atomic_t n_rcu_torture_mberror;
154 static atomic_t n_rcu_torture_error;
155 static long n_rcu_torture_barrier_error;
156 static long n_rcu_torture_boost_ktrerror;
157 static long n_rcu_torture_boost_rterror;
158 static long n_rcu_torture_boost_failure;
159 static long n_rcu_torture_boosts;
160 static atomic_long_t n_rcu_torture_timers;
161 static long n_barrier_attempts;
162 static long n_barrier_successes; /* did rcu_barrier test succeed? */
163 static struct list_head rcu_torture_removed;
164
165 static int rcu_torture_writer_state;
166 #define RTWS_FIXED_DELAY        0
167 #define RTWS_DELAY              1
168 #define RTWS_REPLACE            2
169 #define RTWS_DEF_FREE           3
170 #define RTWS_EXP_SYNC           4
171 #define RTWS_COND_GET           5
172 #define RTWS_COND_SYNC          6
173 #define RTWS_SYNC               7
174 #define RTWS_STUTTER            8
175 #define RTWS_STOPPING           9
176 static const char * const rcu_torture_writer_state_names[] = {
177         "RTWS_FIXED_DELAY",
178         "RTWS_DELAY",
179         "RTWS_REPLACE",
180         "RTWS_DEF_FREE",
181         "RTWS_EXP_SYNC",
182         "RTWS_COND_GET",
183         "RTWS_COND_SYNC",
184         "RTWS_SYNC",
185         "RTWS_STUTTER",
186         "RTWS_STOPPING",
187 };
188
189 /* Record reader segment types and duration for first failing read. */
190 struct rt_read_seg {
191         int rt_readstate;
192         unsigned long rt_delay_jiffies;
193         unsigned long rt_delay_ms;
194         unsigned long rt_delay_us;
195         bool rt_preempted;
196 };
197 static int err_segs_recorded;
198 static struct rt_read_seg err_segs[RCUTORTURE_RDR_MAX_SEGS];
199 static int rt_read_nsegs;
200
201 static const char *rcu_torture_writer_state_getname(void)
202 {
203         unsigned int i = READ_ONCE(rcu_torture_writer_state);
204
205         if (i >= ARRAY_SIZE(rcu_torture_writer_state_names))
206                 return "???";
207         return rcu_torture_writer_state_names[i];
208 }
209
210 #if defined(CONFIG_RCU_BOOST) && !defined(CONFIG_HOTPLUG_CPU)
211 #define rcu_can_boost() 1
212 #else /* #if defined(CONFIG_RCU_BOOST) && !defined(CONFIG_HOTPLUG_CPU) */
213 #define rcu_can_boost() 0
214 #endif /* #else #if defined(CONFIG_RCU_BOOST) && !defined(CONFIG_HOTPLUG_CPU) */
215
216 #ifdef CONFIG_RCU_TRACE
217 static u64 notrace rcu_trace_clock_local(void)
218 {
219         u64 ts = trace_clock_local();
220
221         (void)do_div(ts, NSEC_PER_USEC);
222         return ts;
223 }
224 #else /* #ifdef CONFIG_RCU_TRACE */
225 static u64 notrace rcu_trace_clock_local(void)
226 {
227         return 0ULL;
228 }
229 #endif /* #else #ifdef CONFIG_RCU_TRACE */
230
231 static unsigned long boost_starttime;   /* jiffies of next boost test start. */
232 static DEFINE_MUTEX(boost_mutex);       /* protect setting boost_starttime */
233                                         /*  and boost task create/destroy. */
234 static atomic_t barrier_cbs_count;      /* Barrier callbacks registered. */
235 static bool barrier_phase;              /* Test phase. */
236 static atomic_t barrier_cbs_invoked;    /* Barrier callbacks invoked. */
237 static wait_queue_head_t *barrier_cbs_wq; /* Coordinate barrier testing. */
238 static DECLARE_WAIT_QUEUE_HEAD(barrier_wq);
239
240 static bool rcu_fwd_cb_nodelay;         /* Short rcu_torture_delay() delays. */
241
242 /*
243  * Allocate an element from the rcu_tortures pool.
244  */
245 static struct rcu_torture *
246 rcu_torture_alloc(void)
247 {
248         struct list_head *p;
249
250         spin_lock_bh(&rcu_torture_lock);
251         if (list_empty(&rcu_torture_freelist)) {
252                 atomic_inc(&n_rcu_torture_alloc_fail);
253                 spin_unlock_bh(&rcu_torture_lock);
254                 return NULL;
255         }
256         atomic_inc(&n_rcu_torture_alloc);
257         p = rcu_torture_freelist.next;
258         list_del_init(p);
259         spin_unlock_bh(&rcu_torture_lock);
260         return container_of(p, struct rcu_torture, rtort_free);
261 }
262
263 /*
264  * Free an element to the rcu_tortures pool.
265  */
266 static void
267 rcu_torture_free(struct rcu_torture *p)
268 {
269         atomic_inc(&n_rcu_torture_free);
270         spin_lock_bh(&rcu_torture_lock);
271         list_add_tail(&p->rtort_free, &rcu_torture_freelist);
272         spin_unlock_bh(&rcu_torture_lock);
273 }
274
275 /*
276  * Operations vector for selecting different types of tests.
277  */
278
279 struct rcu_torture_ops {
280         int ttype;
281         void (*init)(void);
282         void (*cleanup)(void);
283         int (*readlock)(void);
284         void (*read_delay)(struct torture_random_state *rrsp,
285                            struct rt_read_seg *rtrsp);
286         void (*readunlock)(int idx);
287         unsigned long (*get_gp_seq)(void);
288         unsigned long (*gp_diff)(unsigned long new, unsigned long old);
289         void (*deferred_free)(struct rcu_torture *p);
290         void (*sync)(void);
291         void (*exp_sync)(void);
292         unsigned long (*get_state)(void);
293         void (*cond_sync)(unsigned long oldstate);
294         call_rcu_func_t call;
295         void (*cb_barrier)(void);
296         void (*fqs)(void);
297         void (*stats)(void);
298         int (*stall_dur)(void);
299         int irq_capable;
300         int can_boost;
301         int extendables;
302         int slow_gps;
303         const char *name;
304 };
305
306 static struct rcu_torture_ops *cur_ops;
307
308 /*
309  * Definitions for rcu torture testing.
310  */
311
312 static int rcu_torture_read_lock(void) __acquires(RCU)
313 {
314         rcu_read_lock();
315         return 0;
316 }
317
318 static void
319 rcu_read_delay(struct torture_random_state *rrsp, struct rt_read_seg *rtrsp)
320 {
321         unsigned long started;
322         unsigned long completed;
323         const unsigned long shortdelay_us = 200;
324         unsigned long longdelay_ms = 300;
325         unsigned long long ts;
326
327         /* We want a short delay sometimes to make a reader delay the grace
328          * period, and we want a long delay occasionally to trigger
329          * force_quiescent_state. */
330
331         if (!rcu_fwd_cb_nodelay &&
332             !(torture_random(rrsp) % (nrealreaders * 2000 * longdelay_ms))) {
333                 started = cur_ops->get_gp_seq();
334                 ts = rcu_trace_clock_local();
335                 if (preempt_count() & (SOFTIRQ_MASK | HARDIRQ_MASK))
336                         longdelay_ms = 5; /* Avoid triggering BH limits. */
337                 mdelay(longdelay_ms);
338                 rtrsp->rt_delay_ms = longdelay_ms;
339                 completed = cur_ops->get_gp_seq();
340                 do_trace_rcu_torture_read(cur_ops->name, NULL, ts,
341                                           started, completed);
342         }
343         if (!(torture_random(rrsp) % (nrealreaders * 2 * shortdelay_us))) {
344                 udelay(shortdelay_us);
345                 rtrsp->rt_delay_us = shortdelay_us;
346         }
347         if (!preempt_count() &&
348             !(torture_random(rrsp) % (nrealreaders * 500))) {
349                 torture_preempt_schedule();  /* QS only if preemptible. */
350                 rtrsp->rt_preempted = true;
351         }
352 }
353
354 static void rcu_torture_read_unlock(int idx) __releases(RCU)
355 {
356         rcu_read_unlock();
357 }
358
359 /*
360  * Update callback in the pipe.  This should be invoked after a grace period.
361  */
362 static bool
363 rcu_torture_pipe_update_one(struct rcu_torture *rp)
364 {
365         int i;
366
367         i = rp->rtort_pipe_count;
368         if (i > RCU_TORTURE_PIPE_LEN)
369                 i = RCU_TORTURE_PIPE_LEN;
370         atomic_inc(&rcu_torture_wcount[i]);
371         if (++rp->rtort_pipe_count >= RCU_TORTURE_PIPE_LEN) {
372                 rp->rtort_mbtest = 0;
373                 return true;
374         }
375         return false;
376 }
377
378 /*
379  * Update all callbacks in the pipe.  Suitable for synchronous grace-period
380  * primitives.
381  */
382 static void
383 rcu_torture_pipe_update(struct rcu_torture *old_rp)
384 {
385         struct rcu_torture *rp;
386         struct rcu_torture *rp1;
387
388         if (old_rp)
389                 list_add(&old_rp->rtort_free, &rcu_torture_removed);
390         list_for_each_entry_safe(rp, rp1, &rcu_torture_removed, rtort_free) {
391                 if (rcu_torture_pipe_update_one(rp)) {
392                         list_del(&rp->rtort_free);
393                         rcu_torture_free(rp);
394                 }
395         }
396 }
397
398 static void
399 rcu_torture_cb(struct rcu_head *p)
400 {
401         struct rcu_torture *rp = container_of(p, struct rcu_torture, rtort_rcu);
402
403         if (torture_must_stop_irq()) {
404                 /* Test is ending, just drop callbacks on the floor. */
405                 /* The next initialization will pick up the pieces. */
406                 return;
407         }
408         if (rcu_torture_pipe_update_one(rp))
409                 rcu_torture_free(rp);
410         else
411                 cur_ops->deferred_free(rp);
412 }
413
414 static unsigned long rcu_no_completed(void)
415 {
416         return 0;
417 }
418
419 static void rcu_torture_deferred_free(struct rcu_torture *p)
420 {
421         call_rcu(&p->rtort_rcu, rcu_torture_cb);
422 }
423
424 static void rcu_sync_torture_init(void)
425 {
426         INIT_LIST_HEAD(&rcu_torture_removed);
427 }
428
429 static struct rcu_torture_ops rcu_ops = {
430         .ttype          = RCU_FLAVOR,
431         .init           = rcu_sync_torture_init,
432         .readlock       = rcu_torture_read_lock,
433         .read_delay     = rcu_read_delay,
434         .readunlock     = rcu_torture_read_unlock,
435         .get_gp_seq     = rcu_get_gp_seq,
436         .gp_diff        = rcu_seq_diff,
437         .deferred_free  = rcu_torture_deferred_free,
438         .sync           = synchronize_rcu,
439         .exp_sync       = synchronize_rcu_expedited,
440         .get_state      = get_state_synchronize_rcu,
441         .cond_sync      = cond_synchronize_rcu,
442         .call           = call_rcu,
443         .cb_barrier     = rcu_barrier,
444         .fqs            = rcu_force_quiescent_state,
445         .stats          = NULL,
446         .stall_dur      = rcu_jiffies_till_stall_check,
447         .irq_capable    = 1,
448         .can_boost      = rcu_can_boost(),
449         .extendables    = RCUTORTURE_MAX_EXTEND,
450         .name           = "rcu"
451 };
452
453 /*
454  * Don't even think about trying any of these in real life!!!
455  * The names includes "busted", and they really means it!
456  * The only purpose of these functions is to provide a buggy RCU
457  * implementation to make sure that rcutorture correctly emits
458  * buggy-RCU error messages.
459  */
460 static void rcu_busted_torture_deferred_free(struct rcu_torture *p)
461 {
462         /* This is a deliberate bug for testing purposes only! */
463         rcu_torture_cb(&p->rtort_rcu);
464 }
465
466 static void synchronize_rcu_busted(void)
467 {
468         /* This is a deliberate bug for testing purposes only! */
469 }
470
471 static void
472 call_rcu_busted(struct rcu_head *head, rcu_callback_t func)
473 {
474         /* This is a deliberate bug for testing purposes only! */
475         func(head);
476 }
477
478 static struct rcu_torture_ops rcu_busted_ops = {
479         .ttype          = INVALID_RCU_FLAVOR,
480         .init           = rcu_sync_torture_init,
481         .readlock       = rcu_torture_read_lock,
482         .read_delay     = rcu_read_delay,  /* just reuse rcu's version. */
483         .readunlock     = rcu_torture_read_unlock,
484         .get_gp_seq     = rcu_no_completed,
485         .deferred_free  = rcu_busted_torture_deferred_free,
486         .sync           = synchronize_rcu_busted,
487         .exp_sync       = synchronize_rcu_busted,
488         .call           = call_rcu_busted,
489         .cb_barrier     = NULL,
490         .fqs            = NULL,
491         .stats          = NULL,
492         .irq_capable    = 1,
493         .name           = "busted"
494 };
495
496 /*
497  * Definitions for srcu torture testing.
498  */
499
500 DEFINE_STATIC_SRCU(srcu_ctl);
501 static struct srcu_struct srcu_ctld;
502 static struct srcu_struct *srcu_ctlp = &srcu_ctl;
503
504 static int srcu_torture_read_lock(void) __acquires(srcu_ctlp)
505 {
506         return srcu_read_lock(srcu_ctlp);
507 }
508
509 static void
510 srcu_read_delay(struct torture_random_state *rrsp, struct rt_read_seg *rtrsp)
511 {
512         long delay;
513         const long uspertick = 1000000 / HZ;
514         const long longdelay = 10;
515
516         /* We want there to be long-running readers, but not all the time. */
517
518         delay = torture_random(rrsp) %
519                 (nrealreaders * 2 * longdelay * uspertick);
520         if (!delay && in_task()) {
521                 schedule_timeout_interruptible(longdelay);
522                 rtrsp->rt_delay_jiffies = longdelay;
523         } else {
524                 rcu_read_delay(rrsp, rtrsp);
525         }
526 }
527
528 static void srcu_torture_read_unlock(int idx) __releases(srcu_ctlp)
529 {
530         srcu_read_unlock(srcu_ctlp, idx);
531 }
532
533 static unsigned long srcu_torture_completed(void)
534 {
535         return srcu_batches_completed(srcu_ctlp);
536 }
537
538 static void srcu_torture_deferred_free(struct rcu_torture *rp)
539 {
540         call_srcu(srcu_ctlp, &rp->rtort_rcu, rcu_torture_cb);
541 }
542
543 static void srcu_torture_synchronize(void)
544 {
545         synchronize_srcu(srcu_ctlp);
546 }
547
548 static void srcu_torture_call(struct rcu_head *head,
549                               rcu_callback_t func)
550 {
551         call_srcu(srcu_ctlp, head, func);
552 }
553
554 static void srcu_torture_barrier(void)
555 {
556         srcu_barrier(srcu_ctlp);
557 }
558
559 static void srcu_torture_stats(void)
560 {
561         srcu_torture_stats_print(srcu_ctlp, torture_type, TORTURE_FLAG);
562 }
563
564 static void srcu_torture_synchronize_expedited(void)
565 {
566         synchronize_srcu_expedited(srcu_ctlp);
567 }
568
569 static struct rcu_torture_ops srcu_ops = {
570         .ttype          = SRCU_FLAVOR,
571         .init           = rcu_sync_torture_init,
572         .readlock       = srcu_torture_read_lock,
573         .read_delay     = srcu_read_delay,
574         .readunlock     = srcu_torture_read_unlock,
575         .get_gp_seq     = srcu_torture_completed,
576         .deferred_free  = srcu_torture_deferred_free,
577         .sync           = srcu_torture_synchronize,
578         .exp_sync       = srcu_torture_synchronize_expedited,
579         .call           = srcu_torture_call,
580         .cb_barrier     = srcu_torture_barrier,
581         .stats          = srcu_torture_stats,
582         .irq_capable    = 1,
583         .name           = "srcu"
584 };
585
586 static void srcu_torture_init(void)
587 {
588         rcu_sync_torture_init();
589         WARN_ON(init_srcu_struct(&srcu_ctld));
590         srcu_ctlp = &srcu_ctld;
591 }
592
593 static void srcu_torture_cleanup(void)
594 {
595         cleanup_srcu_struct(&srcu_ctld);
596         srcu_ctlp = &srcu_ctl; /* In case of a later rcutorture run. */
597 }
598
599 /* As above, but dynamically allocated. */
600 static struct rcu_torture_ops srcud_ops = {
601         .ttype          = SRCU_FLAVOR,
602         .init           = srcu_torture_init,
603         .cleanup        = srcu_torture_cleanup,
604         .readlock       = srcu_torture_read_lock,
605         .read_delay     = srcu_read_delay,
606         .readunlock     = srcu_torture_read_unlock,
607         .get_gp_seq     = srcu_torture_completed,
608         .deferred_free  = srcu_torture_deferred_free,
609         .sync           = srcu_torture_synchronize,
610         .exp_sync       = srcu_torture_synchronize_expedited,
611         .call           = srcu_torture_call,
612         .cb_barrier     = srcu_torture_barrier,
613         .stats          = srcu_torture_stats,
614         .irq_capable    = 1,
615         .name           = "srcud"
616 };
617
618 /* As above, but broken due to inappropriate reader extension. */
619 static struct rcu_torture_ops busted_srcud_ops = {
620         .ttype          = SRCU_FLAVOR,
621         .init           = srcu_torture_init,
622         .cleanup        = srcu_torture_cleanup,
623         .readlock       = srcu_torture_read_lock,
624         .read_delay     = rcu_read_delay,
625         .readunlock     = srcu_torture_read_unlock,
626         .get_gp_seq     = srcu_torture_completed,
627         .deferred_free  = srcu_torture_deferred_free,
628         .sync           = srcu_torture_synchronize,
629         .exp_sync       = srcu_torture_synchronize_expedited,
630         .call           = srcu_torture_call,
631         .cb_barrier     = srcu_torture_barrier,
632         .stats          = srcu_torture_stats,
633         .irq_capable    = 1,
634         .extendables    = RCUTORTURE_MAX_EXTEND,
635         .name           = "busted_srcud"
636 };
637
638 /*
639  * Definitions for RCU-tasks torture testing.
640  */
641
642 static int tasks_torture_read_lock(void)
643 {
644         return 0;
645 }
646
647 static void tasks_torture_read_unlock(int idx)
648 {
649 }
650
651 static void rcu_tasks_torture_deferred_free(struct rcu_torture *p)
652 {
653         call_rcu_tasks(&p->rtort_rcu, rcu_torture_cb);
654 }
655
656 static struct rcu_torture_ops tasks_ops = {
657         .ttype          = RCU_TASKS_FLAVOR,
658         .init           = rcu_sync_torture_init,
659         .readlock       = tasks_torture_read_lock,
660         .read_delay     = rcu_read_delay,  /* just reuse rcu's version. */
661         .readunlock     = tasks_torture_read_unlock,
662         .get_gp_seq     = rcu_no_completed,
663         .deferred_free  = rcu_tasks_torture_deferred_free,
664         .sync           = synchronize_rcu_tasks,
665         .exp_sync       = synchronize_rcu_tasks,
666         .call           = call_rcu_tasks,
667         .cb_barrier     = rcu_barrier_tasks,
668         .fqs            = NULL,
669         .stats          = NULL,
670         .irq_capable    = 1,
671         .slow_gps       = 1,
672         .name           = "tasks"
673 };
674
675 static unsigned long rcutorture_seq_diff(unsigned long new, unsigned long old)
676 {
677         if (!cur_ops->gp_diff)
678                 return new - old;
679         return cur_ops->gp_diff(new, old);
680 }
681
682 static bool __maybe_unused torturing_tasks(void)
683 {
684         return cur_ops == &tasks_ops;
685 }
686
687 /*
688  * RCU torture priority-boost testing.  Runs one real-time thread per
689  * CPU for moderate bursts, repeatedly registering RCU callbacks and
690  * spinning waiting for them to be invoked.  If a given callback takes
691  * too long to be invoked, we assume that priority inversion has occurred.
692  */
693
694 struct rcu_boost_inflight {
695         struct rcu_head rcu;
696         int inflight;
697 };
698
699 static void rcu_torture_boost_cb(struct rcu_head *head)
700 {
701         struct rcu_boost_inflight *rbip =
702                 container_of(head, struct rcu_boost_inflight, rcu);
703
704         /* Ensure RCU-core accesses precede clearing ->inflight */
705         smp_store_release(&rbip->inflight, 0);
706 }
707
708 static int old_rt_runtime = -1;
709
710 static void rcu_torture_disable_rt_throttle(void)
711 {
712         /*
713          * Disable RT throttling so that rcutorture's boost threads don't get
714          * throttled. Only possible if rcutorture is built-in otherwise the
715          * user should manually do this by setting the sched_rt_period_us and
716          * sched_rt_runtime sysctls.
717          */
718         if (!IS_BUILTIN(CONFIG_RCU_TORTURE_TEST) || old_rt_runtime != -1)
719                 return;
720
721         old_rt_runtime = sysctl_sched_rt_runtime;
722         sysctl_sched_rt_runtime = -1;
723 }
724
725 static void rcu_torture_enable_rt_throttle(void)
726 {
727         if (!IS_BUILTIN(CONFIG_RCU_TORTURE_TEST) || old_rt_runtime == -1)
728                 return;
729
730         sysctl_sched_rt_runtime = old_rt_runtime;
731         old_rt_runtime = -1;
732 }
733
734 static bool rcu_torture_boost_failed(unsigned long start, unsigned long end)
735 {
736         if (end - start > test_boost_duration * HZ - HZ / 2) {
737                 VERBOSE_TOROUT_STRING("rcu_torture_boost boosting failed");
738                 n_rcu_torture_boost_failure++;
739
740                 return true; /* failed */
741         }
742
743         return false; /* passed */
744 }
745
746 static int rcu_torture_boost(void *arg)
747 {
748         unsigned long call_rcu_time;
749         unsigned long endtime;
750         unsigned long oldstarttime;
751         struct rcu_boost_inflight rbi = { .inflight = 0 };
752         struct sched_param sp;
753
754         VERBOSE_TOROUT_STRING("rcu_torture_boost started");
755
756         /* Set real-time priority. */
757         sp.sched_priority = 1;
758         if (sched_setscheduler(current, SCHED_FIFO, &sp) < 0) {
759                 VERBOSE_TOROUT_STRING("rcu_torture_boost RT prio failed!");
760                 n_rcu_torture_boost_rterror++;
761         }
762
763         init_rcu_head_on_stack(&rbi.rcu);
764         /* Each pass through the following loop does one boost-test cycle. */
765         do {
766                 /* Track if the test failed already in this test interval? */
767                 bool failed = false;
768
769                 /* Increment n_rcu_torture_boosts once per boost-test */
770                 while (!kthread_should_stop()) {
771                         if (mutex_trylock(&boost_mutex)) {
772                                 n_rcu_torture_boosts++;
773                                 mutex_unlock(&boost_mutex);
774                                 break;
775                         }
776                         schedule_timeout_uninterruptible(1);
777                 }
778                 if (kthread_should_stop())
779                         goto checkwait;
780
781                 /* Wait for the next test interval. */
782                 oldstarttime = boost_starttime;
783                 while (ULONG_CMP_LT(jiffies, oldstarttime)) {
784                         schedule_timeout_interruptible(oldstarttime - jiffies);
785                         stutter_wait("rcu_torture_boost");
786                         if (torture_must_stop())
787                                 goto checkwait;
788                 }
789
790                 /* Do one boost-test interval. */
791                 endtime = oldstarttime + test_boost_duration * HZ;
792                 call_rcu_time = jiffies;
793                 while (ULONG_CMP_LT(jiffies, endtime)) {
794                         /* If we don't have a callback in flight, post one. */
795                         if (!smp_load_acquire(&rbi.inflight)) {
796                                 /* RCU core before ->inflight = 1. */
797                                 smp_store_release(&rbi.inflight, 1);
798                                 call_rcu(&rbi.rcu, rcu_torture_boost_cb);
799                                 /* Check if the boost test failed */
800                                 failed = failed ||
801                                          rcu_torture_boost_failed(call_rcu_time,
802                                                                  jiffies);
803                                 call_rcu_time = jiffies;
804                         }
805                         stutter_wait("rcu_torture_boost");
806                         if (torture_must_stop())
807                                 goto checkwait;
808                 }
809
810                 /*
811                  * If boost never happened, then inflight will always be 1, in
812                  * this case the boost check would never happen in the above
813                  * loop so do another one here.
814                  */
815                 if (!failed && smp_load_acquire(&rbi.inflight))
816                         rcu_torture_boost_failed(call_rcu_time, jiffies);
817
818                 /*
819                  * Set the start time of the next test interval.
820                  * Yes, this is vulnerable to long delays, but such
821                  * delays simply cause a false negative for the next
822                  * interval.  Besides, we are running at RT priority,
823                  * so delays should be relatively rare.
824                  */
825                 while (oldstarttime == boost_starttime &&
826                        !kthread_should_stop()) {
827                         if (mutex_trylock(&boost_mutex)) {
828                                 boost_starttime = jiffies +
829                                                   test_boost_interval * HZ;
830                                 mutex_unlock(&boost_mutex);
831                                 break;
832                         }
833                         schedule_timeout_uninterruptible(1);
834                 }
835
836                 /* Go do the stutter. */
837 checkwait:      stutter_wait("rcu_torture_boost");
838         } while (!torture_must_stop());
839
840         /* Clean up and exit. */
841         while (!kthread_should_stop() || smp_load_acquire(&rbi.inflight)) {
842                 torture_shutdown_absorb("rcu_torture_boost");
843                 schedule_timeout_uninterruptible(1);
844         }
845         destroy_rcu_head_on_stack(&rbi.rcu);
846         torture_kthread_stopping("rcu_torture_boost");
847         return 0;
848 }
849
850 /*
851  * RCU torture force-quiescent-state kthread.  Repeatedly induces
852  * bursts of calls to force_quiescent_state(), increasing the probability
853  * of occurrence of some important types of race conditions.
854  */
855 static int
856 rcu_torture_fqs(void *arg)
857 {
858         unsigned long fqs_resume_time;
859         int fqs_burst_remaining;
860
861         VERBOSE_TOROUT_STRING("rcu_torture_fqs task started");
862         do {
863                 fqs_resume_time = jiffies + fqs_stutter * HZ;
864                 while (ULONG_CMP_LT(jiffies, fqs_resume_time) &&
865                        !kthread_should_stop()) {
866                         schedule_timeout_interruptible(1);
867                 }
868                 fqs_burst_remaining = fqs_duration;
869                 while (fqs_burst_remaining > 0 &&
870                        !kthread_should_stop()) {
871                         cur_ops->fqs();
872                         udelay(fqs_holdoff);
873                         fqs_burst_remaining -= fqs_holdoff;
874                 }
875                 stutter_wait("rcu_torture_fqs");
876         } while (!torture_must_stop());
877         torture_kthread_stopping("rcu_torture_fqs");
878         return 0;
879 }
880
881 /*
882  * RCU torture writer kthread.  Repeatedly substitutes a new structure
883  * for that pointed to by rcu_torture_current, freeing the old structure
884  * after a series of grace periods (the "pipeline").
885  */
886 static int
887 rcu_torture_writer(void *arg)
888 {
889         bool can_expedite = !rcu_gp_is_expedited() && !rcu_gp_is_normal();
890         int expediting = 0;
891         unsigned long gp_snap;
892         bool gp_cond1 = gp_cond, gp_exp1 = gp_exp, gp_normal1 = gp_normal;
893         bool gp_sync1 = gp_sync;
894         int i;
895         struct rcu_torture *rp;
896         struct rcu_torture *old_rp;
897         static DEFINE_TORTURE_RANDOM(rand);
898         int synctype[] = { RTWS_DEF_FREE, RTWS_EXP_SYNC,
899                            RTWS_COND_GET, RTWS_SYNC };
900         int nsynctypes = 0;
901
902         VERBOSE_TOROUT_STRING("rcu_torture_writer task started");
903         if (!can_expedite)
904                 pr_alert("%s" TORTURE_FLAG
905                          " GP expediting controlled from boot/sysfs for %s.\n",
906                          torture_type, cur_ops->name);
907
908         /* Initialize synctype[] array.  If none set, take default. */
909         if (!gp_cond1 && !gp_exp1 && !gp_normal1 && !gp_sync1)
910                 gp_cond1 = gp_exp1 = gp_normal1 = gp_sync1 = true;
911         if (gp_cond1 && cur_ops->get_state && cur_ops->cond_sync) {
912                 synctype[nsynctypes++] = RTWS_COND_GET;
913                 pr_info("%s: Testing conditional GPs.\n", __func__);
914         } else if (gp_cond && (!cur_ops->get_state || !cur_ops->cond_sync)) {
915                 pr_alert("%s: gp_cond without primitives.\n", __func__);
916         }
917         if (gp_exp1 && cur_ops->exp_sync) {
918                 synctype[nsynctypes++] = RTWS_EXP_SYNC;
919                 pr_info("%s: Testing expedited GPs.\n", __func__);
920         } else if (gp_exp && !cur_ops->exp_sync) {
921                 pr_alert("%s: gp_exp without primitives.\n", __func__);
922         }
923         if (gp_normal1 && cur_ops->deferred_free) {
924                 synctype[nsynctypes++] = RTWS_DEF_FREE;
925                 pr_info("%s: Testing asynchronous GPs.\n", __func__);
926         } else if (gp_normal && !cur_ops->deferred_free) {
927                 pr_alert("%s: gp_normal without primitives.\n", __func__);
928         }
929         if (gp_sync1 && cur_ops->sync) {
930                 synctype[nsynctypes++] = RTWS_SYNC;
931                 pr_info("%s: Testing normal GPs.\n", __func__);
932         } else if (gp_sync && !cur_ops->sync) {
933                 pr_alert("%s: gp_sync without primitives.\n", __func__);
934         }
935         if (WARN_ONCE(nsynctypes == 0,
936                       "rcu_torture_writer: No update-side primitives.\n")) {
937                 /*
938                  * No updates primitives, so don't try updating.
939                  * The resulting test won't be testing much, hence the
940                  * above WARN_ONCE().
941                  */
942                 rcu_torture_writer_state = RTWS_STOPPING;
943                 torture_kthread_stopping("rcu_torture_writer");
944         }
945
946         do {
947                 rcu_torture_writer_state = RTWS_FIXED_DELAY;
948                 schedule_timeout_uninterruptible(1);
949                 rp = rcu_torture_alloc();
950                 if (rp == NULL)
951                         continue;
952                 rp->rtort_pipe_count = 0;
953                 rcu_torture_writer_state = RTWS_DELAY;
954                 udelay(torture_random(&rand) & 0x3ff);
955                 rcu_torture_writer_state = RTWS_REPLACE;
956                 old_rp = rcu_dereference_check(rcu_torture_current,
957                                                current == writer_task);
958                 rp->rtort_mbtest = 1;
959                 rcu_assign_pointer(rcu_torture_current, rp);
960                 smp_wmb(); /* Mods to old_rp must follow rcu_assign_pointer() */
961                 if (old_rp) {
962                         i = old_rp->rtort_pipe_count;
963                         if (i > RCU_TORTURE_PIPE_LEN)
964                                 i = RCU_TORTURE_PIPE_LEN;
965                         atomic_inc(&rcu_torture_wcount[i]);
966                         old_rp->rtort_pipe_count++;
967                         switch (synctype[torture_random(&rand) % nsynctypes]) {
968                         case RTWS_DEF_FREE:
969                                 rcu_torture_writer_state = RTWS_DEF_FREE;
970                                 cur_ops->deferred_free(old_rp);
971                                 break;
972                         case RTWS_EXP_SYNC:
973                                 rcu_torture_writer_state = RTWS_EXP_SYNC;
974                                 cur_ops->exp_sync();
975                                 rcu_torture_pipe_update(old_rp);
976                                 break;
977                         case RTWS_COND_GET:
978                                 rcu_torture_writer_state = RTWS_COND_GET;
979                                 gp_snap = cur_ops->get_state();
980                                 i = torture_random(&rand) % 16;
981                                 if (i != 0)
982                                         schedule_timeout_interruptible(i);
983                                 udelay(torture_random(&rand) % 1000);
984                                 rcu_torture_writer_state = RTWS_COND_SYNC;
985                                 cur_ops->cond_sync(gp_snap);
986                                 rcu_torture_pipe_update(old_rp);
987                                 break;
988                         case RTWS_SYNC:
989                                 rcu_torture_writer_state = RTWS_SYNC;
990                                 cur_ops->sync();
991                                 rcu_torture_pipe_update(old_rp);
992                                 break;
993                         default:
994                                 WARN_ON_ONCE(1);
995                                 break;
996                         }
997                 }
998                 WRITE_ONCE(rcu_torture_current_version,
999                            rcu_torture_current_version + 1);
1000                 /* Cycle through nesting levels of rcu_expedite_gp() calls. */
1001                 if (can_expedite &&
1002                     !(torture_random(&rand) & 0xff & (!!expediting - 1))) {
1003                         WARN_ON_ONCE(expediting == 0 && rcu_gp_is_expedited());
1004                         if (expediting >= 0)
1005                                 rcu_expedite_gp();
1006                         else
1007                                 rcu_unexpedite_gp();
1008                         if (++expediting > 3)
1009                                 expediting = -expediting;
1010                 } else if (!can_expedite) { /* Disabled during boot, recheck. */
1011                         can_expedite = !rcu_gp_is_expedited() &&
1012                                        !rcu_gp_is_normal();
1013                 }
1014                 rcu_torture_writer_state = RTWS_STUTTER;
1015                 if (stutter_wait("rcu_torture_writer") &&
1016                     !READ_ONCE(rcu_fwd_cb_nodelay) &&
1017                     !cur_ops->slow_gps)
1018                         for (i = 0; i < ARRAY_SIZE(rcu_tortures); i++)
1019                                 if (list_empty(&rcu_tortures[i].rtort_free) &&
1020                                     rcu_access_pointer(rcu_torture_current) !=
1021                                     &rcu_tortures[i])
1022                                         WARN(1, "%s: rtort_pipe_count: %d\n", __func__, rcu_tortures[i].rtort_pipe_count);
1023         } while (!torture_must_stop());
1024         /* Reset expediting back to unexpedited. */
1025         if (expediting > 0)
1026                 expediting = -expediting;
1027         while (can_expedite && expediting++ < 0)
1028                 rcu_unexpedite_gp();
1029         WARN_ON_ONCE(can_expedite && rcu_gp_is_expedited());
1030         if (!can_expedite)
1031                 pr_alert("%s" TORTURE_FLAG
1032                          " Dynamic grace-period expediting was disabled.\n",
1033                          torture_type);
1034         rcu_torture_writer_state = RTWS_STOPPING;
1035         torture_kthread_stopping("rcu_torture_writer");
1036         return 0;
1037 }
1038
1039 /*
1040  * RCU torture fake writer kthread.  Repeatedly calls sync, with a random
1041  * delay between calls.
1042  */
1043 static int
1044 rcu_torture_fakewriter(void *arg)
1045 {
1046         DEFINE_TORTURE_RANDOM(rand);
1047
1048         VERBOSE_TOROUT_STRING("rcu_torture_fakewriter task started");
1049         set_user_nice(current, MAX_NICE);
1050
1051         do {
1052                 schedule_timeout_uninterruptible(1 + torture_random(&rand)%10);
1053                 udelay(torture_random(&rand) & 0x3ff);
1054                 if (cur_ops->cb_barrier != NULL &&
1055                     torture_random(&rand) % (nfakewriters * 8) == 0) {
1056                         cur_ops->cb_barrier();
1057                 } else if (gp_normal == gp_exp) {
1058                         if (cur_ops->sync && torture_random(&rand) & 0x80)
1059                                 cur_ops->sync();
1060                         else if (cur_ops->exp_sync)
1061                                 cur_ops->exp_sync();
1062                 } else if (gp_normal && cur_ops->sync) {
1063                         cur_ops->sync();
1064                 } else if (cur_ops->exp_sync) {
1065                         cur_ops->exp_sync();
1066                 }
1067                 stutter_wait("rcu_torture_fakewriter");
1068         } while (!torture_must_stop());
1069
1070         torture_kthread_stopping("rcu_torture_fakewriter");
1071         return 0;
1072 }
1073
1074 static void rcu_torture_timer_cb(struct rcu_head *rhp)
1075 {
1076         kfree(rhp);
1077 }
1078
1079 /*
1080  * Do one extension of an RCU read-side critical section using the
1081  * current reader state in readstate (set to zero for initial entry
1082  * to extended critical section), set the new state as specified by
1083  * newstate (set to zero for final exit from extended critical section),
1084  * and random-number-generator state in trsp.  If this is neither the
1085  * beginning or end of the critical section and if there was actually a
1086  * change, do a ->read_delay().
1087  */
1088 static void rcutorture_one_extend(int *readstate, int newstate,
1089                                   struct torture_random_state *trsp,
1090                                   struct rt_read_seg *rtrsp)
1091 {
1092         int idxnew = -1;
1093         int idxold = *readstate;
1094         int statesnew = ~*readstate & newstate;
1095         int statesold = *readstate & ~newstate;
1096
1097         WARN_ON_ONCE(idxold < 0);
1098         WARN_ON_ONCE((idxold >> RCUTORTURE_RDR_SHIFT) > 1);
1099         rtrsp->rt_readstate = newstate;
1100
1101         /* First, put new protection in place to avoid critical-section gap. */
1102         if (statesnew & RCUTORTURE_RDR_BH)
1103                 local_bh_disable();
1104         if (statesnew & RCUTORTURE_RDR_IRQ)
1105                 local_irq_disable();
1106         if (statesnew & RCUTORTURE_RDR_PREEMPT)
1107                 preempt_disable();
1108         if (statesnew & RCUTORTURE_RDR_RBH)
1109                 rcu_read_lock_bh();
1110         if (statesnew & RCUTORTURE_RDR_SCHED)
1111                 rcu_read_lock_sched();
1112         if (statesnew & RCUTORTURE_RDR_RCU)
1113                 idxnew = cur_ops->readlock() << RCUTORTURE_RDR_SHIFT;
1114
1115         /* Next, remove old protection, irq first due to bh conflict. */
1116         if (statesold & RCUTORTURE_RDR_IRQ)
1117                 local_irq_enable();
1118         if (statesold & RCUTORTURE_RDR_BH)
1119                 local_bh_enable();
1120         if (statesold & RCUTORTURE_RDR_PREEMPT)
1121                 preempt_enable();
1122         if (statesold & RCUTORTURE_RDR_RBH)
1123                 rcu_read_unlock_bh();
1124         if (statesold & RCUTORTURE_RDR_SCHED)
1125                 rcu_read_unlock_sched();
1126         if (statesold & RCUTORTURE_RDR_RCU)
1127                 cur_ops->readunlock(idxold >> RCUTORTURE_RDR_SHIFT);
1128
1129         /* Delay if neither beginning nor end and there was a change. */
1130         if ((statesnew || statesold) && *readstate && newstate)
1131                 cur_ops->read_delay(trsp, rtrsp);
1132
1133         /* Update the reader state. */
1134         if (idxnew == -1)
1135                 idxnew = idxold & ~RCUTORTURE_RDR_MASK;
1136         WARN_ON_ONCE(idxnew < 0);
1137         WARN_ON_ONCE((idxnew >> RCUTORTURE_RDR_SHIFT) > 1);
1138         *readstate = idxnew | newstate;
1139         WARN_ON_ONCE((*readstate >> RCUTORTURE_RDR_SHIFT) < 0);
1140         WARN_ON_ONCE((*readstate >> RCUTORTURE_RDR_SHIFT) > 1);
1141 }
1142
1143 /* Return the biggest extendables mask given current RCU and boot parameters. */
1144 static int rcutorture_extend_mask_max(void)
1145 {
1146         int mask;
1147
1148         WARN_ON_ONCE(extendables & ~RCUTORTURE_MAX_EXTEND);
1149         mask = extendables & RCUTORTURE_MAX_EXTEND & cur_ops->extendables;
1150         mask = mask | RCUTORTURE_RDR_RCU;
1151         return mask;
1152 }
1153
1154 /* Return a random protection state mask, but with at least one bit set. */
1155 static int
1156 rcutorture_extend_mask(int oldmask, struct torture_random_state *trsp)
1157 {
1158         int mask = rcutorture_extend_mask_max();
1159         unsigned long randmask1 = torture_random(trsp) >> 8;
1160         unsigned long randmask2 = randmask1 >> 3;
1161
1162         WARN_ON_ONCE(mask >> RCUTORTURE_RDR_SHIFT);
1163         /* Mostly only one bit (need preemption!), sometimes lots of bits. */
1164         if (!(randmask1 & 0x7))
1165                 mask = mask & randmask2;
1166         else
1167                 mask = mask & (1 << (randmask2 % RCUTORTURE_RDR_NBITS));
1168         /* Can't enable bh w/irq disabled. */
1169         if ((mask & RCUTORTURE_RDR_IRQ) &&
1170             ((!(mask & RCUTORTURE_RDR_BH) && (oldmask & RCUTORTURE_RDR_BH)) ||
1171              (!(mask & RCUTORTURE_RDR_RBH) && (oldmask & RCUTORTURE_RDR_RBH))))
1172                 mask |= RCUTORTURE_RDR_BH | RCUTORTURE_RDR_RBH;
1173         return mask ?: RCUTORTURE_RDR_RCU;
1174 }
1175
1176 /*
1177  * Do a randomly selected number of extensions of an existing RCU read-side
1178  * critical section.
1179  */
1180 static struct rt_read_seg *
1181 rcutorture_loop_extend(int *readstate, struct torture_random_state *trsp,
1182                        struct rt_read_seg *rtrsp)
1183 {
1184         int i;
1185         int j;
1186         int mask = rcutorture_extend_mask_max();
1187
1188         WARN_ON_ONCE(!*readstate); /* -Existing- RCU read-side critsect! */
1189         if (!((mask - 1) & mask))
1190                 return rtrsp;  /* Current RCU reader not extendable. */
1191         /* Bias towards larger numbers of loops. */
1192         i = (torture_random(trsp) >> 3);
1193         i = ((i | (i >> 3)) & RCUTORTURE_RDR_MAX_LOOPS) + 1;
1194         for (j = 0; j < i; j++) {
1195                 mask = rcutorture_extend_mask(*readstate, trsp);
1196                 rcutorture_one_extend(readstate, mask, trsp, &rtrsp[j]);
1197         }
1198         return &rtrsp[j];
1199 }
1200
1201 /*
1202  * Do one read-side critical section, returning false if there was
1203  * no data to read.  Can be invoked both from process context and
1204  * from a timer handler.
1205  */
1206 static bool rcu_torture_one_read(struct torture_random_state *trsp)
1207 {
1208         int i;
1209         unsigned long started;
1210         unsigned long completed;
1211         int newstate;
1212         struct rcu_torture *p;
1213         int pipe_count;
1214         int readstate = 0;
1215         struct rt_read_seg rtseg[RCUTORTURE_RDR_MAX_SEGS] = { { 0 } };
1216         struct rt_read_seg *rtrsp = &rtseg[0];
1217         struct rt_read_seg *rtrsp1;
1218         unsigned long long ts;
1219
1220         newstate = rcutorture_extend_mask(readstate, trsp);
1221         rcutorture_one_extend(&readstate, newstate, trsp, rtrsp++);
1222         started = cur_ops->get_gp_seq();
1223         ts = rcu_trace_clock_local();
1224         p = rcu_dereference_check(rcu_torture_current,
1225                                   rcu_read_lock_bh_held() ||
1226                                   rcu_read_lock_sched_held() ||
1227                                   srcu_read_lock_held(srcu_ctlp) ||
1228                                   torturing_tasks());
1229         if (p == NULL) {
1230                 /* Wait for rcu_torture_writer to get underway */
1231                 rcutorture_one_extend(&readstate, 0, trsp, rtrsp);
1232                 return false;
1233         }
1234         if (p->rtort_mbtest == 0)
1235                 atomic_inc(&n_rcu_torture_mberror);
1236         rtrsp = rcutorture_loop_extend(&readstate, trsp, rtrsp);
1237         preempt_disable();
1238         pipe_count = p->rtort_pipe_count;
1239         if (pipe_count > RCU_TORTURE_PIPE_LEN) {
1240                 /* Should not happen, but... */
1241                 pipe_count = RCU_TORTURE_PIPE_LEN;
1242         }
1243         completed = cur_ops->get_gp_seq();
1244         if (pipe_count > 1) {
1245                 do_trace_rcu_torture_read(cur_ops->name, &p->rtort_rcu,
1246                                           ts, started, completed);
1247                 rcu_ftrace_dump(DUMP_ALL);
1248         }
1249         __this_cpu_inc(rcu_torture_count[pipe_count]);
1250         completed = rcutorture_seq_diff(completed, started);
1251         if (completed > RCU_TORTURE_PIPE_LEN) {
1252                 /* Should not happen, but... */
1253                 completed = RCU_TORTURE_PIPE_LEN;
1254         }
1255         __this_cpu_inc(rcu_torture_batch[completed]);
1256         preempt_enable();
1257         rcutorture_one_extend(&readstate, 0, trsp, rtrsp);
1258         WARN_ON_ONCE(readstate & RCUTORTURE_RDR_MASK);
1259
1260         /* If error or close call, record the sequence of reader protections. */
1261         if ((pipe_count > 1 || completed > 1) && !xchg(&err_segs_recorded, 1)) {
1262                 i = 0;
1263                 for (rtrsp1 = &rtseg[0]; rtrsp1 < rtrsp; rtrsp1++)
1264                         err_segs[i++] = *rtrsp1;
1265                 rt_read_nsegs = i;
1266         }
1267
1268         return true;
1269 }
1270
1271 static DEFINE_TORTURE_RANDOM_PERCPU(rcu_torture_timer_rand);
1272
1273 /*
1274  * RCU torture reader from timer handler.  Dereferences rcu_torture_current,
1275  * incrementing the corresponding element of the pipeline array.  The
1276  * counter in the element should never be greater than 1, otherwise, the
1277  * RCU implementation is broken.
1278  */
1279 static void rcu_torture_timer(struct timer_list *unused)
1280 {
1281         atomic_long_inc(&n_rcu_torture_timers);
1282         (void)rcu_torture_one_read(this_cpu_ptr(&rcu_torture_timer_rand));
1283
1284         /* Test call_rcu() invocation from interrupt handler. */
1285         if (cur_ops->call) {
1286                 struct rcu_head *rhp = kmalloc(sizeof(*rhp), GFP_NOWAIT);
1287
1288                 if (rhp)
1289                         cur_ops->call(rhp, rcu_torture_timer_cb);
1290         }
1291 }
1292
1293 /*
1294  * RCU torture reader kthread.  Repeatedly dereferences rcu_torture_current,
1295  * incrementing the corresponding element of the pipeline array.  The
1296  * counter in the element should never be greater than 1, otherwise, the
1297  * RCU implementation is broken.
1298  */
1299 static int
1300 rcu_torture_reader(void *arg)
1301 {
1302         unsigned long lastsleep = jiffies;
1303         long myid = (long)arg;
1304         int mynumonline = myid;
1305         DEFINE_TORTURE_RANDOM(rand);
1306         struct timer_list t;
1307
1308         VERBOSE_TOROUT_STRING("rcu_torture_reader task started");
1309         set_user_nice(current, MAX_NICE);
1310         if (irqreader && cur_ops->irq_capable)
1311                 timer_setup_on_stack(&t, rcu_torture_timer, 0);
1312
1313         do {
1314                 if (irqreader && cur_ops->irq_capable) {
1315                         if (!timer_pending(&t))
1316                                 mod_timer(&t, jiffies + 1);
1317                 }
1318                 if (!rcu_torture_one_read(&rand))
1319                         schedule_timeout_interruptible(HZ);
1320                 if (time_after(jiffies, lastsleep)) {
1321                         schedule_timeout_interruptible(1);
1322                         lastsleep = jiffies + 10;
1323                 }
1324                 while (num_online_cpus() < mynumonline && !torture_must_stop())
1325                         schedule_timeout_interruptible(HZ / 5);
1326                 stutter_wait("rcu_torture_reader");
1327         } while (!torture_must_stop());
1328         if (irqreader && cur_ops->irq_capable) {
1329                 del_timer_sync(&t);
1330                 destroy_timer_on_stack(&t);
1331         }
1332         torture_kthread_stopping("rcu_torture_reader");
1333         return 0;
1334 }
1335
1336 /*
1337  * Print torture statistics.  Caller must ensure that there is only
1338  * one call to this function at a given time!!!  This is normally
1339  * accomplished by relying on the module system to only have one copy
1340  * of the module loaded, and then by giving the rcu_torture_stats
1341  * kthread full control (or the init/cleanup functions when rcu_torture_stats
1342  * thread is not running).
1343  */
1344 static void
1345 rcu_torture_stats_print(void)
1346 {
1347         int cpu;
1348         int i;
1349         long pipesummary[RCU_TORTURE_PIPE_LEN + 1] = { 0 };
1350         long batchsummary[RCU_TORTURE_PIPE_LEN + 1] = { 0 };
1351         static unsigned long rtcv_snap = ULONG_MAX;
1352         static bool splatted;
1353         struct task_struct *wtp;
1354
1355         for_each_possible_cpu(cpu) {
1356                 for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++) {
1357                         pipesummary[i] += per_cpu(rcu_torture_count, cpu)[i];
1358                         batchsummary[i] += per_cpu(rcu_torture_batch, cpu)[i];
1359                 }
1360         }
1361         for (i = RCU_TORTURE_PIPE_LEN - 1; i >= 0; i--) {
1362                 if (pipesummary[i] != 0)
1363                         break;
1364         }
1365
1366         pr_alert("%s%s ", torture_type, TORTURE_FLAG);
1367         pr_cont("rtc: %p ver: %lu tfle: %d rta: %d rtaf: %d rtf: %d ",
1368                 rcu_torture_current,
1369                 rcu_torture_current_version,
1370                 list_empty(&rcu_torture_freelist),
1371                 atomic_read(&n_rcu_torture_alloc),
1372                 atomic_read(&n_rcu_torture_alloc_fail),
1373                 atomic_read(&n_rcu_torture_free));
1374         pr_cont("rtmbe: %d rtbe: %ld rtbke: %ld rtbre: %ld ",
1375                 atomic_read(&n_rcu_torture_mberror),
1376                 n_rcu_torture_barrier_error,
1377                 n_rcu_torture_boost_ktrerror,
1378                 n_rcu_torture_boost_rterror);
1379         pr_cont("rtbf: %ld rtb: %ld nt: %ld ",
1380                 n_rcu_torture_boost_failure,
1381                 n_rcu_torture_boosts,
1382                 atomic_long_read(&n_rcu_torture_timers));
1383         torture_onoff_stats();
1384         pr_cont("barrier: %ld/%ld:%ld\n",
1385                 n_barrier_successes,
1386                 n_barrier_attempts,
1387                 n_rcu_torture_barrier_error);
1388
1389         pr_alert("%s%s ", torture_type, TORTURE_FLAG);
1390         if (atomic_read(&n_rcu_torture_mberror) != 0 ||
1391             n_rcu_torture_barrier_error != 0 ||
1392             n_rcu_torture_boost_ktrerror != 0 ||
1393             n_rcu_torture_boost_rterror != 0 ||
1394             n_rcu_torture_boost_failure != 0 ||
1395             i > 1) {
1396                 pr_cont("%s", "!!! ");
1397                 atomic_inc(&n_rcu_torture_error);
1398                 WARN_ON_ONCE(1);
1399         }
1400         pr_cont("Reader Pipe: ");
1401         for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++)
1402                 pr_cont(" %ld", pipesummary[i]);
1403         pr_cont("\n");
1404
1405         pr_alert("%s%s ", torture_type, TORTURE_FLAG);
1406         pr_cont("Reader Batch: ");
1407         for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++)
1408                 pr_cont(" %ld", batchsummary[i]);
1409         pr_cont("\n");
1410
1411         pr_alert("%s%s ", torture_type, TORTURE_FLAG);
1412         pr_cont("Free-Block Circulation: ");
1413         for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++) {
1414                 pr_cont(" %d", atomic_read(&rcu_torture_wcount[i]));
1415         }
1416         pr_cont("\n");
1417
1418         if (cur_ops->stats)
1419                 cur_ops->stats();
1420         if (rtcv_snap == rcu_torture_current_version &&
1421             rcu_torture_current != NULL) {
1422                 int __maybe_unused flags = 0;
1423                 unsigned long __maybe_unused gp_seq = 0;
1424
1425                 rcutorture_get_gp_data(cur_ops->ttype,
1426                                        &flags, &gp_seq);
1427                 srcutorture_get_gp_data(cur_ops->ttype, srcu_ctlp,
1428                                         &flags, &gp_seq);
1429                 wtp = READ_ONCE(writer_task);
1430                 pr_alert("??? Writer stall state %s(%d) g%lu f%#x ->state %#lx cpu %d\n",
1431                          rcu_torture_writer_state_getname(),
1432                          rcu_torture_writer_state, gp_seq, flags,
1433                          wtp == NULL ? ~0UL : wtp->state,
1434                          wtp == NULL ? -1 : (int)task_cpu(wtp));
1435                 if (!splatted && wtp) {
1436                         sched_show_task(wtp);
1437                         splatted = true;
1438                 }
1439                 show_rcu_gp_kthreads();
1440                 rcu_ftrace_dump(DUMP_ALL);
1441         }
1442         rtcv_snap = rcu_torture_current_version;
1443 }
1444
1445 /*
1446  * Periodically prints torture statistics, if periodic statistics printing
1447  * was specified via the stat_interval module parameter.
1448  */
1449 static int
1450 rcu_torture_stats(void *arg)
1451 {
1452         VERBOSE_TOROUT_STRING("rcu_torture_stats task started");
1453         do {
1454                 schedule_timeout_interruptible(stat_interval * HZ);
1455                 rcu_torture_stats_print();
1456                 torture_shutdown_absorb("rcu_torture_stats");
1457         } while (!torture_must_stop());
1458         torture_kthread_stopping("rcu_torture_stats");
1459         return 0;
1460 }
1461
1462 static void
1463 rcu_torture_print_module_parms(struct rcu_torture_ops *cur_ops, const char *tag)
1464 {
1465         pr_alert("%s" TORTURE_FLAG
1466                  "--- %s: nreaders=%d nfakewriters=%d "
1467                  "stat_interval=%d verbose=%d test_no_idle_hz=%d "
1468                  "shuffle_interval=%d stutter=%d irqreader=%d "
1469                  "fqs_duration=%d fqs_holdoff=%d fqs_stutter=%d "
1470                  "test_boost=%d/%d test_boost_interval=%d "
1471                  "test_boost_duration=%d shutdown_secs=%d "
1472                  "stall_cpu=%d stall_cpu_holdoff=%d stall_cpu_irqsoff=%d "
1473                  "n_barrier_cbs=%d "
1474                  "onoff_interval=%d onoff_holdoff=%d\n",
1475                  torture_type, tag, nrealreaders, nfakewriters,
1476                  stat_interval, verbose, test_no_idle_hz, shuffle_interval,
1477                  stutter, irqreader, fqs_duration, fqs_holdoff, fqs_stutter,
1478                  test_boost, cur_ops->can_boost,
1479                  test_boost_interval, test_boost_duration, shutdown_secs,
1480                  stall_cpu, stall_cpu_holdoff, stall_cpu_irqsoff,
1481                  n_barrier_cbs,
1482                  onoff_interval, onoff_holdoff);
1483 }
1484
1485 static int rcutorture_booster_cleanup(unsigned int cpu)
1486 {
1487         struct task_struct *t;
1488
1489         if (boost_tasks[cpu] == NULL)
1490                 return 0;
1491         mutex_lock(&boost_mutex);
1492         t = boost_tasks[cpu];
1493         boost_tasks[cpu] = NULL;
1494         rcu_torture_enable_rt_throttle();
1495         mutex_unlock(&boost_mutex);
1496
1497         /* This must be outside of the mutex, otherwise deadlock! */
1498         torture_stop_kthread(rcu_torture_boost, t);
1499         return 0;
1500 }
1501
1502 static int rcutorture_booster_init(unsigned int cpu)
1503 {
1504         int retval;
1505
1506         if (boost_tasks[cpu] != NULL)
1507                 return 0;  /* Already created, nothing more to do. */
1508
1509         /* Don't allow time recalculation while creating a new task. */
1510         mutex_lock(&boost_mutex);
1511         rcu_torture_disable_rt_throttle();
1512         VERBOSE_TOROUT_STRING("Creating rcu_torture_boost task");
1513         boost_tasks[cpu] = kthread_create_on_node(rcu_torture_boost, NULL,
1514                                                   cpu_to_node(cpu),
1515                                                   "rcu_torture_boost");
1516         if (IS_ERR(boost_tasks[cpu])) {
1517                 retval = PTR_ERR(boost_tasks[cpu]);
1518                 VERBOSE_TOROUT_STRING("rcu_torture_boost task create failed");
1519                 n_rcu_torture_boost_ktrerror++;
1520                 boost_tasks[cpu] = NULL;
1521                 mutex_unlock(&boost_mutex);
1522                 return retval;
1523         }
1524         kthread_bind(boost_tasks[cpu], cpu);
1525         wake_up_process(boost_tasks[cpu]);
1526         mutex_unlock(&boost_mutex);
1527         return 0;
1528 }
1529
1530 /*
1531  * CPU-stall kthread.  It waits as specified by stall_cpu_holdoff, then
1532  * induces a CPU stall for the time specified by stall_cpu.
1533  */
1534 static int rcu_torture_stall(void *args)
1535 {
1536         unsigned long stop_at;
1537
1538         VERBOSE_TOROUT_STRING("rcu_torture_stall task started");
1539         if (stall_cpu_holdoff > 0) {
1540                 VERBOSE_TOROUT_STRING("rcu_torture_stall begin holdoff");
1541                 schedule_timeout_interruptible(stall_cpu_holdoff * HZ);
1542                 VERBOSE_TOROUT_STRING("rcu_torture_stall end holdoff");
1543         }
1544         if (!kthread_should_stop()) {
1545                 stop_at = ktime_get_seconds() + stall_cpu;
1546                 /* RCU CPU stall is expected behavior in following code. */
1547                 rcu_read_lock();
1548                 if (stall_cpu_irqsoff)
1549                         local_irq_disable();
1550                 else
1551                         preempt_disable();
1552                 pr_alert("rcu_torture_stall start on CPU %d.\n",
1553                          smp_processor_id());
1554                 while (ULONG_CMP_LT((unsigned long)ktime_get_seconds(),
1555                                     stop_at))
1556                         continue;  /* Induce RCU CPU stall warning. */
1557                 if (stall_cpu_irqsoff)
1558                         local_irq_enable();
1559                 else
1560                         preempt_enable();
1561                 rcu_read_unlock();
1562                 pr_alert("rcu_torture_stall end.\n");
1563         }
1564         torture_shutdown_absorb("rcu_torture_stall");
1565         while (!kthread_should_stop())
1566                 schedule_timeout_interruptible(10 * HZ);
1567         return 0;
1568 }
1569
1570 /* Spawn CPU-stall kthread, if stall_cpu specified. */
1571 static int __init rcu_torture_stall_init(void)
1572 {
1573         if (stall_cpu <= 0)
1574                 return 0;
1575         return torture_create_kthread(rcu_torture_stall, NULL, stall_task);
1576 }
1577
1578 /* State structure for forward-progress self-propagating RCU callback. */
1579 struct fwd_cb_state {
1580         struct rcu_head rh;
1581         int stop;
1582 };
1583
1584 /*
1585  * Forward-progress self-propagating RCU callback function.  Because
1586  * callbacks run from softirq, this function is an implicit RCU read-side
1587  * critical section.
1588  */
1589 static void rcu_torture_fwd_prog_cb(struct rcu_head *rhp)
1590 {
1591         struct fwd_cb_state *fcsp = container_of(rhp, struct fwd_cb_state, rh);
1592
1593         if (READ_ONCE(fcsp->stop)) {
1594                 WRITE_ONCE(fcsp->stop, 2);
1595                 return;
1596         }
1597         cur_ops->call(&fcsp->rh, rcu_torture_fwd_prog_cb);
1598 }
1599
1600 /* State for continuous-flood RCU callbacks. */
1601 struct rcu_fwd_cb {
1602         struct rcu_head rh;
1603         struct rcu_fwd_cb *rfc_next;
1604         int rfc_gps;
1605 };
1606 static DEFINE_SPINLOCK(rcu_fwd_lock);
1607 static struct rcu_fwd_cb *rcu_fwd_cb_head;
1608 static struct rcu_fwd_cb **rcu_fwd_cb_tail = &rcu_fwd_cb_head;
1609 static long n_launders_cb;
1610 static unsigned long rcu_fwd_startat;
1611 static bool rcu_fwd_emergency_stop;
1612 #define MAX_FWD_CB_JIFFIES      (8 * HZ) /* Maximum CB test duration. */
1613 #define MIN_FWD_CB_LAUNDERS     3       /* This many CB invocations to count. */
1614 #define MIN_FWD_CBS_LAUNDERED   100     /* Number of counted CBs. */
1615 #define FWD_CBS_HIST_DIV        10      /* Histogram buckets/second. */
1616 struct rcu_launder_hist {
1617         long n_launders;
1618         unsigned long launder_gp_seq;
1619 };
1620 #define N_LAUNDERS_HIST (2 * MAX_FWD_CB_JIFFIES / (HZ / FWD_CBS_HIST_DIV))
1621 static struct rcu_launder_hist n_launders_hist[N_LAUNDERS_HIST];
1622 static unsigned long rcu_launder_gp_seq_start;
1623
1624 static void rcu_torture_fwd_cb_hist(void)
1625 {
1626         unsigned long gps;
1627         unsigned long gps_old;
1628         int i;
1629         int j;
1630
1631         for (i = ARRAY_SIZE(n_launders_hist) - 1; i > 0; i--)
1632                 if (n_launders_hist[i].n_launders > 0)
1633                         break;
1634         pr_alert("%s: Callback-invocation histogram (duration %lu jiffies):",
1635                  __func__, jiffies - rcu_fwd_startat);
1636         gps_old = rcu_launder_gp_seq_start;
1637         for (j = 0; j <= i; j++) {
1638                 gps = n_launders_hist[j].launder_gp_seq;
1639                 pr_cont(" %ds/%d: %ld:%ld",
1640                         j + 1, FWD_CBS_HIST_DIV, n_launders_hist[j].n_launders,
1641                         rcutorture_seq_diff(gps, gps_old));
1642                 gps_old = gps;
1643         }
1644         pr_cont("\n");
1645 }
1646
1647 /* Callback function for continuous-flood RCU callbacks. */
1648 static void rcu_torture_fwd_cb_cr(struct rcu_head *rhp)
1649 {
1650         unsigned long flags;
1651         int i;
1652         struct rcu_fwd_cb *rfcp = container_of(rhp, struct rcu_fwd_cb, rh);
1653         struct rcu_fwd_cb **rfcpp;
1654
1655         rfcp->rfc_next = NULL;
1656         rfcp->rfc_gps++;
1657         spin_lock_irqsave(&rcu_fwd_lock, flags);
1658         rfcpp = rcu_fwd_cb_tail;
1659         rcu_fwd_cb_tail = &rfcp->rfc_next;
1660         WRITE_ONCE(*rfcpp, rfcp);
1661         WRITE_ONCE(n_launders_cb, n_launders_cb + 1);
1662         i = ((jiffies - rcu_fwd_startat) / (HZ / FWD_CBS_HIST_DIV));
1663         if (i >= ARRAY_SIZE(n_launders_hist))
1664                 i = ARRAY_SIZE(n_launders_hist) - 1;
1665         n_launders_hist[i].n_launders++;
1666         n_launders_hist[i].launder_gp_seq = cur_ops->get_gp_seq();
1667         spin_unlock_irqrestore(&rcu_fwd_lock, flags);
1668 }
1669
1670 /*
1671  * Free all callbacks on the rcu_fwd_cb_head list, either because the
1672  * test is over or because we hit an OOM event.
1673  */
1674 static unsigned long rcu_torture_fwd_prog_cbfree(void)
1675 {
1676         unsigned long flags;
1677         unsigned long freed = 0;
1678         struct rcu_fwd_cb *rfcp;
1679
1680         for (;;) {
1681                 spin_lock_irqsave(&rcu_fwd_lock, flags);
1682                 rfcp = rcu_fwd_cb_head;
1683                 if (!rfcp) {
1684                         spin_unlock_irqrestore(&rcu_fwd_lock, flags);
1685                         break;
1686                 }
1687                 rcu_fwd_cb_head = rfcp->rfc_next;
1688                 if (!rcu_fwd_cb_head)
1689                         rcu_fwd_cb_tail = &rcu_fwd_cb_head;
1690                 spin_unlock_irqrestore(&rcu_fwd_lock, flags);
1691                 kfree(rfcp);
1692                 freed++;
1693                 cond_resched();
1694         }
1695         return freed;
1696 }
1697
1698 /* Carry out need_resched()/cond_resched() forward-progress testing. */
1699 static void rcu_torture_fwd_prog_nr(int *tested, int *tested_tries)
1700 {
1701         unsigned long cver;
1702         unsigned long dur;
1703         struct fwd_cb_state fcs;
1704         unsigned long gps;
1705         int idx;
1706         int sd;
1707         int sd4;
1708         bool selfpropcb = false;
1709         unsigned long stopat;
1710         static DEFINE_TORTURE_RANDOM(trs);
1711
1712         if  (cur_ops->call && cur_ops->sync && cur_ops->cb_barrier) {
1713                 init_rcu_head_on_stack(&fcs.rh);
1714                 selfpropcb = true;
1715         }
1716
1717         /* Tight loop containing cond_resched(). */
1718         WRITE_ONCE(rcu_fwd_cb_nodelay, true);
1719         cur_ops->sync(); /* Later readers see above write. */
1720         if  (selfpropcb) {
1721                 WRITE_ONCE(fcs.stop, 0);
1722                 cur_ops->call(&fcs.rh, rcu_torture_fwd_prog_cb);
1723         }
1724         cver = READ_ONCE(rcu_torture_current_version);
1725         gps = cur_ops->get_gp_seq();
1726         sd = cur_ops->stall_dur() + 1;
1727         sd4 = (sd + fwd_progress_div - 1) / fwd_progress_div;
1728         dur = sd4 + torture_random(&trs) % (sd - sd4);
1729         WRITE_ONCE(rcu_fwd_startat, jiffies);
1730         stopat = rcu_fwd_startat + dur;
1731         while (time_before(jiffies, stopat) &&
1732                !READ_ONCE(rcu_fwd_emergency_stop) && !torture_must_stop()) {
1733                 idx = cur_ops->readlock();
1734                 udelay(10);
1735                 cur_ops->readunlock(idx);
1736                 if (!fwd_progress_need_resched || need_resched())
1737                         cond_resched();
1738         }
1739         (*tested_tries)++;
1740         if (!time_before(jiffies, stopat) &&
1741             !READ_ONCE(rcu_fwd_emergency_stop) && !torture_must_stop()) {
1742                 (*tested)++;
1743                 cver = READ_ONCE(rcu_torture_current_version) - cver;
1744                 gps = rcutorture_seq_diff(cur_ops->get_gp_seq(), gps);
1745                 WARN_ON(!cver && gps < 2);
1746                 pr_alert("%s: Duration %ld cver %ld gps %ld\n", __func__, dur, cver, gps);
1747         }
1748         if (selfpropcb) {
1749                 WRITE_ONCE(fcs.stop, 1);
1750                 cur_ops->sync(); /* Wait for running CB to complete. */
1751                 cur_ops->cb_barrier(); /* Wait for queued callbacks. */
1752         }
1753
1754         if (selfpropcb) {
1755                 WARN_ON(READ_ONCE(fcs.stop) != 2);
1756                 destroy_rcu_head_on_stack(&fcs.rh);
1757         }
1758         schedule_timeout_uninterruptible(HZ / 10); /* Let kthreads recover. */
1759         WRITE_ONCE(rcu_fwd_cb_nodelay, false);
1760 }
1761
1762 /* Carry out call_rcu() forward-progress testing. */
1763 static void rcu_torture_fwd_prog_cr(void)
1764 {
1765         unsigned long cver;
1766         unsigned long gps;
1767         int i;
1768         long n_launders;
1769         long n_launders_cb_snap;
1770         long n_launders_sa;
1771         long n_max_cbs;
1772         long n_max_gps;
1773         struct rcu_fwd_cb *rfcp;
1774         struct rcu_fwd_cb *rfcpn;
1775         unsigned long stopat;
1776         unsigned long stoppedat;
1777
1778         if (READ_ONCE(rcu_fwd_emergency_stop))
1779                 return; /* Get out of the way quickly, no GP wait! */
1780
1781         /* Loop continuously posting RCU callbacks. */
1782         WRITE_ONCE(rcu_fwd_cb_nodelay, true);
1783         cur_ops->sync(); /* Later readers see above write. */
1784         WRITE_ONCE(rcu_fwd_startat, jiffies);
1785         stopat = rcu_fwd_startat + MAX_FWD_CB_JIFFIES;
1786         n_launders = 0;
1787         n_launders_cb = 0;
1788         n_launders_sa = 0;
1789         n_max_cbs = 0;
1790         n_max_gps = 0;
1791         for (i = 0; i < ARRAY_SIZE(n_launders_hist); i++)
1792                 n_launders_hist[i].n_launders = 0;
1793         cver = READ_ONCE(rcu_torture_current_version);
1794         gps = cur_ops->get_gp_seq();
1795         rcu_launder_gp_seq_start = gps;
1796         while (time_before(jiffies, stopat) &&
1797                !READ_ONCE(rcu_fwd_emergency_stop) && !torture_must_stop()) {
1798                 rfcp = READ_ONCE(rcu_fwd_cb_head);
1799                 rfcpn = NULL;
1800                 if (rfcp)
1801                         rfcpn = READ_ONCE(rfcp->rfc_next);
1802                 if (rfcpn) {
1803                         if (rfcp->rfc_gps >= MIN_FWD_CB_LAUNDERS &&
1804                             ++n_max_gps >= MIN_FWD_CBS_LAUNDERED)
1805                                 break;
1806                         rcu_fwd_cb_head = rfcpn;
1807                         n_launders++;
1808                         n_launders_sa++;
1809                 } else {
1810                         rfcp = kmalloc(sizeof(*rfcp), GFP_KERNEL);
1811                         if (WARN_ON_ONCE(!rfcp)) {
1812                                 schedule_timeout_interruptible(1);
1813                                 continue;
1814                         }
1815                         n_max_cbs++;
1816                         n_launders_sa = 0;
1817                         rfcp->rfc_gps = 0;
1818                 }
1819                 cur_ops->call(&rfcp->rh, rcu_torture_fwd_cb_cr);
1820                 cond_resched();
1821         }
1822         stoppedat = jiffies;
1823         n_launders_cb_snap = READ_ONCE(n_launders_cb);
1824         cver = READ_ONCE(rcu_torture_current_version) - cver;
1825         gps = rcutorture_seq_diff(cur_ops->get_gp_seq(), gps);
1826         cur_ops->cb_barrier(); /* Wait for callbacks to be invoked. */
1827         (void)rcu_torture_fwd_prog_cbfree();
1828
1829         if (!torture_must_stop() && !READ_ONCE(rcu_fwd_emergency_stop)) {
1830                 WARN_ON(n_max_gps < MIN_FWD_CBS_LAUNDERED);
1831                 pr_alert("%s Duration %lu barrier: %lu pending %ld n_launders: %ld n_launders_sa: %ld n_max_gps: %ld n_max_cbs: %ld cver %ld gps %ld\n",
1832                          __func__,
1833                          stoppedat - rcu_fwd_startat, jiffies - stoppedat,
1834                          n_launders + n_max_cbs - n_launders_cb_snap,
1835                          n_launders, n_launders_sa,
1836                          n_max_gps, n_max_cbs, cver, gps);
1837                 rcu_torture_fwd_cb_hist();
1838         }
1839         schedule_timeout_uninterruptible(HZ); /* Let CBs drain. */
1840         WRITE_ONCE(rcu_fwd_cb_nodelay, false);
1841 }
1842
1843
1844 /*
1845  * OOM notifier, but this only prints diagnostic information for the
1846  * current forward-progress test.
1847  */
1848 static int rcutorture_oom_notify(struct notifier_block *self,
1849                                  unsigned long notused, void *nfreed)
1850 {
1851         WARN(1, "%s invoked upon OOM during forward-progress testing.\n",
1852              __func__);
1853         rcu_torture_fwd_cb_hist();
1854         rcu_fwd_progress_check(1 + (jiffies - READ_ONCE(rcu_fwd_startat)) / 2);
1855         WRITE_ONCE(rcu_fwd_emergency_stop, true);
1856         smp_mb(); /* Emergency stop before free and wait to avoid hangs. */
1857         pr_info("%s: Freed %lu RCU callbacks.\n",
1858                 __func__, rcu_torture_fwd_prog_cbfree());
1859         rcu_barrier();
1860         pr_info("%s: Freed %lu RCU callbacks.\n",
1861                 __func__, rcu_torture_fwd_prog_cbfree());
1862         rcu_barrier();
1863         pr_info("%s: Freed %lu RCU callbacks.\n",
1864                 __func__, rcu_torture_fwd_prog_cbfree());
1865         smp_mb(); /* Frees before return to avoid redoing OOM. */
1866         (*(unsigned long *)nfreed)++; /* Forward progress CBs freed! */
1867         pr_info("%s returning after OOM processing.\n", __func__);
1868         return NOTIFY_OK;
1869 }
1870
1871 static struct notifier_block rcutorture_oom_nb = {
1872         .notifier_call = rcutorture_oom_notify
1873 };
1874
1875 /* Carry out grace-period forward-progress testing. */
1876 static int rcu_torture_fwd_prog(void *args)
1877 {
1878         int tested = 0;
1879         int tested_tries = 0;
1880
1881         VERBOSE_TOROUT_STRING("rcu_torture_fwd_progress task started");
1882         rcu_bind_current_to_nocb();
1883         if (!IS_ENABLED(CONFIG_SMP) || !IS_ENABLED(CONFIG_RCU_BOOST))
1884                 set_user_nice(current, MAX_NICE);
1885         do {
1886                 schedule_timeout_interruptible(fwd_progress_holdoff * HZ);
1887                 WRITE_ONCE(rcu_fwd_emergency_stop, false);
1888                 register_oom_notifier(&rcutorture_oom_nb);
1889                 rcu_torture_fwd_prog_nr(&tested, &tested_tries);
1890                 rcu_torture_fwd_prog_cr();
1891                 unregister_oom_notifier(&rcutorture_oom_nb);
1892
1893                 /* Avoid slow periods, better to test when busy. */
1894                 stutter_wait("rcu_torture_fwd_prog");
1895         } while (!torture_must_stop());
1896         /* Short runs might not contain a valid forward-progress attempt. */
1897         WARN_ON(!tested && tested_tries >= 5);
1898         pr_alert("%s: tested %d tested_tries %d\n", __func__, tested, tested_tries);
1899         torture_kthread_stopping("rcu_torture_fwd_prog");
1900         return 0;
1901 }
1902
1903 /* If forward-progress checking is requested and feasible, spawn the thread. */
1904 static int __init rcu_torture_fwd_prog_init(void)
1905 {
1906         if (!fwd_progress)
1907                 return 0; /* Not requested, so don't do it. */
1908         if (!cur_ops->stall_dur || cur_ops->stall_dur() <= 0 ||
1909             cur_ops == &rcu_busted_ops) {
1910                 VERBOSE_TOROUT_STRING("rcu_torture_fwd_prog_init: Disabled, unsupported by RCU flavor under test");
1911                 return 0;
1912         }
1913         if (stall_cpu > 0) {
1914                 VERBOSE_TOROUT_STRING("rcu_torture_fwd_prog_init: Disabled, conflicts with CPU-stall testing");
1915                 if (IS_MODULE(CONFIG_RCU_TORTURE_TESTS))
1916                         return -EINVAL; /* In module, can fail back to user. */
1917                 WARN_ON(1); /* Make sure rcutorture notices conflict. */
1918                 return 0;
1919         }
1920         if (fwd_progress_holdoff <= 0)
1921                 fwd_progress_holdoff = 1;
1922         if (fwd_progress_div <= 0)
1923                 fwd_progress_div = 4;
1924         return torture_create_kthread(rcu_torture_fwd_prog,
1925                                       NULL, fwd_prog_task);
1926 }
1927
1928 /* Callback function for RCU barrier testing. */
1929 static void rcu_torture_barrier_cbf(struct rcu_head *rcu)
1930 {
1931         atomic_inc(&barrier_cbs_invoked);
1932 }
1933
1934 /* kthread function to register callbacks used to test RCU barriers. */
1935 static int rcu_torture_barrier_cbs(void *arg)
1936 {
1937         long myid = (long)arg;
1938         bool lastphase = 0;
1939         bool newphase;
1940         struct rcu_head rcu;
1941
1942         init_rcu_head_on_stack(&rcu);
1943         VERBOSE_TOROUT_STRING("rcu_torture_barrier_cbs task started");
1944         set_user_nice(current, MAX_NICE);
1945         do {
1946                 wait_event(barrier_cbs_wq[myid],
1947                            (newphase =
1948                             smp_load_acquire(&barrier_phase)) != lastphase ||
1949                            torture_must_stop());
1950                 lastphase = newphase;
1951                 if (torture_must_stop())
1952                         break;
1953                 /*
1954                  * The above smp_load_acquire() ensures barrier_phase load
1955                  * is ordered before the following ->call().
1956                  */
1957                 local_irq_disable(); /* Just to test no-irq call_rcu(). */
1958                 cur_ops->call(&rcu, rcu_torture_barrier_cbf);
1959                 local_irq_enable();
1960                 if (atomic_dec_and_test(&barrier_cbs_count))
1961                         wake_up(&barrier_wq);
1962         } while (!torture_must_stop());
1963         if (cur_ops->cb_barrier != NULL)
1964                 cur_ops->cb_barrier();
1965         destroy_rcu_head_on_stack(&rcu);
1966         torture_kthread_stopping("rcu_torture_barrier_cbs");
1967         return 0;
1968 }
1969
1970 /* kthread function to drive and coordinate RCU barrier testing. */
1971 static int rcu_torture_barrier(void *arg)
1972 {
1973         int i;
1974
1975         VERBOSE_TOROUT_STRING("rcu_torture_barrier task starting");
1976         do {
1977                 atomic_set(&barrier_cbs_invoked, 0);
1978                 atomic_set(&barrier_cbs_count, n_barrier_cbs);
1979                 /* Ensure barrier_phase ordered after prior assignments. */
1980                 smp_store_release(&barrier_phase, !barrier_phase);
1981                 for (i = 0; i < n_barrier_cbs; i++)
1982                         wake_up(&barrier_cbs_wq[i]);
1983                 wait_event(barrier_wq,
1984                            atomic_read(&barrier_cbs_count) == 0 ||
1985                            torture_must_stop());
1986                 if (torture_must_stop())
1987                         break;
1988                 n_barrier_attempts++;
1989                 cur_ops->cb_barrier(); /* Implies smp_mb() for wait_event(). */
1990                 if (atomic_read(&barrier_cbs_invoked) != n_barrier_cbs) {
1991                         n_rcu_torture_barrier_error++;
1992                         pr_err("barrier_cbs_invoked = %d, n_barrier_cbs = %d\n",
1993                                atomic_read(&barrier_cbs_invoked),
1994                                n_barrier_cbs);
1995                         WARN_ON_ONCE(1);
1996                 } else {
1997                         n_barrier_successes++;
1998                 }
1999                 schedule_timeout_interruptible(HZ / 10);
2000         } while (!torture_must_stop());
2001         torture_kthread_stopping("rcu_torture_barrier");
2002         return 0;
2003 }
2004
2005 /* Initialize RCU barrier testing. */
2006 static int rcu_torture_barrier_init(void)
2007 {
2008         int i;
2009         int ret;
2010
2011         if (n_barrier_cbs <= 0)
2012                 return 0;
2013         if (cur_ops->call == NULL || cur_ops->cb_barrier == NULL) {
2014                 pr_alert("%s" TORTURE_FLAG
2015                          " Call or barrier ops missing for %s,\n",
2016                          torture_type, cur_ops->name);
2017                 pr_alert("%s" TORTURE_FLAG
2018                          " RCU barrier testing omitted from run.\n",
2019                          torture_type);
2020                 return 0;
2021         }
2022         atomic_set(&barrier_cbs_count, 0);
2023         atomic_set(&barrier_cbs_invoked, 0);
2024         barrier_cbs_tasks =
2025                 kcalloc(n_barrier_cbs, sizeof(barrier_cbs_tasks[0]),
2026                         GFP_KERNEL);
2027         barrier_cbs_wq =
2028                 kcalloc(n_barrier_cbs, sizeof(barrier_cbs_wq[0]), GFP_KERNEL);
2029         if (barrier_cbs_tasks == NULL || !barrier_cbs_wq)
2030                 return -ENOMEM;
2031         for (i = 0; i < n_barrier_cbs; i++) {
2032                 init_waitqueue_head(&barrier_cbs_wq[i]);
2033                 ret = torture_create_kthread(rcu_torture_barrier_cbs,
2034                                              (void *)(long)i,
2035                                              barrier_cbs_tasks[i]);
2036                 if (ret)
2037                         return ret;
2038         }
2039         return torture_create_kthread(rcu_torture_barrier, NULL, barrier_task);
2040 }
2041
2042 /* Clean up after RCU barrier testing. */
2043 static void rcu_torture_barrier_cleanup(void)
2044 {
2045         int i;
2046
2047         torture_stop_kthread(rcu_torture_barrier, barrier_task);
2048         if (barrier_cbs_tasks != NULL) {
2049                 for (i = 0; i < n_barrier_cbs; i++)
2050                         torture_stop_kthread(rcu_torture_barrier_cbs,
2051                                              barrier_cbs_tasks[i]);
2052                 kfree(barrier_cbs_tasks);
2053                 barrier_cbs_tasks = NULL;
2054         }
2055         if (barrier_cbs_wq != NULL) {
2056                 kfree(barrier_cbs_wq);
2057                 barrier_cbs_wq = NULL;
2058         }
2059 }
2060
2061 static bool rcu_torture_can_boost(void)
2062 {
2063         static int boost_warn_once;
2064         int prio;
2065
2066         if (!(test_boost == 1 && cur_ops->can_boost) && test_boost != 2)
2067                 return false;
2068
2069         prio = rcu_get_gp_kthreads_prio();
2070         if (!prio)
2071                 return false;
2072
2073         if (prio < 2) {
2074                 if (boost_warn_once  == 1)
2075                         return false;
2076
2077                 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);
2078                 boost_warn_once = 1;
2079                 return false;
2080         }
2081
2082         return true;
2083 }
2084
2085 static enum cpuhp_state rcutor_hp;
2086
2087 static void
2088 rcu_torture_cleanup(void)
2089 {
2090         int firsttime;
2091         int flags = 0;
2092         unsigned long gp_seq = 0;
2093         int i;
2094
2095         if (torture_cleanup_begin()) {
2096                 if (cur_ops->cb_barrier != NULL)
2097                         cur_ops->cb_barrier();
2098                 return;
2099         }
2100         if (!cur_ops) {
2101                 torture_cleanup_end();
2102                 return;
2103         }
2104
2105         rcu_torture_barrier_cleanup();
2106         torture_stop_kthread(rcu_torture_fwd_prog, fwd_prog_task);
2107         torture_stop_kthread(rcu_torture_stall, stall_task);
2108         torture_stop_kthread(rcu_torture_writer, writer_task);
2109
2110         if (reader_tasks) {
2111                 for (i = 0; i < nrealreaders; i++)
2112                         torture_stop_kthread(rcu_torture_reader,
2113                                              reader_tasks[i]);
2114                 kfree(reader_tasks);
2115         }
2116         rcu_torture_current = NULL;
2117
2118         if (fakewriter_tasks) {
2119                 for (i = 0; i < nfakewriters; i++) {
2120                         torture_stop_kthread(rcu_torture_fakewriter,
2121                                              fakewriter_tasks[i]);
2122                 }
2123                 kfree(fakewriter_tasks);
2124                 fakewriter_tasks = NULL;
2125         }
2126
2127         rcutorture_get_gp_data(cur_ops->ttype, &flags, &gp_seq);
2128         srcutorture_get_gp_data(cur_ops->ttype, srcu_ctlp, &flags, &gp_seq);
2129         pr_alert("%s:  End-test grace-period state: g%lu f%#x\n",
2130                  cur_ops->name, gp_seq, flags);
2131         torture_stop_kthread(rcu_torture_stats, stats_task);
2132         torture_stop_kthread(rcu_torture_fqs, fqs_task);
2133         if (rcu_torture_can_boost())
2134                 cpuhp_remove_state(rcutor_hp);
2135
2136         /*
2137          * Wait for all RCU callbacks to fire, then do torture-type-specific
2138          * cleanup operations.
2139          */
2140         if (cur_ops->cb_barrier != NULL)
2141                 cur_ops->cb_barrier();
2142         if (cur_ops->cleanup != NULL)
2143                 cur_ops->cleanup();
2144
2145         rcu_torture_stats_print();  /* -After- the stats thread is stopped! */
2146
2147         if (err_segs_recorded) {
2148                 pr_alert("Failure/close-call rcutorture reader segments:\n");
2149                 if (rt_read_nsegs == 0)
2150                         pr_alert("\t: No segments recorded!!!\n");
2151                 firsttime = 1;
2152                 for (i = 0; i < rt_read_nsegs; i++) {
2153                         pr_alert("\t%d: %#x ", i, err_segs[i].rt_readstate);
2154                         if (err_segs[i].rt_delay_jiffies != 0) {
2155                                 pr_cont("%s%ldjiffies", firsttime ? "" : "+",
2156                                         err_segs[i].rt_delay_jiffies);
2157                                 firsttime = 0;
2158                         }
2159                         if (err_segs[i].rt_delay_ms != 0) {
2160                                 pr_cont("%s%ldms", firsttime ? "" : "+",
2161                                         err_segs[i].rt_delay_ms);
2162                                 firsttime = 0;
2163                         }
2164                         if (err_segs[i].rt_delay_us != 0) {
2165                                 pr_cont("%s%ldus", firsttime ? "" : "+",
2166                                         err_segs[i].rt_delay_us);
2167                                 firsttime = 0;
2168                         }
2169                         pr_cont("%s\n",
2170                                 err_segs[i].rt_preempted ? "preempted" : "");
2171
2172                 }
2173         }
2174         if (atomic_read(&n_rcu_torture_error) || n_rcu_torture_barrier_error)
2175                 rcu_torture_print_module_parms(cur_ops, "End of test: FAILURE");
2176         else if (torture_onoff_failures())
2177                 rcu_torture_print_module_parms(cur_ops,
2178                                                "End of test: RCU_HOTPLUG");
2179         else
2180                 rcu_torture_print_module_parms(cur_ops, "End of test: SUCCESS");
2181         torture_cleanup_end();
2182 }
2183
2184 #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD
2185 static void rcu_torture_leak_cb(struct rcu_head *rhp)
2186 {
2187 }
2188
2189 static void rcu_torture_err_cb(struct rcu_head *rhp)
2190 {
2191         /*
2192          * This -might- happen due to race conditions, but is unlikely.
2193          * The scenario that leads to this happening is that the
2194          * first of the pair of duplicate callbacks is queued,
2195          * someone else starts a grace period that includes that
2196          * callback, then the second of the pair must wait for the
2197          * next grace period.  Unlikely, but can happen.  If it
2198          * does happen, the debug-objects subsystem won't have splatted.
2199          */
2200         pr_alert("%s: duplicated callback was invoked.\n", KBUILD_MODNAME);
2201 }
2202 #endif /* #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD */
2203
2204 /*
2205  * Verify that double-free causes debug-objects to complain, but only
2206  * if CONFIG_DEBUG_OBJECTS_RCU_HEAD=y.  Otherwise, say that the test
2207  * cannot be carried out.
2208  */
2209 static void rcu_test_debug_objects(void)
2210 {
2211 #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD
2212         struct rcu_head rh1;
2213         struct rcu_head rh2;
2214
2215         init_rcu_head_on_stack(&rh1);
2216         init_rcu_head_on_stack(&rh2);
2217         pr_alert("%s: WARN: Duplicate call_rcu() test starting.\n", KBUILD_MODNAME);
2218
2219         /* Try to queue the rh2 pair of callbacks for the same grace period. */
2220         preempt_disable(); /* Prevent preemption from interrupting test. */
2221         rcu_read_lock(); /* Make it impossible to finish a grace period. */
2222         call_rcu(&rh1, rcu_torture_leak_cb); /* Start grace period. */
2223         local_irq_disable(); /* Make it harder to start a new grace period. */
2224         call_rcu(&rh2, rcu_torture_leak_cb);
2225         call_rcu(&rh2, rcu_torture_err_cb); /* Duplicate callback. */
2226         local_irq_enable();
2227         rcu_read_unlock();
2228         preempt_enable();
2229
2230         /* Wait for them all to get done so we can safely return. */
2231         rcu_barrier();
2232         pr_alert("%s: WARN: Duplicate call_rcu() test complete.\n", KBUILD_MODNAME);
2233         destroy_rcu_head_on_stack(&rh1);
2234         destroy_rcu_head_on_stack(&rh2);
2235 #else /* #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD */
2236         pr_alert("%s: !CONFIG_DEBUG_OBJECTS_RCU_HEAD, not testing duplicate call_rcu()\n", KBUILD_MODNAME);
2237 #endif /* #else #ifdef CONFIG_DEBUG_OBJECTS_RCU_HEAD */
2238 }
2239
2240 static void rcutorture_sync(void)
2241 {
2242         static unsigned long n;
2243
2244         if (cur_ops->sync && !(++n & 0xfff))
2245                 cur_ops->sync();
2246 }
2247
2248 static int __init
2249 rcu_torture_init(void)
2250 {
2251         long i;
2252         int cpu;
2253         int firsterr = 0;
2254         static struct rcu_torture_ops *torture_ops[] = {
2255                 &rcu_ops, &rcu_busted_ops, &srcu_ops, &srcud_ops,
2256                 &busted_srcud_ops, &tasks_ops,
2257         };
2258
2259         if (!torture_init_begin(torture_type, verbose))
2260                 return -EBUSY;
2261
2262         /* Process args and tell the world that the torturer is on the job. */
2263         for (i = 0; i < ARRAY_SIZE(torture_ops); i++) {
2264                 cur_ops = torture_ops[i];
2265                 if (strcmp(torture_type, cur_ops->name) == 0)
2266                         break;
2267         }
2268         if (i == ARRAY_SIZE(torture_ops)) {
2269                 pr_alert("rcu-torture: invalid torture type: \"%s\"\n",
2270                          torture_type);
2271                 pr_alert("rcu-torture types:");
2272                 for (i = 0; i < ARRAY_SIZE(torture_ops); i++)
2273                         pr_cont(" %s", torture_ops[i]->name);
2274                 pr_cont("\n");
2275                 WARN_ON(!IS_MODULE(CONFIG_RCU_TORTURE_TEST));
2276                 firsterr = -EINVAL;
2277                 cur_ops = NULL;
2278                 goto unwind;
2279         }
2280         if (cur_ops->fqs == NULL && fqs_duration != 0) {
2281                 pr_alert("rcu-torture: ->fqs NULL and non-zero fqs_duration, fqs disabled.\n");
2282                 fqs_duration = 0;
2283         }
2284         if (cur_ops->init)
2285                 cur_ops->init();
2286
2287         if (nreaders >= 0) {
2288                 nrealreaders = nreaders;
2289         } else {
2290                 nrealreaders = num_online_cpus() - 2 - nreaders;
2291                 if (nrealreaders <= 0)
2292                         nrealreaders = 1;
2293         }
2294         rcu_torture_print_module_parms(cur_ops, "Start of test");
2295
2296         /* Set up the freelist. */
2297
2298         INIT_LIST_HEAD(&rcu_torture_freelist);
2299         for (i = 0; i < ARRAY_SIZE(rcu_tortures); i++) {
2300                 rcu_tortures[i].rtort_mbtest = 0;
2301                 list_add_tail(&rcu_tortures[i].rtort_free,
2302                               &rcu_torture_freelist);
2303         }
2304
2305         /* Initialize the statistics so that each run gets its own numbers. */
2306
2307         rcu_torture_current = NULL;
2308         rcu_torture_current_version = 0;
2309         atomic_set(&n_rcu_torture_alloc, 0);
2310         atomic_set(&n_rcu_torture_alloc_fail, 0);
2311         atomic_set(&n_rcu_torture_free, 0);
2312         atomic_set(&n_rcu_torture_mberror, 0);
2313         atomic_set(&n_rcu_torture_error, 0);
2314         n_rcu_torture_barrier_error = 0;
2315         n_rcu_torture_boost_ktrerror = 0;
2316         n_rcu_torture_boost_rterror = 0;
2317         n_rcu_torture_boost_failure = 0;
2318         n_rcu_torture_boosts = 0;
2319         for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++)
2320                 atomic_set(&rcu_torture_wcount[i], 0);
2321         for_each_possible_cpu(cpu) {
2322                 for (i = 0; i < RCU_TORTURE_PIPE_LEN + 1; i++) {
2323                         per_cpu(rcu_torture_count, cpu)[i] = 0;
2324                         per_cpu(rcu_torture_batch, cpu)[i] = 0;
2325                 }
2326         }
2327         err_segs_recorded = 0;
2328         rt_read_nsegs = 0;
2329
2330         /* Start up the kthreads. */
2331
2332         firsterr = torture_create_kthread(rcu_torture_writer, NULL,
2333                                           writer_task);
2334         if (firsterr)
2335                 goto unwind;
2336         if (nfakewriters > 0) {
2337                 fakewriter_tasks = kcalloc(nfakewriters,
2338                                            sizeof(fakewriter_tasks[0]),
2339                                            GFP_KERNEL);
2340                 if (fakewriter_tasks == NULL) {
2341                         VERBOSE_TOROUT_ERRSTRING("out of memory");
2342                         firsterr = -ENOMEM;
2343                         goto unwind;
2344                 }
2345         }
2346         for (i = 0; i < nfakewriters; i++) {
2347                 firsterr = torture_create_kthread(rcu_torture_fakewriter,
2348                                                   NULL, fakewriter_tasks[i]);
2349                 if (firsterr)
2350                         goto unwind;
2351         }
2352         reader_tasks = kcalloc(nrealreaders, sizeof(reader_tasks[0]),
2353                                GFP_KERNEL);
2354         if (reader_tasks == NULL) {
2355                 VERBOSE_TOROUT_ERRSTRING("out of memory");
2356                 firsterr = -ENOMEM;
2357                 goto unwind;
2358         }
2359         for (i = 0; i < nrealreaders; i++) {
2360                 firsterr = torture_create_kthread(rcu_torture_reader, (void *)i,
2361                                                   reader_tasks[i]);
2362                 if (firsterr)
2363                         goto unwind;
2364         }
2365         if (stat_interval > 0) {
2366                 firsterr = torture_create_kthread(rcu_torture_stats, NULL,
2367                                                   stats_task);
2368                 if (firsterr)
2369                         goto unwind;
2370         }
2371         if (test_no_idle_hz && shuffle_interval > 0) {
2372                 firsterr = torture_shuffle_init(shuffle_interval * HZ);
2373                 if (firsterr)
2374                         goto unwind;
2375         }
2376         if (stutter < 0)
2377                 stutter = 0;
2378         if (stutter) {
2379                 int t;
2380
2381                 t = cur_ops->stall_dur ? cur_ops->stall_dur() : stutter * HZ;
2382                 firsterr = torture_stutter_init(stutter * HZ, t);
2383                 if (firsterr)
2384                         goto unwind;
2385         }
2386         if (fqs_duration < 0)
2387                 fqs_duration = 0;
2388         if (fqs_duration) {
2389                 /* Create the fqs thread */
2390                 firsterr = torture_create_kthread(rcu_torture_fqs, NULL,
2391                                                   fqs_task);
2392                 if (firsterr)
2393                         goto unwind;
2394         }
2395         if (test_boost_interval < 1)
2396                 test_boost_interval = 1;
2397         if (test_boost_duration < 2)
2398                 test_boost_duration = 2;
2399         if (rcu_torture_can_boost()) {
2400
2401                 boost_starttime = jiffies + test_boost_interval * HZ;
2402
2403                 firsterr = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "RCU_TORTURE",
2404                                              rcutorture_booster_init,
2405                                              rcutorture_booster_cleanup);
2406                 if (firsterr < 0)
2407                         goto unwind;
2408                 rcutor_hp = firsterr;
2409         }
2410         firsterr = torture_shutdown_init(shutdown_secs, rcu_torture_cleanup);
2411         if (firsterr)
2412                 goto unwind;
2413         firsterr = torture_onoff_init(onoff_holdoff * HZ, onoff_interval,
2414                                       rcutorture_sync);
2415         if (firsterr)
2416                 goto unwind;
2417         firsterr = rcu_torture_stall_init();
2418         if (firsterr)
2419                 goto unwind;
2420         firsterr = rcu_torture_fwd_prog_init();
2421         if (firsterr)
2422                 goto unwind;
2423         firsterr = rcu_torture_barrier_init();
2424         if (firsterr)
2425                 goto unwind;
2426         if (object_debug)
2427                 rcu_test_debug_objects();
2428         torture_init_end();
2429         return 0;
2430
2431 unwind:
2432         torture_init_end();
2433         rcu_torture_cleanup();
2434         return firsterr;
2435 }
2436
2437 module_init(rcu_torture_init);
2438 module_exit(rcu_torture_cleanup);