xref: /linux/kernel/rcu/rcuscale.c (revision 3e49aea71d5bac93b892f954d14bc8070e4cc651)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Read-Copy Update module-based scalability-test facility
4  *
5  * Copyright (C) IBM Corporation, 2015
6  *
7  * Authors: Paul E. McKenney <paulmck@linux.ibm.com>
8  */
9 
10 #define pr_fmt(fmt) fmt
11 
12 #include <linux/types.h>
13 #include <linux/kernel.h>
14 #include <linux/init.h>
15 #include <linux/mm.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/rcupdate.h>
22 #include <linux/interrupt.h>
23 #include <linux/sched.h>
24 #include <uapi/linux/sched/types.h>
25 #include <linux/atomic.h>
26 #include <linux/bitops.h>
27 #include <linux/completion.h>
28 #include <linux/moduleparam.h>
29 #include <linux/percpu.h>
30 #include <linux/notifier.h>
31 #include <linux/reboot.h>
32 #include <linux/freezer.h>
33 #include <linux/cpu.h>
34 #include <linux/delay.h>
35 #include <linux/stat.h>
36 #include <linux/srcu.h>
37 #include <linux/slab.h>
38 #include <asm/byteorder.h>
39 #include <linux/torture.h>
40 #include <linux/vmalloc.h>
41 #include <linux/rcupdate_trace.h>
42 
43 #include "rcu.h"
44 
45 MODULE_DESCRIPTION("Read-Copy Update module-based scalability-test facility");
46 MODULE_LICENSE("GPL");
47 MODULE_AUTHOR("Paul E. McKenney <paulmck@linux.ibm.com>");
48 
49 #define SCALE_FLAG "-scale:"
50 #define SCALEOUT_STRING(s) \
51 	pr_alert("%s" SCALE_FLAG " %s\n", scale_type, s)
52 #define VERBOSE_SCALEOUT_STRING(s) \
53 	do { if (verbose) pr_alert("%s" SCALE_FLAG " %s\n", scale_type, s); } while (0)
54 #define SCALEOUT_ERRSTRING(s) \
55 	pr_alert("%s" SCALE_FLAG "!!! %s\n", scale_type, s)
56 
57 /*
58  * The intended use cases for the nreaders and nwriters module parameters
59  * are as follows:
60  *
61  * 1.	Specify only the nr_cpus kernel boot parameter.  This will
62  *	set both nreaders and nwriters to the value specified by
63  *	nr_cpus for a mixed reader/writer test.
64  *
65  * 2.	Specify the nr_cpus kernel boot parameter, but set
66  *	rcuscale.nreaders to zero.  This will set nwriters to the
67  *	value specified by nr_cpus for an update-only test.
68  *
69  * 3.	Specify the nr_cpus kernel boot parameter, but set
70  *	rcuscale.nwriters to zero.  This will set nreaders to the
71  *	value specified by nr_cpus for a read-only test.
72  *
73  * Various other use cases may of course be specified.
74  *
75  * Note that this test's readers are intended only as a test load for
76  * the writers.  The reader scalability statistics will be overly
77  * pessimistic due to the per-critical-section interrupt disabling,
78  * test-end checks, and the pair of calls through pointers.
79  */
80 
81 #ifdef MODULE
82 # define RCUSCALE_SHUTDOWN 0
83 #else
84 # define RCUSCALE_SHUTDOWN 1
85 #endif
86 
87 torture_param(bool, gp_async, false, "Use asynchronous GP wait primitives");
88 torture_param(int, gp_async_max, 1000, "Max # outstanding waits per writer");
89 torture_param(bool, gp_exp, false, "Use expedited GP wait primitives");
90 torture_param(int, holdoff, 10, "Holdoff time before test start (s)");
91 torture_param(int, minruntime, 0, "Minimum run time (s)");
92 torture_param(int, nreaders, -1, "Number of RCU reader threads");
93 torture_param(int, nwriters, -1, "Number of RCU updater threads");
94 torture_param(bool, shutdown, RCUSCALE_SHUTDOWN,
95 	      "Shutdown at end of scalability tests.");
96 torture_param(int, verbose, 1, "Enable verbose debugging printk()s");
97 torture_param(int, writer_holdoff, 0, "Holdoff (us) between GPs, zero to disable");
98 torture_param(int, writer_holdoff_jiffies, 0, "Holdoff (jiffies) between GPs, zero to disable");
99 torture_param(int, kfree_rcu_test, 0, "Do we run a kfree_rcu() scale test?");
100 torture_param(int, kfree_mult, 1, "Multiple of kfree_obj size to allocate.");
101 torture_param(int, kfree_by_call_rcu, 0, "Use call_rcu() to emulate kfree_rcu()?");
102 
103 static char *scale_type = "rcu";
104 module_param(scale_type, charp, 0444);
105 MODULE_PARM_DESC(scale_type, "Type of RCU to scalability-test (rcu, srcu, ...)");
106 
107 static int nrealreaders;
108 static int nrealwriters;
109 static struct task_struct **writer_tasks;
110 static struct task_struct **reader_tasks;
111 static struct task_struct *shutdown_task;
112 
113 static u64 **writer_durations;
114 static int *writer_n_durations;
115 static atomic_t n_rcu_scale_reader_started;
116 static atomic_t n_rcu_scale_writer_started;
117 static atomic_t n_rcu_scale_writer_finished;
118 static wait_queue_head_t shutdown_wq;
119 static u64 t_rcu_scale_writer_started;
120 static u64 t_rcu_scale_writer_finished;
121 static unsigned long b_rcu_gp_test_started;
122 static unsigned long b_rcu_gp_test_finished;
123 static DEFINE_PER_CPU(atomic_t, n_async_inflight);
124 
125 #define MAX_MEAS 10000
126 #define MIN_MEAS 100
127 
128 /*
129  * Operations vector for selecting different types of tests.
130  */
131 
132 struct rcu_scale_ops {
133 	int ptype;
134 	void (*init)(void);
135 	void (*cleanup)(void);
136 	int (*readlock)(void);
137 	void (*readunlock)(int idx);
138 	unsigned long (*get_gp_seq)(void);
139 	unsigned long (*gp_diff)(unsigned long new, unsigned long old);
140 	unsigned long (*exp_completed)(void);
141 	void (*async)(struct rcu_head *head, rcu_callback_t func);
142 	void (*gp_barrier)(void);
143 	void (*sync)(void);
144 	void (*exp_sync)(void);
145 	struct task_struct *(*rso_gp_kthread)(void);
146 	const char *name;
147 };
148 
149 static struct rcu_scale_ops *cur_ops;
150 
151 /*
152  * Definitions for rcu scalability testing.
153  */
154 
155 static int rcu_scale_read_lock(void) __acquires(RCU)
156 {
157 	rcu_read_lock();
158 	return 0;
159 }
160 
161 static void rcu_scale_read_unlock(int idx) __releases(RCU)
162 {
163 	rcu_read_unlock();
164 }
165 
166 static unsigned long __maybe_unused rcu_no_completed(void)
167 {
168 	return 0;
169 }
170 
171 static void rcu_sync_scale_init(void)
172 {
173 }
174 
175 static struct rcu_scale_ops rcu_ops = {
176 	.ptype		= RCU_FLAVOR,
177 	.init		= rcu_sync_scale_init,
178 	.readlock	= rcu_scale_read_lock,
179 	.readunlock	= rcu_scale_read_unlock,
180 	.get_gp_seq	= rcu_get_gp_seq,
181 	.gp_diff	= rcu_seq_diff,
182 	.exp_completed	= rcu_exp_batches_completed,
183 	.async		= call_rcu_hurry,
184 	.gp_barrier	= rcu_barrier,
185 	.sync		= synchronize_rcu,
186 	.exp_sync	= synchronize_rcu_expedited,
187 	.name		= "rcu"
188 };
189 
190 /*
191  * Definitions for srcu scalability testing.
192  */
193 
194 DEFINE_STATIC_SRCU(srcu_ctl_scale);
195 static struct srcu_struct *srcu_ctlp = &srcu_ctl_scale;
196 
197 static int srcu_scale_read_lock(void) __acquires(srcu_ctlp)
198 {
199 	return srcu_read_lock(srcu_ctlp);
200 }
201 
202 static void srcu_scale_read_unlock(int idx) __releases(srcu_ctlp)
203 {
204 	srcu_read_unlock(srcu_ctlp, idx);
205 }
206 
207 static unsigned long srcu_scale_completed(void)
208 {
209 	return srcu_batches_completed(srcu_ctlp);
210 }
211 
212 static void srcu_call_rcu(struct rcu_head *head, rcu_callback_t func)
213 {
214 	call_srcu(srcu_ctlp, head, func);
215 }
216 
217 static void srcu_rcu_barrier(void)
218 {
219 	srcu_barrier(srcu_ctlp);
220 }
221 
222 static void srcu_scale_synchronize(void)
223 {
224 	synchronize_srcu(srcu_ctlp);
225 }
226 
227 static void srcu_scale_synchronize_expedited(void)
228 {
229 	synchronize_srcu_expedited(srcu_ctlp);
230 }
231 
232 static struct rcu_scale_ops srcu_ops = {
233 	.ptype		= SRCU_FLAVOR,
234 	.init		= rcu_sync_scale_init,
235 	.readlock	= srcu_scale_read_lock,
236 	.readunlock	= srcu_scale_read_unlock,
237 	.get_gp_seq	= srcu_scale_completed,
238 	.gp_diff	= rcu_seq_diff,
239 	.exp_completed	= srcu_scale_completed,
240 	.async		= srcu_call_rcu,
241 	.gp_barrier	= srcu_rcu_barrier,
242 	.sync		= srcu_scale_synchronize,
243 	.exp_sync	= srcu_scale_synchronize_expedited,
244 	.name		= "srcu"
245 };
246 
247 static struct srcu_struct srcud;
248 
249 static void srcu_sync_scale_init(void)
250 {
251 	srcu_ctlp = &srcud;
252 	init_srcu_struct(srcu_ctlp);
253 }
254 
255 static void srcu_sync_scale_cleanup(void)
256 {
257 	cleanup_srcu_struct(srcu_ctlp);
258 }
259 
260 static struct rcu_scale_ops srcud_ops = {
261 	.ptype		= SRCU_FLAVOR,
262 	.init		= srcu_sync_scale_init,
263 	.cleanup	= srcu_sync_scale_cleanup,
264 	.readlock	= srcu_scale_read_lock,
265 	.readunlock	= srcu_scale_read_unlock,
266 	.get_gp_seq	= srcu_scale_completed,
267 	.gp_diff	= rcu_seq_diff,
268 	.exp_completed	= srcu_scale_completed,
269 	.async		= srcu_call_rcu,
270 	.gp_barrier	= srcu_rcu_barrier,
271 	.sync		= srcu_scale_synchronize,
272 	.exp_sync	= srcu_scale_synchronize_expedited,
273 	.name		= "srcud"
274 };
275 
276 #ifdef CONFIG_TASKS_RCU
277 
278 /*
279  * Definitions for RCU-tasks scalability testing.
280  */
281 
282 static int tasks_scale_read_lock(void)
283 {
284 	return 0;
285 }
286 
287 static void tasks_scale_read_unlock(int idx)
288 {
289 }
290 
291 static struct rcu_scale_ops tasks_ops = {
292 	.ptype		= RCU_TASKS_FLAVOR,
293 	.init		= rcu_sync_scale_init,
294 	.readlock	= tasks_scale_read_lock,
295 	.readunlock	= tasks_scale_read_unlock,
296 	.get_gp_seq	= rcu_no_completed,
297 	.gp_diff	= rcu_seq_diff,
298 	.async		= call_rcu_tasks,
299 	.gp_barrier	= rcu_barrier_tasks,
300 	.sync		= synchronize_rcu_tasks,
301 	.exp_sync	= synchronize_rcu_tasks,
302 	.rso_gp_kthread	= get_rcu_tasks_gp_kthread,
303 	.name		= "tasks"
304 };
305 
306 #define TASKS_OPS &tasks_ops,
307 
308 #else // #ifdef CONFIG_TASKS_RCU
309 
310 #define TASKS_OPS
311 
312 #endif // #else // #ifdef CONFIG_TASKS_RCU
313 
314 #ifdef CONFIG_TASKS_RUDE_RCU
315 
316 /*
317  * Definitions for RCU-tasks-rude scalability testing.
318  */
319 
320 static int tasks_rude_scale_read_lock(void)
321 {
322 	return 0;
323 }
324 
325 static void tasks_rude_scale_read_unlock(int idx)
326 {
327 }
328 
329 static struct rcu_scale_ops tasks_rude_ops = {
330 	.ptype		= RCU_TASKS_RUDE_FLAVOR,
331 	.init		= rcu_sync_scale_init,
332 	.readlock	= tasks_rude_scale_read_lock,
333 	.readunlock	= tasks_rude_scale_read_unlock,
334 	.get_gp_seq	= rcu_no_completed,
335 	.gp_diff	= rcu_seq_diff,
336 	.sync		= synchronize_rcu_tasks_rude,
337 	.exp_sync	= synchronize_rcu_tasks_rude,
338 	.rso_gp_kthread	= get_rcu_tasks_rude_gp_kthread,
339 	.name		= "tasks-rude"
340 };
341 
342 #define TASKS_RUDE_OPS &tasks_rude_ops,
343 
344 #else // #ifdef CONFIG_TASKS_RUDE_RCU
345 
346 #define TASKS_RUDE_OPS
347 
348 #endif // #else // #ifdef CONFIG_TASKS_RUDE_RCU
349 
350 #ifdef CONFIG_TASKS_TRACE_RCU
351 
352 /*
353  * Definitions for RCU-tasks-trace scalability testing.
354  */
355 
356 static int tasks_trace_scale_read_lock(void)
357 {
358 	rcu_read_lock_trace();
359 	return 0;
360 }
361 
362 static void tasks_trace_scale_read_unlock(int idx)
363 {
364 	rcu_read_unlock_trace();
365 }
366 
367 static struct rcu_scale_ops tasks_tracing_ops = {
368 	.ptype		= RCU_TASKS_FLAVOR,
369 	.init		= rcu_sync_scale_init,
370 	.readlock	= tasks_trace_scale_read_lock,
371 	.readunlock	= tasks_trace_scale_read_unlock,
372 	.get_gp_seq	= rcu_no_completed,
373 	.gp_diff	= rcu_seq_diff,
374 	.async		= call_rcu_tasks_trace,
375 	.gp_barrier	= rcu_barrier_tasks_trace,
376 	.sync		= synchronize_rcu_tasks_trace,
377 	.exp_sync	= synchronize_rcu_tasks_trace,
378 	.rso_gp_kthread	= get_rcu_tasks_trace_gp_kthread,
379 	.name		= "tasks-tracing"
380 };
381 
382 #define TASKS_TRACING_OPS &tasks_tracing_ops,
383 
384 #else // #ifdef CONFIG_TASKS_TRACE_RCU
385 
386 #define TASKS_TRACING_OPS
387 
388 #endif // #else // #ifdef CONFIG_TASKS_TRACE_RCU
389 
390 static unsigned long rcuscale_seq_diff(unsigned long new, unsigned long old)
391 {
392 	if (!cur_ops->gp_diff)
393 		return new - old;
394 	return cur_ops->gp_diff(new, old);
395 }
396 
397 /*
398  * If scalability tests complete, wait for shutdown to commence.
399  */
400 static void rcu_scale_wait_shutdown(void)
401 {
402 	cond_resched_tasks_rcu_qs();
403 	if (atomic_read(&n_rcu_scale_writer_finished) < nrealwriters)
404 		return;
405 	while (!torture_must_stop())
406 		schedule_timeout_uninterruptible(1);
407 }
408 
409 /*
410  * RCU scalability reader kthread.  Repeatedly does empty RCU read-side
411  * critical section, minimizing update-side interference.  However, the
412  * point of this test is not to evaluate reader scalability, but instead
413  * to serve as a test load for update-side scalability testing.
414  */
415 static int
416 rcu_scale_reader(void *arg)
417 {
418 	unsigned long flags;
419 	int idx;
420 	long me = (long)arg;
421 
422 	VERBOSE_SCALEOUT_STRING("rcu_scale_reader task started");
423 	set_cpus_allowed_ptr(current, cpumask_of(me % nr_cpu_ids));
424 	set_user_nice(current, MAX_NICE);
425 	atomic_inc(&n_rcu_scale_reader_started);
426 
427 	do {
428 		local_irq_save(flags);
429 		idx = cur_ops->readlock();
430 		cur_ops->readunlock(idx);
431 		local_irq_restore(flags);
432 		rcu_scale_wait_shutdown();
433 	} while (!torture_must_stop());
434 	torture_kthread_stopping("rcu_scale_reader");
435 	return 0;
436 }
437 
438 /*
439  * Callback function for asynchronous grace periods from rcu_scale_writer().
440  */
441 static void rcu_scale_async_cb(struct rcu_head *rhp)
442 {
443 	atomic_dec(this_cpu_ptr(&n_async_inflight));
444 	kfree(rhp);
445 }
446 
447 /*
448  * RCU scale writer kthread.  Repeatedly does a grace period.
449  */
450 static int
451 rcu_scale_writer(void *arg)
452 {
453 	int i = 0;
454 	int i_max;
455 	unsigned long jdone;
456 	long me = (long)arg;
457 	struct rcu_head *rhp = NULL;
458 	bool started = false, done = false, alldone = false;
459 	u64 t;
460 	DEFINE_TORTURE_RANDOM(tr);
461 	u64 *wdp;
462 	u64 *wdpp = writer_durations[me];
463 
464 	VERBOSE_SCALEOUT_STRING("rcu_scale_writer task started");
465 	WARN_ON(!wdpp);
466 	set_cpus_allowed_ptr(current, cpumask_of(me % nr_cpu_ids));
467 	current->flags |= PF_NO_SETAFFINITY;
468 	sched_set_fifo_low(current);
469 
470 	if (holdoff)
471 		schedule_timeout_idle(holdoff * HZ);
472 
473 	/*
474 	 * Wait until rcu_end_inkernel_boot() is called for normal GP tests
475 	 * so that RCU is not always expedited for normal GP tests.
476 	 * The system_state test is approximate, but works well in practice.
477 	 */
478 	while (!gp_exp && system_state != SYSTEM_RUNNING)
479 		schedule_timeout_uninterruptible(1);
480 
481 	t = ktime_get_mono_fast_ns();
482 	if (atomic_inc_return(&n_rcu_scale_writer_started) >= nrealwriters) {
483 		t_rcu_scale_writer_started = t;
484 		if (gp_exp) {
485 			b_rcu_gp_test_started =
486 				cur_ops->exp_completed() / 2;
487 		} else {
488 			b_rcu_gp_test_started = cur_ops->get_gp_seq();
489 		}
490 	}
491 
492 	jdone = jiffies + minruntime * HZ;
493 	do {
494 		if (writer_holdoff)
495 			udelay(writer_holdoff);
496 		if (writer_holdoff_jiffies)
497 			schedule_timeout_idle(torture_random(&tr) % writer_holdoff_jiffies + 1);
498 		wdp = &wdpp[i];
499 		*wdp = ktime_get_mono_fast_ns();
500 		if (gp_async) {
501 retry:
502 			if (!rhp)
503 				rhp = kmalloc(sizeof(*rhp), GFP_KERNEL);
504 			if (rhp && atomic_read(this_cpu_ptr(&n_async_inflight)) < gp_async_max) {
505 				atomic_inc(this_cpu_ptr(&n_async_inflight));
506 				cur_ops->async(rhp, rcu_scale_async_cb);
507 				rhp = NULL;
508 			} else if (!kthread_should_stop()) {
509 				cur_ops->gp_barrier();
510 				goto retry;
511 			} else {
512 				kfree(rhp); /* Because we are stopping. */
513 			}
514 		} else if (gp_exp) {
515 			cur_ops->exp_sync();
516 		} else {
517 			cur_ops->sync();
518 		}
519 		t = ktime_get_mono_fast_ns();
520 		*wdp = t - *wdp;
521 		i_max = i;
522 		if (!started &&
523 		    atomic_read(&n_rcu_scale_writer_started) >= nrealwriters)
524 			started = true;
525 		if (!done && i >= MIN_MEAS && time_after(jiffies, jdone)) {
526 			done = true;
527 			sched_set_normal(current, 0);
528 			pr_alert("%s%s rcu_scale_writer %ld has %d measurements\n",
529 				 scale_type, SCALE_FLAG, me, MIN_MEAS);
530 			if (atomic_inc_return(&n_rcu_scale_writer_finished) >=
531 			    nrealwriters) {
532 				schedule_timeout_interruptible(10);
533 				rcu_ftrace_dump(DUMP_ALL);
534 				SCALEOUT_STRING("Test complete");
535 				t_rcu_scale_writer_finished = t;
536 				if (gp_exp) {
537 					b_rcu_gp_test_finished =
538 						cur_ops->exp_completed() / 2;
539 				} else {
540 					b_rcu_gp_test_finished =
541 						cur_ops->get_gp_seq();
542 				}
543 				if (shutdown) {
544 					smp_mb(); /* Assign before wake. */
545 					wake_up(&shutdown_wq);
546 				}
547 			}
548 		}
549 		if (done && !alldone &&
550 		    atomic_read(&n_rcu_scale_writer_finished) >= nrealwriters)
551 			alldone = true;
552 		if (started && !alldone && i < MAX_MEAS - 1)
553 			i++;
554 		rcu_scale_wait_shutdown();
555 	} while (!torture_must_stop());
556 	if (gp_async) {
557 		cur_ops->gp_barrier();
558 	}
559 	writer_n_durations[me] = i_max + 1;
560 	torture_kthread_stopping("rcu_scale_writer");
561 	return 0;
562 }
563 
564 static void
565 rcu_scale_print_module_parms(struct rcu_scale_ops *cur_ops, const char *tag)
566 {
567 	pr_alert("%s" SCALE_FLAG
568 		 "--- %s: gp_async=%d gp_async_max=%d gp_exp=%d holdoff=%d minruntime=%d nreaders=%d nwriters=%d writer_holdoff=%d writer_holdoff_jiffies=%d verbose=%d shutdown=%d\n",
569 		 scale_type, tag, gp_async, gp_async_max, gp_exp, holdoff, minruntime, nrealreaders, nrealwriters, writer_holdoff, writer_holdoff_jiffies, verbose, shutdown);
570 }
571 
572 /*
573  * Return the number if non-negative.  If -1, the number of CPUs.
574  * If less than -1, that much less than the number of CPUs, but
575  * at least one.
576  */
577 static int compute_real(int n)
578 {
579 	int nr;
580 
581 	if (n >= 0) {
582 		nr = n;
583 	} else {
584 		nr = num_online_cpus() + 1 + n;
585 		if (nr <= 0)
586 			nr = 1;
587 	}
588 	return nr;
589 }
590 
591 /*
592  * kfree_rcu() scalability tests: Start a kfree_rcu() loop on all CPUs for number
593  * of iterations and measure total time and number of GP for all iterations to complete.
594  */
595 
596 torture_param(int, kfree_nthreads, -1, "Number of threads running loops of kfree_rcu().");
597 torture_param(int, kfree_alloc_num, 8000, "Number of allocations and frees done in an iteration.");
598 torture_param(int, kfree_loops, 10, "Number of loops doing kfree_alloc_num allocations and frees.");
599 torture_param(bool, kfree_rcu_test_double, false, "Do we run a kfree_rcu() double-argument scale test?");
600 torture_param(bool, kfree_rcu_test_single, false, "Do we run a kfree_rcu() single-argument scale test?");
601 
602 static struct task_struct **kfree_reader_tasks;
603 static int kfree_nrealthreads;
604 static atomic_t n_kfree_scale_thread_started;
605 static atomic_t n_kfree_scale_thread_ended;
606 static struct task_struct *kthread_tp;
607 static u64 kthread_stime;
608 
609 struct kfree_obj {
610 	char kfree_obj[8];
611 	struct rcu_head rh;
612 };
613 
614 /* Used if doing RCU-kfree'ing via call_rcu(). */
615 static void kfree_call_rcu(struct rcu_head *rh)
616 {
617 	struct kfree_obj *obj = container_of(rh, struct kfree_obj, rh);
618 
619 	kfree(obj);
620 }
621 
622 static int
623 kfree_scale_thread(void *arg)
624 {
625 	int i, loop = 0;
626 	long me = (long)arg;
627 	struct kfree_obj *alloc_ptr;
628 	u64 start_time, end_time;
629 	long long mem_begin, mem_during = 0;
630 	bool kfree_rcu_test_both;
631 	DEFINE_TORTURE_RANDOM(tr);
632 
633 	VERBOSE_SCALEOUT_STRING("kfree_scale_thread task started");
634 	set_cpus_allowed_ptr(current, cpumask_of(me % nr_cpu_ids));
635 	set_user_nice(current, MAX_NICE);
636 	kfree_rcu_test_both = (kfree_rcu_test_single == kfree_rcu_test_double);
637 
638 	start_time = ktime_get_mono_fast_ns();
639 
640 	if (atomic_inc_return(&n_kfree_scale_thread_started) >= kfree_nrealthreads) {
641 		if (gp_exp)
642 			b_rcu_gp_test_started = cur_ops->exp_completed() / 2;
643 		else
644 			b_rcu_gp_test_started = cur_ops->get_gp_seq();
645 	}
646 
647 	do {
648 		if (!mem_during) {
649 			mem_during = mem_begin = si_mem_available();
650 		} else if (loop % (kfree_loops / 4) == 0) {
651 			mem_during = (mem_during + si_mem_available()) / 2;
652 		}
653 
654 		for (i = 0; i < kfree_alloc_num; i++) {
655 			alloc_ptr = kmalloc(kfree_mult * sizeof(struct kfree_obj), GFP_KERNEL);
656 			if (!alloc_ptr)
657 				return -ENOMEM;
658 
659 			if (kfree_by_call_rcu) {
660 				call_rcu(&(alloc_ptr->rh), kfree_call_rcu);
661 				continue;
662 			}
663 
664 			// By default kfree_rcu_test_single and kfree_rcu_test_double are
665 			// initialized to false. If both have the same value (false or true)
666 			// both are randomly tested, otherwise only the one with value true
667 			// is tested.
668 			if ((kfree_rcu_test_single && !kfree_rcu_test_double) ||
669 					(kfree_rcu_test_both && torture_random(&tr) & 0x800))
670 				kfree_rcu_mightsleep(alloc_ptr);
671 			else
672 				kfree_rcu(alloc_ptr, rh);
673 		}
674 
675 		cond_resched();
676 	} while (!torture_must_stop() && ++loop < kfree_loops);
677 
678 	if (atomic_inc_return(&n_kfree_scale_thread_ended) >= kfree_nrealthreads) {
679 		end_time = ktime_get_mono_fast_ns();
680 
681 		if (gp_exp)
682 			b_rcu_gp_test_finished = cur_ops->exp_completed() / 2;
683 		else
684 			b_rcu_gp_test_finished = cur_ops->get_gp_seq();
685 
686 		pr_alert("Total time taken by all kfree'ers: %llu ns, loops: %d, batches: %ld, memory footprint: %lldMB\n",
687 		       (unsigned long long)(end_time - start_time), kfree_loops,
688 		       rcuscale_seq_diff(b_rcu_gp_test_finished, b_rcu_gp_test_started),
689 		       (mem_begin - mem_during) >> (20 - PAGE_SHIFT));
690 
691 		if (shutdown) {
692 			smp_mb(); /* Assign before wake. */
693 			wake_up(&shutdown_wq);
694 		}
695 	}
696 
697 	torture_kthread_stopping("kfree_scale_thread");
698 	return 0;
699 }
700 
701 static void
702 kfree_scale_cleanup(void)
703 {
704 	int i;
705 
706 	if (torture_cleanup_begin())
707 		return;
708 
709 	if (kfree_reader_tasks) {
710 		for (i = 0; i < kfree_nrealthreads; i++)
711 			torture_stop_kthread(kfree_scale_thread,
712 					     kfree_reader_tasks[i]);
713 		kfree(kfree_reader_tasks);
714 	}
715 
716 	torture_cleanup_end();
717 }
718 
719 /*
720  * shutdown kthread.  Just waits to be awakened, then shuts down system.
721  */
722 static int
723 kfree_scale_shutdown(void *arg)
724 {
725 	wait_event_idle(shutdown_wq,
726 			atomic_read(&n_kfree_scale_thread_ended) >= kfree_nrealthreads);
727 
728 	smp_mb(); /* Wake before output. */
729 
730 	kfree_scale_cleanup();
731 	kernel_power_off();
732 	return -EINVAL;
733 }
734 
735 // Used if doing RCU-kfree'ing via call_rcu().
736 static unsigned long jiffies_at_lazy_cb;
737 static struct rcu_head lazy_test1_rh;
738 static int rcu_lazy_test1_cb_called;
739 static void call_rcu_lazy_test1(struct rcu_head *rh)
740 {
741 	jiffies_at_lazy_cb = jiffies;
742 	WRITE_ONCE(rcu_lazy_test1_cb_called, 1);
743 }
744 
745 static int __init
746 kfree_scale_init(void)
747 {
748 	int firsterr = 0;
749 	long i;
750 	unsigned long jif_start;
751 	unsigned long orig_jif;
752 
753 	pr_alert("%s" SCALE_FLAG
754 		 "--- kfree_rcu_test: kfree_mult=%d kfree_by_call_rcu=%d kfree_nthreads=%d kfree_alloc_num=%d kfree_loops=%d kfree_rcu_test_double=%d kfree_rcu_test_single=%d\n",
755 		 scale_type, kfree_mult, kfree_by_call_rcu, kfree_nthreads, kfree_alloc_num, kfree_loops, kfree_rcu_test_double, kfree_rcu_test_single);
756 
757 	// Also, do a quick self-test to ensure laziness is as much as
758 	// expected.
759 	if (kfree_by_call_rcu && !IS_ENABLED(CONFIG_RCU_LAZY)) {
760 		pr_alert("CONFIG_RCU_LAZY is disabled, falling back to kfree_rcu() for delayed RCU kfree'ing\n");
761 		kfree_by_call_rcu = 0;
762 	}
763 
764 	if (kfree_by_call_rcu) {
765 		/* do a test to check the timeout. */
766 		orig_jif = rcu_get_jiffies_lazy_flush();
767 
768 		rcu_set_jiffies_lazy_flush(2 * HZ);
769 		rcu_barrier();
770 
771 		jif_start = jiffies;
772 		jiffies_at_lazy_cb = 0;
773 		call_rcu(&lazy_test1_rh, call_rcu_lazy_test1);
774 
775 		smp_cond_load_relaxed(&rcu_lazy_test1_cb_called, VAL == 1);
776 
777 		rcu_set_jiffies_lazy_flush(orig_jif);
778 
779 		if (WARN_ON_ONCE(jiffies_at_lazy_cb - jif_start < 2 * HZ)) {
780 			pr_alert("ERROR: call_rcu() CBs are not being lazy as expected!\n");
781 			WARN_ON_ONCE(1);
782 			return -1;
783 		}
784 
785 		if (WARN_ON_ONCE(jiffies_at_lazy_cb - jif_start > 3 * HZ)) {
786 			pr_alert("ERROR: call_rcu() CBs are being too lazy!\n");
787 			WARN_ON_ONCE(1);
788 			return -1;
789 		}
790 	}
791 
792 	kfree_nrealthreads = compute_real(kfree_nthreads);
793 	/* Start up the kthreads. */
794 	if (shutdown) {
795 		init_waitqueue_head(&shutdown_wq);
796 		firsterr = torture_create_kthread(kfree_scale_shutdown, NULL,
797 						  shutdown_task);
798 		if (torture_init_error(firsterr))
799 			goto unwind;
800 		schedule_timeout_uninterruptible(1);
801 	}
802 
803 	pr_alert("kfree object size=%zu, kfree_by_call_rcu=%d\n",
804 			kfree_mult * sizeof(struct kfree_obj),
805 			kfree_by_call_rcu);
806 
807 	kfree_reader_tasks = kcalloc(kfree_nrealthreads, sizeof(kfree_reader_tasks[0]),
808 			       GFP_KERNEL);
809 	if (kfree_reader_tasks == NULL) {
810 		firsterr = -ENOMEM;
811 		goto unwind;
812 	}
813 
814 	for (i = 0; i < kfree_nrealthreads; i++) {
815 		firsterr = torture_create_kthread(kfree_scale_thread, (void *)i,
816 						  kfree_reader_tasks[i]);
817 		if (torture_init_error(firsterr))
818 			goto unwind;
819 	}
820 
821 	while (atomic_read(&n_kfree_scale_thread_started) < kfree_nrealthreads)
822 		schedule_timeout_uninterruptible(1);
823 
824 	torture_init_end();
825 	return 0;
826 
827 unwind:
828 	torture_init_end();
829 	kfree_scale_cleanup();
830 	return firsterr;
831 }
832 
833 static void
834 rcu_scale_cleanup(void)
835 {
836 	int i;
837 	int j;
838 	int ngps = 0;
839 	u64 *wdp;
840 	u64 *wdpp;
841 
842 	/*
843 	 * Would like warning at start, but everything is expedited
844 	 * during the mid-boot phase, so have to wait till the end.
845 	 */
846 	if (rcu_gp_is_expedited() && !rcu_gp_is_normal() && !gp_exp)
847 		SCALEOUT_ERRSTRING("All grace periods expedited, no normal ones to measure!");
848 	if (rcu_gp_is_normal() && gp_exp)
849 		SCALEOUT_ERRSTRING("All grace periods normal, no expedited ones to measure!");
850 	if (gp_exp && gp_async)
851 		SCALEOUT_ERRSTRING("No expedited async GPs, so went with async!");
852 
853 	// If built-in, just report all of the GP kthread's CPU time.
854 	if (IS_BUILTIN(CONFIG_RCU_SCALE_TEST) && !kthread_tp && cur_ops->rso_gp_kthread)
855 		kthread_tp = cur_ops->rso_gp_kthread();
856 	if (kthread_tp) {
857 		u32 ns;
858 		u64 us;
859 
860 		kthread_stime = kthread_tp->stime - kthread_stime;
861 		us = div_u64_rem(kthread_stime, 1000, &ns);
862 		pr_info("rcu_scale: Grace-period kthread CPU time: %llu.%03u us\n", us, ns);
863 		show_rcu_gp_kthreads();
864 	}
865 	if (kfree_rcu_test) {
866 		kfree_scale_cleanup();
867 		return;
868 	}
869 
870 	if (torture_cleanup_begin())
871 		return;
872 	if (!cur_ops) {
873 		torture_cleanup_end();
874 		return;
875 	}
876 
877 	if (reader_tasks) {
878 		for (i = 0; i < nrealreaders; i++)
879 			torture_stop_kthread(rcu_scale_reader,
880 					     reader_tasks[i]);
881 		kfree(reader_tasks);
882 	}
883 
884 	if (writer_tasks) {
885 		for (i = 0; i < nrealwriters; i++) {
886 			torture_stop_kthread(rcu_scale_writer,
887 					     writer_tasks[i]);
888 			if (!writer_n_durations)
889 				continue;
890 			j = writer_n_durations[i];
891 			pr_alert("%s%s writer %d gps: %d\n",
892 				 scale_type, SCALE_FLAG, i, j);
893 			ngps += j;
894 		}
895 		pr_alert("%s%s start: %llu end: %llu duration: %llu gps: %d batches: %ld\n",
896 			 scale_type, SCALE_FLAG,
897 			 t_rcu_scale_writer_started, t_rcu_scale_writer_finished,
898 			 t_rcu_scale_writer_finished -
899 			 t_rcu_scale_writer_started,
900 			 ngps,
901 			 rcuscale_seq_diff(b_rcu_gp_test_finished,
902 					   b_rcu_gp_test_started));
903 		for (i = 0; i < nrealwriters; i++) {
904 			if (!writer_durations)
905 				break;
906 			if (!writer_n_durations)
907 				continue;
908 			wdpp = writer_durations[i];
909 			if (!wdpp)
910 				continue;
911 			for (j = 0; j < writer_n_durations[i]; j++) {
912 				wdp = &wdpp[j];
913 				pr_alert("%s%s %4d writer-duration: %5d %llu\n",
914 					scale_type, SCALE_FLAG,
915 					i, j, *wdp);
916 				if (j % 100 == 0)
917 					schedule_timeout_uninterruptible(1);
918 			}
919 			kfree(writer_durations[i]);
920 		}
921 		kfree(writer_tasks);
922 		kfree(writer_durations);
923 		kfree(writer_n_durations);
924 	}
925 
926 	/* Do torture-type-specific cleanup operations.  */
927 	if (cur_ops->cleanup != NULL)
928 		cur_ops->cleanup();
929 
930 	torture_cleanup_end();
931 }
932 
933 /*
934  * RCU scalability shutdown kthread.  Just waits to be awakened, then shuts
935  * down system.
936  */
937 static int
938 rcu_scale_shutdown(void *arg)
939 {
940 	wait_event_idle(shutdown_wq, atomic_read(&n_rcu_scale_writer_finished) >= nrealwriters);
941 	smp_mb(); /* Wake before output. */
942 	rcu_scale_cleanup();
943 	kernel_power_off();
944 	return -EINVAL;
945 }
946 
947 static int __init
948 rcu_scale_init(void)
949 {
950 	long i;
951 	int firsterr = 0;
952 	static struct rcu_scale_ops *scale_ops[] = {
953 		&rcu_ops, &srcu_ops, &srcud_ops, TASKS_OPS TASKS_RUDE_OPS TASKS_TRACING_OPS
954 	};
955 
956 	if (!torture_init_begin(scale_type, verbose))
957 		return -EBUSY;
958 
959 	/* Process args and announce that the scalability'er is on the job. */
960 	for (i = 0; i < ARRAY_SIZE(scale_ops); i++) {
961 		cur_ops = scale_ops[i];
962 		if (strcmp(scale_type, cur_ops->name) == 0)
963 			break;
964 	}
965 	if (i == ARRAY_SIZE(scale_ops)) {
966 		pr_alert("rcu-scale: invalid scale type: \"%s\"\n", scale_type);
967 		pr_alert("rcu-scale types:");
968 		for (i = 0; i < ARRAY_SIZE(scale_ops); i++)
969 			pr_cont(" %s", scale_ops[i]->name);
970 		pr_cont("\n");
971 		firsterr = -EINVAL;
972 		cur_ops = NULL;
973 		goto unwind;
974 	}
975 	if (cur_ops->init)
976 		cur_ops->init();
977 
978 	if (cur_ops->rso_gp_kthread) {
979 		kthread_tp = cur_ops->rso_gp_kthread();
980 		if (kthread_tp)
981 			kthread_stime = kthread_tp->stime;
982 	}
983 	if (kfree_rcu_test)
984 		return kfree_scale_init();
985 
986 	nrealwriters = compute_real(nwriters);
987 	nrealreaders = compute_real(nreaders);
988 	atomic_set(&n_rcu_scale_reader_started, 0);
989 	atomic_set(&n_rcu_scale_writer_started, 0);
990 	atomic_set(&n_rcu_scale_writer_finished, 0);
991 	rcu_scale_print_module_parms(cur_ops, "Start of test");
992 
993 	/* Start up the kthreads. */
994 
995 	if (shutdown) {
996 		init_waitqueue_head(&shutdown_wq);
997 		firsterr = torture_create_kthread(rcu_scale_shutdown, NULL,
998 						  shutdown_task);
999 		if (torture_init_error(firsterr))
1000 			goto unwind;
1001 		schedule_timeout_uninterruptible(1);
1002 	}
1003 	reader_tasks = kcalloc(nrealreaders, sizeof(reader_tasks[0]),
1004 			       GFP_KERNEL);
1005 	if (reader_tasks == NULL) {
1006 		SCALEOUT_ERRSTRING("out of memory");
1007 		firsterr = -ENOMEM;
1008 		goto unwind;
1009 	}
1010 	for (i = 0; i < nrealreaders; i++) {
1011 		firsterr = torture_create_kthread(rcu_scale_reader, (void *)i,
1012 						  reader_tasks[i]);
1013 		if (torture_init_error(firsterr))
1014 			goto unwind;
1015 	}
1016 	while (atomic_read(&n_rcu_scale_reader_started) < nrealreaders)
1017 		schedule_timeout_uninterruptible(1);
1018 	writer_tasks = kcalloc(nrealwriters, sizeof(reader_tasks[0]),
1019 			       GFP_KERNEL);
1020 	writer_durations = kcalloc(nrealwriters, sizeof(*writer_durations),
1021 				   GFP_KERNEL);
1022 	writer_n_durations =
1023 		kcalloc(nrealwriters, sizeof(*writer_n_durations),
1024 			GFP_KERNEL);
1025 	if (!writer_tasks || !writer_durations || !writer_n_durations) {
1026 		SCALEOUT_ERRSTRING("out of memory");
1027 		firsterr = -ENOMEM;
1028 		goto unwind;
1029 	}
1030 	for (i = 0; i < nrealwriters; i++) {
1031 		writer_durations[i] =
1032 			kcalloc(MAX_MEAS, sizeof(*writer_durations[i]),
1033 				GFP_KERNEL);
1034 		if (!writer_durations[i]) {
1035 			firsterr = -ENOMEM;
1036 			goto unwind;
1037 		}
1038 		firsterr = torture_create_kthread(rcu_scale_writer, (void *)i,
1039 						  writer_tasks[i]);
1040 		if (torture_init_error(firsterr))
1041 			goto unwind;
1042 	}
1043 	torture_init_end();
1044 	return 0;
1045 
1046 unwind:
1047 	torture_init_end();
1048 	rcu_scale_cleanup();
1049 	if (shutdown) {
1050 		WARN_ON(!IS_MODULE(CONFIG_RCU_SCALE_TEST));
1051 		kernel_power_off();
1052 	}
1053 	return firsterr;
1054 }
1055 
1056 module_init(rcu_scale_init);
1057 module_exit(rcu_scale_cleanup);
1058