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