xref: /openbmc/linux/kernel/torture.c (revision 0b962c8fe0e5c72a252b236814a6b6e9df799061)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Common functions for in-kernel torture tests.
4  *
5  * Copyright (C) IBM Corporation, 2014
6  *
7  * Author: Paul E. McKenney <paulmck@linux.ibm.com>
8  *	Based on kernel/rcu/torture.c.
9  */
10 
11 #define pr_fmt(fmt) fmt
12 
13 #include <linux/types.h>
14 #include <linux/kernel.h>
15 #include <linux/init.h>
16 #include <linux/module.h>
17 #include <linux/kthread.h>
18 #include <linux/err.h>
19 #include <linux/spinlock.h>
20 #include <linux/smp.h>
21 #include <linux/interrupt.h>
22 #include <linux/sched.h>
23 #include <linux/sched/clock.h>
24 #include <linux/atomic.h>
25 #include <linux/bitops.h>
26 #include <linux/completion.h>
27 #include <linux/moduleparam.h>
28 #include <linux/percpu.h>
29 #include <linux/notifier.h>
30 #include <linux/reboot.h>
31 #include <linux/freezer.h>
32 #include <linux/cpu.h>
33 #include <linux/delay.h>
34 #include <linux/stat.h>
35 #include <linux/slab.h>
36 #include <linux/trace_clock.h>
37 #include <linux/ktime.h>
38 #include <asm/byteorder.h>
39 #include <linux/torture.h>
40 #include "rcu/rcu.h"
41 
42 MODULE_LICENSE("GPL");
43 MODULE_AUTHOR("Paul E. McKenney <paulmck@linux.ibm.com>");
44 
45 static bool disable_onoff_at_boot;
46 module_param(disable_onoff_at_boot, bool, 0444);
47 
48 static bool ftrace_dump_at_shutdown;
49 module_param(ftrace_dump_at_shutdown, bool, 0444);
50 
51 static int verbose_sleep_frequency;
52 module_param(verbose_sleep_frequency, int, 0444);
53 
54 static int verbose_sleep_duration = 1;
55 module_param(verbose_sleep_duration, int, 0444);
56 
57 static char *torture_type;
58 static int verbose;
59 
60 /* Mediate rmmod and system shutdown.  Concurrent rmmod & shutdown illegal! */
61 #define FULLSTOP_DONTSTOP 0	/* Normal operation. */
62 #define FULLSTOP_SHUTDOWN 1	/* System shutdown with torture running. */
63 #define FULLSTOP_RMMOD    2	/* Normal rmmod of torture. */
64 static int fullstop = FULLSTOP_RMMOD;
65 static DEFINE_MUTEX(fullstop_mutex);
66 
67 static atomic_t verbose_sleep_counter;
68 
69 /*
70  * Sleep if needed from VERBOSE_TOROUT*().
71  */
72 void verbose_torout_sleep(void)
73 {
74 	if (verbose_sleep_frequency > 0 &&
75 	    verbose_sleep_duration > 0 &&
76 	    !(atomic_inc_return(&verbose_sleep_counter) % verbose_sleep_frequency))
77 		schedule_timeout_uninterruptible(verbose_sleep_duration);
78 }
79 EXPORT_SYMBOL_GPL(verbose_torout_sleep);
80 
81 /*
82  * Schedule a high-resolution-timer sleep in nanoseconds, with a 32-bit
83  * nanosecond random fuzz.  This function and its friends desynchronize
84  * testing from the timer wheel.
85  */
86 int torture_hrtimeout_ns(ktime_t baset_ns, u32 fuzzt_ns, struct torture_random_state *trsp)
87 {
88 	ktime_t hto = baset_ns;
89 
90 	if (trsp)
91 		hto += (torture_random(trsp) >> 3) % fuzzt_ns;
92 	set_current_state(TASK_UNINTERRUPTIBLE);
93 	return schedule_hrtimeout(&hto, HRTIMER_MODE_REL);
94 }
95 EXPORT_SYMBOL_GPL(torture_hrtimeout_ns);
96 
97 /*
98  * Schedule a high-resolution-timer sleep in microseconds, with a 32-bit
99  * nanosecond (not microsecond!) random fuzz.
100  */
101 int torture_hrtimeout_us(u32 baset_us, u32 fuzzt_ns, struct torture_random_state *trsp)
102 {
103 	ktime_t baset_ns = baset_us * NSEC_PER_USEC;
104 
105 	return torture_hrtimeout_ns(baset_ns, fuzzt_ns, trsp);
106 }
107 EXPORT_SYMBOL_GPL(torture_hrtimeout_us);
108 
109 /*
110  * Schedule a high-resolution-timer sleep in milliseconds, with a 32-bit
111  * microsecond (not millisecond!) random fuzz.
112  */
113 int torture_hrtimeout_ms(u32 baset_ms, u32 fuzzt_us, struct torture_random_state *trsp)
114 {
115 	ktime_t baset_ns = baset_ms * NSEC_PER_MSEC;
116 	u32 fuzzt_ns;
117 
118 	if ((u32)~0U / NSEC_PER_USEC < fuzzt_us)
119 		fuzzt_ns = (u32)~0U;
120 	else
121 		fuzzt_ns = fuzzt_us * NSEC_PER_USEC;
122 	return torture_hrtimeout_ns(baset_ns, fuzzt_ns, trsp);
123 }
124 EXPORT_SYMBOL_GPL(torture_hrtimeout_ms);
125 
126 /*
127  * Schedule a high-resolution-timer sleep in jiffies, with an
128  * implied one-jiffy random fuzz.  This is intended to replace calls to
129  * schedule_timeout_interruptible() and friends.
130  */
131 int torture_hrtimeout_jiffies(u32 baset_j, struct torture_random_state *trsp)
132 {
133 	ktime_t baset_ns = jiffies_to_nsecs(baset_j);
134 
135 	return torture_hrtimeout_ns(baset_ns, jiffies_to_nsecs(1), trsp);
136 }
137 EXPORT_SYMBOL_GPL(torture_hrtimeout_jiffies);
138 
139 /*
140  * Schedule a high-resolution-timer sleep in milliseconds, with a 32-bit
141  * millisecond (not second!) random fuzz.
142  */
143 int torture_hrtimeout_s(u32 baset_s, u32 fuzzt_ms, struct torture_random_state *trsp)
144 {
145 	ktime_t baset_ns = baset_s * NSEC_PER_SEC;
146 	u32 fuzzt_ns;
147 
148 	if ((u32)~0U / NSEC_PER_MSEC < fuzzt_ms)
149 		fuzzt_ns = (u32)~0U;
150 	else
151 		fuzzt_ns = fuzzt_ms * NSEC_PER_MSEC;
152 	return torture_hrtimeout_ns(baset_ns, fuzzt_ns, trsp);
153 }
154 EXPORT_SYMBOL_GPL(torture_hrtimeout_s);
155 
156 #ifdef CONFIG_HOTPLUG_CPU
157 
158 /*
159  * Variables for online-offline handling.  Only present if CPU hotplug
160  * is enabled, otherwise does nothing.
161  */
162 
163 static struct task_struct *onoff_task;
164 static long onoff_holdoff;
165 static long onoff_interval;
166 static torture_ofl_func *onoff_f;
167 static long n_offline_attempts;
168 static long n_offline_successes;
169 static unsigned long sum_offline;
170 static int min_offline = -1;
171 static int max_offline;
172 static long n_online_attempts;
173 static long n_online_successes;
174 static unsigned long sum_online;
175 static int min_online = -1;
176 static int max_online;
177 
178 /*
179  * Attempt to take a CPU offline.  Return false if the CPU is already
180  * offline or if it is not subject to CPU-hotplug operations.  The
181  * caller can detect other failures by looking at the statistics.
182  */
183 bool torture_offline(int cpu, long *n_offl_attempts, long *n_offl_successes,
184 		     unsigned long *sum_offl, int *min_offl, int *max_offl)
185 {
186 	unsigned long delta;
187 	int ret;
188 	char *s;
189 	unsigned long starttime;
190 
191 	if (!cpu_online(cpu) || !cpu_is_hotpluggable(cpu))
192 		return false;
193 	if (num_online_cpus() <= 1)
194 		return false;  /* Can't offline the last CPU. */
195 
196 	if (verbose > 1)
197 		pr_alert("%s" TORTURE_FLAG
198 			 "torture_onoff task: offlining %d\n",
199 			 torture_type, cpu);
200 	starttime = jiffies;
201 	(*n_offl_attempts)++;
202 	ret = remove_cpu(cpu);
203 	if (ret) {
204 		s = "";
205 		if (!rcu_inkernel_boot_has_ended() && ret == -EBUSY) {
206 			// PCI probe frequently disables hotplug during boot.
207 			(*n_offl_attempts)--;
208 			s = " (-EBUSY forgiven during boot)";
209 		}
210 		if (verbose)
211 			pr_alert("%s" TORTURE_FLAG
212 				 "torture_onoff task: offline %d failed%s: errno %d\n",
213 				 torture_type, cpu, s, ret);
214 	} else {
215 		if (verbose > 1)
216 			pr_alert("%s" TORTURE_FLAG
217 				 "torture_onoff task: offlined %d\n",
218 				 torture_type, cpu);
219 		if (onoff_f)
220 			onoff_f();
221 		(*n_offl_successes)++;
222 		delta = jiffies - starttime;
223 		*sum_offl += delta;
224 		if (*min_offl < 0) {
225 			*min_offl = delta;
226 			*max_offl = delta;
227 		}
228 		if (*min_offl > delta)
229 			*min_offl = delta;
230 		if (*max_offl < delta)
231 			*max_offl = delta;
232 	}
233 
234 	return true;
235 }
236 EXPORT_SYMBOL_GPL(torture_offline);
237 
238 /*
239  * Attempt to bring a CPU online.  Return false if the CPU is already
240  * online or if it is not subject to CPU-hotplug operations.  The
241  * caller can detect other failures by looking at the statistics.
242  */
243 bool torture_online(int cpu, long *n_onl_attempts, long *n_onl_successes,
244 		    unsigned long *sum_onl, int *min_onl, int *max_onl)
245 {
246 	unsigned long delta;
247 	int ret;
248 	char *s;
249 	unsigned long starttime;
250 
251 	if (cpu_online(cpu) || !cpu_is_hotpluggable(cpu))
252 		return false;
253 
254 	if (verbose > 1)
255 		pr_alert("%s" TORTURE_FLAG
256 			 "torture_onoff task: onlining %d\n",
257 			 torture_type, cpu);
258 	starttime = jiffies;
259 	(*n_onl_attempts)++;
260 	ret = add_cpu(cpu);
261 	if (ret) {
262 		s = "";
263 		if (!rcu_inkernel_boot_has_ended() && ret == -EBUSY) {
264 			// PCI probe frequently disables hotplug during boot.
265 			(*n_onl_attempts)--;
266 			s = " (-EBUSY forgiven during boot)";
267 		}
268 		if (verbose)
269 			pr_alert("%s" TORTURE_FLAG
270 				 "torture_onoff task: online %d failed%s: errno %d\n",
271 				 torture_type, cpu, s, ret);
272 	} else {
273 		if (verbose > 1)
274 			pr_alert("%s" TORTURE_FLAG
275 				 "torture_onoff task: onlined %d\n",
276 				 torture_type, cpu);
277 		(*n_onl_successes)++;
278 		delta = jiffies - starttime;
279 		*sum_onl += delta;
280 		if (*min_onl < 0) {
281 			*min_onl = delta;
282 			*max_onl = delta;
283 		}
284 		if (*min_onl > delta)
285 			*min_onl = delta;
286 		if (*max_onl < delta)
287 			*max_onl = delta;
288 	}
289 
290 	return true;
291 }
292 EXPORT_SYMBOL_GPL(torture_online);
293 
294 /*
295  * Get everything online at the beginning and ends of tests.
296  */
297 static void torture_online_all(char *phase)
298 {
299 	int cpu;
300 	int ret;
301 
302 	for_each_possible_cpu(cpu) {
303 		if (cpu_online(cpu))
304 			continue;
305 		ret = add_cpu(cpu);
306 		if (ret && verbose) {
307 			pr_alert("%s" TORTURE_FLAG
308 				 "%s: %s online %d: errno %d\n",
309 				 __func__, phase, torture_type, cpu, ret);
310 		}
311 	}
312 }
313 
314 /*
315  * Execute random CPU-hotplug operations at the interval specified
316  * by the onoff_interval.
317  */
318 static int
319 torture_onoff(void *arg)
320 {
321 	int cpu;
322 	int maxcpu = -1;
323 	DEFINE_TORTURE_RANDOM(rand);
324 
325 	VERBOSE_TOROUT_STRING("torture_onoff task started");
326 	for_each_online_cpu(cpu)
327 		maxcpu = cpu;
328 	WARN_ON(maxcpu < 0);
329 	torture_online_all("Initial");
330 	if (maxcpu == 0) {
331 		VERBOSE_TOROUT_STRING("Only one CPU, so CPU-hotplug testing is disabled");
332 		goto stop;
333 	}
334 
335 	if (onoff_holdoff > 0) {
336 		VERBOSE_TOROUT_STRING("torture_onoff begin holdoff");
337 		schedule_timeout_interruptible(onoff_holdoff);
338 		VERBOSE_TOROUT_STRING("torture_onoff end holdoff");
339 	}
340 	while (!torture_must_stop()) {
341 		if (disable_onoff_at_boot && !rcu_inkernel_boot_has_ended()) {
342 			schedule_timeout_interruptible(HZ / 10);
343 			continue;
344 		}
345 		cpu = (torture_random(&rand) >> 4) % (maxcpu + 1);
346 		if (!torture_offline(cpu,
347 				     &n_offline_attempts, &n_offline_successes,
348 				     &sum_offline, &min_offline, &max_offline))
349 			torture_online(cpu,
350 				       &n_online_attempts, &n_online_successes,
351 				       &sum_online, &min_online, &max_online);
352 		schedule_timeout_interruptible(onoff_interval);
353 	}
354 
355 stop:
356 	torture_kthread_stopping("torture_onoff");
357 	torture_online_all("Final");
358 	return 0;
359 }
360 
361 #endif /* #ifdef CONFIG_HOTPLUG_CPU */
362 
363 /*
364  * Initiate online-offline handling.
365  */
366 int torture_onoff_init(long ooholdoff, long oointerval, torture_ofl_func *f)
367 {
368 #ifdef CONFIG_HOTPLUG_CPU
369 	onoff_holdoff = ooholdoff;
370 	onoff_interval = oointerval;
371 	onoff_f = f;
372 	if (onoff_interval <= 0)
373 		return 0;
374 	return torture_create_kthread(torture_onoff, NULL, onoff_task);
375 #else /* #ifdef CONFIG_HOTPLUG_CPU */
376 	return 0;
377 #endif /* #else #ifdef CONFIG_HOTPLUG_CPU */
378 }
379 EXPORT_SYMBOL_GPL(torture_onoff_init);
380 
381 /*
382  * Clean up after online/offline testing.
383  */
384 static void torture_onoff_cleanup(void)
385 {
386 #ifdef CONFIG_HOTPLUG_CPU
387 	if (onoff_task == NULL)
388 		return;
389 	VERBOSE_TOROUT_STRING("Stopping torture_onoff task");
390 	kthread_stop(onoff_task);
391 	onoff_task = NULL;
392 #endif /* #ifdef CONFIG_HOTPLUG_CPU */
393 }
394 
395 /*
396  * Print online/offline testing statistics.
397  */
398 void torture_onoff_stats(void)
399 {
400 #ifdef CONFIG_HOTPLUG_CPU
401 	pr_cont("onoff: %ld/%ld:%ld/%ld %d,%d:%d,%d %lu:%lu (HZ=%d) ",
402 		n_online_successes, n_online_attempts,
403 		n_offline_successes, n_offline_attempts,
404 		min_online, max_online,
405 		min_offline, max_offline,
406 		sum_online, sum_offline, HZ);
407 #endif /* #ifdef CONFIG_HOTPLUG_CPU */
408 }
409 EXPORT_SYMBOL_GPL(torture_onoff_stats);
410 
411 /*
412  * Were all the online/offline operations successful?
413  */
414 bool torture_onoff_failures(void)
415 {
416 #ifdef CONFIG_HOTPLUG_CPU
417 	return n_online_successes != n_online_attempts ||
418 	       n_offline_successes != n_offline_attempts;
419 #else /* #ifdef CONFIG_HOTPLUG_CPU */
420 	return false;
421 #endif /* #else #ifdef CONFIG_HOTPLUG_CPU */
422 }
423 EXPORT_SYMBOL_GPL(torture_onoff_failures);
424 
425 #define TORTURE_RANDOM_MULT	39916801  /* prime */
426 #define TORTURE_RANDOM_ADD	479001701 /* prime */
427 #define TORTURE_RANDOM_REFRESH	10000
428 
429 /*
430  * Crude but fast random-number generator.  Uses a linear congruential
431  * generator, with occasional help from cpu_clock().
432  */
433 unsigned long
434 torture_random(struct torture_random_state *trsp)
435 {
436 	if (--trsp->trs_count < 0) {
437 		trsp->trs_state += (unsigned long)local_clock();
438 		trsp->trs_count = TORTURE_RANDOM_REFRESH;
439 	}
440 	trsp->trs_state = trsp->trs_state * TORTURE_RANDOM_MULT +
441 		TORTURE_RANDOM_ADD;
442 	return swahw32(trsp->trs_state);
443 }
444 EXPORT_SYMBOL_GPL(torture_random);
445 
446 /*
447  * Variables for shuffling.  The idea is to ensure that each CPU stays
448  * idle for an extended period to test interactions with dyntick idle,
449  * as well as interactions with any per-CPU variables.
450  */
451 struct shuffle_task {
452 	struct list_head st_l;
453 	struct task_struct *st_t;
454 };
455 
456 static long shuffle_interval;	/* In jiffies. */
457 static struct task_struct *shuffler_task;
458 static cpumask_var_t shuffle_tmp_mask;
459 static int shuffle_idle_cpu;	/* Force all torture tasks off this CPU */
460 static struct list_head shuffle_task_list = LIST_HEAD_INIT(shuffle_task_list);
461 static DEFINE_MUTEX(shuffle_task_mutex);
462 
463 /*
464  * Register a task to be shuffled.  If there is no memory, just splat
465  * and don't bother registering.
466  */
467 void torture_shuffle_task_register(struct task_struct *tp)
468 {
469 	struct shuffle_task *stp;
470 
471 	if (WARN_ON_ONCE(tp == NULL))
472 		return;
473 	stp = kmalloc(sizeof(*stp), GFP_KERNEL);
474 	if (WARN_ON_ONCE(stp == NULL))
475 		return;
476 	stp->st_t = tp;
477 	mutex_lock(&shuffle_task_mutex);
478 	list_add(&stp->st_l, &shuffle_task_list);
479 	mutex_unlock(&shuffle_task_mutex);
480 }
481 EXPORT_SYMBOL_GPL(torture_shuffle_task_register);
482 
483 /*
484  * Unregister all tasks, for example, at the end of the torture run.
485  */
486 static void torture_shuffle_task_unregister_all(void)
487 {
488 	struct shuffle_task *stp;
489 	struct shuffle_task *p;
490 
491 	mutex_lock(&shuffle_task_mutex);
492 	list_for_each_entry_safe(stp, p, &shuffle_task_list, st_l) {
493 		list_del(&stp->st_l);
494 		kfree(stp);
495 	}
496 	mutex_unlock(&shuffle_task_mutex);
497 }
498 
499 /* Shuffle tasks such that we allow shuffle_idle_cpu to become idle.
500  * A special case is when shuffle_idle_cpu = -1, in which case we allow
501  * the tasks to run on all CPUs.
502  */
503 static void torture_shuffle_tasks(void)
504 {
505 	struct shuffle_task *stp;
506 
507 	cpumask_setall(shuffle_tmp_mask);
508 	get_online_cpus();
509 
510 	/* No point in shuffling if there is only one online CPU (ex: UP) */
511 	if (num_online_cpus() == 1) {
512 		put_online_cpus();
513 		return;
514 	}
515 
516 	/* Advance to the next CPU.  Upon overflow, don't idle any CPUs. */
517 	shuffle_idle_cpu = cpumask_next(shuffle_idle_cpu, shuffle_tmp_mask);
518 	if (shuffle_idle_cpu >= nr_cpu_ids)
519 		shuffle_idle_cpu = -1;
520 	else
521 		cpumask_clear_cpu(shuffle_idle_cpu, shuffle_tmp_mask);
522 
523 	mutex_lock(&shuffle_task_mutex);
524 	list_for_each_entry(stp, &shuffle_task_list, st_l)
525 		set_cpus_allowed_ptr(stp->st_t, shuffle_tmp_mask);
526 	mutex_unlock(&shuffle_task_mutex);
527 
528 	put_online_cpus();
529 }
530 
531 /* Shuffle tasks across CPUs, with the intent of allowing each CPU in the
532  * system to become idle at a time and cut off its timer ticks. This is meant
533  * to test the support for such tickless idle CPU in RCU.
534  */
535 static int torture_shuffle(void *arg)
536 {
537 	VERBOSE_TOROUT_STRING("torture_shuffle task started");
538 	do {
539 		schedule_timeout_interruptible(shuffle_interval);
540 		torture_shuffle_tasks();
541 		torture_shutdown_absorb("torture_shuffle");
542 	} while (!torture_must_stop());
543 	torture_kthread_stopping("torture_shuffle");
544 	return 0;
545 }
546 
547 /*
548  * Start the shuffler, with shuffint in jiffies.
549  */
550 int torture_shuffle_init(long shuffint)
551 {
552 	shuffle_interval = shuffint;
553 
554 	shuffle_idle_cpu = -1;
555 
556 	if (!alloc_cpumask_var(&shuffle_tmp_mask, GFP_KERNEL)) {
557 		VERBOSE_TOROUT_ERRSTRING("Failed to alloc mask");
558 		return -ENOMEM;
559 	}
560 
561 	/* Create the shuffler thread */
562 	return torture_create_kthread(torture_shuffle, NULL, shuffler_task);
563 }
564 EXPORT_SYMBOL_GPL(torture_shuffle_init);
565 
566 /*
567  * Stop the shuffling.
568  */
569 static void torture_shuffle_cleanup(void)
570 {
571 	torture_shuffle_task_unregister_all();
572 	if (shuffler_task) {
573 		VERBOSE_TOROUT_STRING("Stopping torture_shuffle task");
574 		kthread_stop(shuffler_task);
575 		free_cpumask_var(shuffle_tmp_mask);
576 	}
577 	shuffler_task = NULL;
578 }
579 
580 /*
581  * Variables for auto-shutdown.  This allows "lights out" torture runs
582  * to be fully scripted.
583  */
584 static struct task_struct *shutdown_task;
585 static ktime_t shutdown_time;		/* time to system shutdown. */
586 static void (*torture_shutdown_hook)(void);
587 
588 /*
589  * Absorb kthreads into a kernel function that won't return, so that
590  * they won't ever access module text or data again.
591  */
592 void torture_shutdown_absorb(const char *title)
593 {
594 	while (READ_ONCE(fullstop) == FULLSTOP_SHUTDOWN) {
595 		pr_notice("torture thread %s parking due to system shutdown\n",
596 			  title);
597 		schedule_timeout_uninterruptible(MAX_SCHEDULE_TIMEOUT);
598 	}
599 }
600 EXPORT_SYMBOL_GPL(torture_shutdown_absorb);
601 
602 /*
603  * Cause the torture test to shutdown the system after the test has
604  * run for the time specified by the shutdown_secs parameter.
605  */
606 static int torture_shutdown(void *arg)
607 {
608 	ktime_t ktime_snap;
609 
610 	VERBOSE_TOROUT_STRING("torture_shutdown task started");
611 	ktime_snap = ktime_get();
612 	while (ktime_before(ktime_snap, shutdown_time) &&
613 	       !torture_must_stop()) {
614 		if (verbose)
615 			pr_alert("%s" TORTURE_FLAG
616 				 "torture_shutdown task: %llu ms remaining\n",
617 				 torture_type,
618 				 ktime_ms_delta(shutdown_time, ktime_snap));
619 		set_current_state(TASK_INTERRUPTIBLE);
620 		schedule_hrtimeout(&shutdown_time, HRTIMER_MODE_ABS);
621 		ktime_snap = ktime_get();
622 	}
623 	if (torture_must_stop()) {
624 		torture_kthread_stopping("torture_shutdown");
625 		return 0;
626 	}
627 
628 	/* OK, shut down the system. */
629 
630 	VERBOSE_TOROUT_STRING("torture_shutdown task shutting down system");
631 	shutdown_task = NULL;	/* Avoid self-kill deadlock. */
632 	if (torture_shutdown_hook)
633 		torture_shutdown_hook();
634 	else
635 		VERBOSE_TOROUT_STRING("No torture_shutdown_hook(), skipping.");
636 	if (ftrace_dump_at_shutdown)
637 		rcu_ftrace_dump(DUMP_ALL);
638 	kernel_power_off();	/* Shut down the system. */
639 	return 0;
640 }
641 
642 /*
643  * Start up the shutdown task.
644  */
645 int torture_shutdown_init(int ssecs, void (*cleanup)(void))
646 {
647 	torture_shutdown_hook = cleanup;
648 	if (ssecs > 0) {
649 		shutdown_time = ktime_add(ktime_get(), ktime_set(ssecs, 0));
650 		return torture_create_kthread(torture_shutdown, NULL,
651 					     shutdown_task);
652 	}
653 	return 0;
654 }
655 EXPORT_SYMBOL_GPL(torture_shutdown_init);
656 
657 /*
658  * Detect and respond to a system shutdown.
659  */
660 static int torture_shutdown_notify(struct notifier_block *unused1,
661 				   unsigned long unused2, void *unused3)
662 {
663 	mutex_lock(&fullstop_mutex);
664 	if (READ_ONCE(fullstop) == FULLSTOP_DONTSTOP) {
665 		VERBOSE_TOROUT_STRING("Unscheduled system shutdown detected");
666 		WRITE_ONCE(fullstop, FULLSTOP_SHUTDOWN);
667 	} else {
668 		pr_warn("Concurrent rmmod and shutdown illegal!\n");
669 	}
670 	mutex_unlock(&fullstop_mutex);
671 	return NOTIFY_DONE;
672 }
673 
674 static struct notifier_block torture_shutdown_nb = {
675 	.notifier_call = torture_shutdown_notify,
676 };
677 
678 /*
679  * Shut down the shutdown task.  Say what???  Heh!  This can happen if
680  * the torture module gets an rmmod before the shutdown time arrives.  ;-)
681  */
682 static void torture_shutdown_cleanup(void)
683 {
684 	unregister_reboot_notifier(&torture_shutdown_nb);
685 	if (shutdown_task != NULL) {
686 		VERBOSE_TOROUT_STRING("Stopping torture_shutdown task");
687 		kthread_stop(shutdown_task);
688 	}
689 	shutdown_task = NULL;
690 }
691 
692 /*
693  * Variables for stuttering, which means to periodically pause and
694  * restart testing in order to catch bugs that appear when load is
695  * suddenly applied to or removed from the system.
696  */
697 static struct task_struct *stutter_task;
698 static int stutter_pause_test;
699 static int stutter;
700 static int stutter_gap;
701 
702 /*
703  * Block until the stutter interval ends.  This must be called periodically
704  * by all running kthreads that need to be subject to stuttering.
705  */
706 bool stutter_wait(const char *title)
707 {
708 	unsigned int i = 0;
709 	bool ret = false;
710 	int spt;
711 
712 	cond_resched_tasks_rcu_qs();
713 	spt = READ_ONCE(stutter_pause_test);
714 	for (; spt; spt = READ_ONCE(stutter_pause_test)) {
715 		if (!ret) {
716 			sched_set_normal(current, MAX_NICE);
717 			ret = true;
718 		}
719 		if (spt == 1) {
720 			schedule_timeout_interruptible(1);
721 		} else if (spt == 2) {
722 			while (READ_ONCE(stutter_pause_test)) {
723 				if (!(i++ & 0xffff))
724 					torture_hrtimeout_us(10, 0, NULL);
725 				cond_resched();
726 			}
727 		} else {
728 			schedule_timeout_interruptible(round_jiffies_relative(HZ));
729 		}
730 		torture_shutdown_absorb(title);
731 	}
732 	return ret;
733 }
734 EXPORT_SYMBOL_GPL(stutter_wait);
735 
736 /*
737  * Cause the torture test to "stutter", starting and stopping all
738  * threads periodically.
739  */
740 static int torture_stutter(void *arg)
741 {
742 	DEFINE_TORTURE_RANDOM(rand);
743 	int wtime;
744 
745 	VERBOSE_TOROUT_STRING("torture_stutter task started");
746 	do {
747 		if (!torture_must_stop() && stutter > 1) {
748 			wtime = stutter;
749 			if (stutter > 2) {
750 				WRITE_ONCE(stutter_pause_test, 1);
751 				wtime = stutter - 3;
752 				torture_hrtimeout_jiffies(wtime, &rand);
753 				wtime = 2;
754 			}
755 			WRITE_ONCE(stutter_pause_test, 2);
756 			torture_hrtimeout_jiffies(wtime, NULL);
757 		}
758 		WRITE_ONCE(stutter_pause_test, 0);
759 		if (!torture_must_stop())
760 			torture_hrtimeout_jiffies(stutter_gap, NULL);
761 		torture_shutdown_absorb("torture_stutter");
762 	} while (!torture_must_stop());
763 	torture_kthread_stopping("torture_stutter");
764 	return 0;
765 }
766 
767 /*
768  * Initialize and kick off the torture_stutter kthread.
769  */
770 int torture_stutter_init(const int s, const int sgap)
771 {
772 	stutter = s;
773 	stutter_gap = sgap;
774 	return torture_create_kthread(torture_stutter, NULL, stutter_task);
775 }
776 EXPORT_SYMBOL_GPL(torture_stutter_init);
777 
778 /*
779  * Cleanup after the torture_stutter kthread.
780  */
781 static void torture_stutter_cleanup(void)
782 {
783 	if (!stutter_task)
784 		return;
785 	VERBOSE_TOROUT_STRING("Stopping torture_stutter task");
786 	kthread_stop(stutter_task);
787 	stutter_task = NULL;
788 }
789 
790 /*
791  * Initialize torture module.  Please note that this is -not- invoked via
792  * the usual module_init() mechanism, but rather by an explicit call from
793  * the client torture module.  This call must be paired with a later
794  * torture_init_end().
795  *
796  * The runnable parameter points to a flag that controls whether or not
797  * the test is currently runnable.  If there is no such flag, pass in NULL.
798  */
799 bool torture_init_begin(char *ttype, int v)
800 {
801 	mutex_lock(&fullstop_mutex);
802 	if (torture_type != NULL) {
803 		pr_alert("torture_init_begin: Refusing %s init: %s running.\n",
804 			 ttype, torture_type);
805 		pr_alert("torture_init_begin: One torture test at a time!\n");
806 		mutex_unlock(&fullstop_mutex);
807 		return false;
808 	}
809 	torture_type = ttype;
810 	verbose = v;
811 	fullstop = FULLSTOP_DONTSTOP;
812 	return true;
813 }
814 EXPORT_SYMBOL_GPL(torture_init_begin);
815 
816 /*
817  * Tell the torture module that initialization is complete.
818  */
819 void torture_init_end(void)
820 {
821 	mutex_unlock(&fullstop_mutex);
822 	register_reboot_notifier(&torture_shutdown_nb);
823 }
824 EXPORT_SYMBOL_GPL(torture_init_end);
825 
826 /*
827  * Clean up torture module.  Please note that this is -not- invoked via
828  * the usual module_exit() mechanism, but rather by an explicit call from
829  * the client torture module.  Returns true if a race with system shutdown
830  * is detected, otherwise, all kthreads started by functions in this file
831  * will be shut down.
832  *
833  * This must be called before the caller starts shutting down its own
834  * kthreads.
835  *
836  * Both torture_cleanup_begin() and torture_cleanup_end() must be paired,
837  * in order to correctly perform the cleanup. They are separated because
838  * threads can still need to reference the torture_type type, thus nullify
839  * only after completing all other relevant calls.
840  */
841 bool torture_cleanup_begin(void)
842 {
843 	mutex_lock(&fullstop_mutex);
844 	if (READ_ONCE(fullstop) == FULLSTOP_SHUTDOWN) {
845 		pr_warn("Concurrent rmmod and shutdown illegal!\n");
846 		mutex_unlock(&fullstop_mutex);
847 		schedule_timeout_uninterruptible(10);
848 		return true;
849 	}
850 	WRITE_ONCE(fullstop, FULLSTOP_RMMOD);
851 	mutex_unlock(&fullstop_mutex);
852 	torture_shutdown_cleanup();
853 	torture_shuffle_cleanup();
854 	torture_stutter_cleanup();
855 	torture_onoff_cleanup();
856 	return false;
857 }
858 EXPORT_SYMBOL_GPL(torture_cleanup_begin);
859 
860 void torture_cleanup_end(void)
861 {
862 	mutex_lock(&fullstop_mutex);
863 	torture_type = NULL;
864 	mutex_unlock(&fullstop_mutex);
865 }
866 EXPORT_SYMBOL_GPL(torture_cleanup_end);
867 
868 /*
869  * Is it time for the current torture test to stop?
870  */
871 bool torture_must_stop(void)
872 {
873 	return torture_must_stop_irq() || kthread_should_stop();
874 }
875 EXPORT_SYMBOL_GPL(torture_must_stop);
876 
877 /*
878  * Is it time for the current torture test to stop?  This is the irq-safe
879  * version, hence no check for kthread_should_stop().
880  */
881 bool torture_must_stop_irq(void)
882 {
883 	return READ_ONCE(fullstop) != FULLSTOP_DONTSTOP;
884 }
885 EXPORT_SYMBOL_GPL(torture_must_stop_irq);
886 
887 /*
888  * Each kthread must wait for kthread_should_stop() before returning from
889  * its top-level function, otherwise segfaults ensue.  This function
890  * prints a "stopping" message and waits for kthread_should_stop(), and
891  * should be called from all torture kthreads immediately prior to
892  * returning.
893  */
894 void torture_kthread_stopping(char *title)
895 {
896 	char buf[128];
897 
898 	snprintf(buf, sizeof(buf), "Stopping %s", title);
899 	VERBOSE_TOROUT_STRING(buf);
900 	while (!kthread_should_stop()) {
901 		torture_shutdown_absorb(title);
902 		schedule_timeout_uninterruptible(1);
903 	}
904 }
905 EXPORT_SYMBOL_GPL(torture_kthread_stopping);
906 
907 /*
908  * Create a generic torture kthread that is immediately runnable.  If you
909  * need the kthread to be stopped so that you can do something to it before
910  * it starts, you will need to open-code your own.
911  */
912 int _torture_create_kthread(int (*fn)(void *arg), void *arg, char *s, char *m,
913 			    char *f, struct task_struct **tp)
914 {
915 	int ret = 0;
916 
917 	VERBOSE_TOROUT_STRING(m);
918 	*tp = kthread_run(fn, arg, "%s", s);
919 	if (IS_ERR(*tp)) {
920 		ret = PTR_ERR(*tp);
921 		VERBOSE_TOROUT_ERRSTRING(f);
922 		*tp = NULL;
923 	}
924 	torture_shuffle_task_register(*tp);
925 	return ret;
926 }
927 EXPORT_SYMBOL_GPL(_torture_create_kthread);
928 
929 /*
930  * Stop a generic kthread, emitting a message.
931  */
932 void _torture_stop_kthread(char *m, struct task_struct **tp)
933 {
934 	if (*tp == NULL)
935 		return;
936 	VERBOSE_TOROUT_STRING(m);
937 	kthread_stop(*tp);
938 	*tp = NULL;
939 }
940 EXPORT_SYMBOL_GPL(_torture_stop_kthread);
941