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