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