xref: /linux-6.15/kernel/kcsan/kcsan_test.c (revision 7310bd1f)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * KCSAN test with various race scenarious to test runtime behaviour. Since the
4  * interface with which KCSAN's reports are obtained is via the console, this is
5  * the output we should verify. For each test case checks the presence (or
6  * absence) of generated reports. Relies on 'console' tracepoint to capture
7  * reports as they appear in the kernel log.
8  *
9  * Makes use of KUnit for test organization, and the Torture framework for test
10  * thread control.
11  *
12  * Copyright (C) 2020, Google LLC.
13  * Author: Marco Elver <[email protected]>
14  */
15 
16 #define pr_fmt(fmt) "kcsan_test: " fmt
17 
18 #include <kunit/test.h>
19 #include <linux/jiffies.h>
20 #include <linux/kcsan-checks.h>
21 #include <linux/kernel.h>
22 #include <linux/sched.h>
23 #include <linux/seqlock.h>
24 #include <linux/spinlock.h>
25 #include <linux/string.h>
26 #include <linux/timer.h>
27 #include <linux/torture.h>
28 #include <linux/tracepoint.h>
29 #include <linux/types.h>
30 #include <trace/events/printk.h>
31 
32 #define KCSAN_TEST_REQUIRES(test, cond) do {			\
33 	if (!(cond))						\
34 		kunit_skip((test), "Test requires: " #cond);	\
35 } while (0)
36 
37 #ifdef CONFIG_CC_HAS_TSAN_COMPOUND_READ_BEFORE_WRITE
38 #define __KCSAN_ACCESS_RW(alt) (KCSAN_ACCESS_COMPOUND | KCSAN_ACCESS_WRITE)
39 #else
40 #define __KCSAN_ACCESS_RW(alt) (alt)
41 #endif
42 
43 /* Points to current test-case memory access "kernels". */
44 static void (*access_kernels[2])(void);
45 
46 static struct task_struct **threads; /* Lists of threads. */
47 static unsigned long end_time;       /* End time of test. */
48 
49 /* Report as observed from console. */
50 static struct {
51 	spinlock_t lock;
52 	int nlines;
53 	char lines[3][512];
54 } observed = {
55 	.lock = __SPIN_LOCK_UNLOCKED(observed.lock),
56 };
57 
58 /* Setup test checking loop. */
59 static __no_kcsan inline void
60 begin_test_checks(void (*func1)(void), void (*func2)(void))
61 {
62 	kcsan_disable_current();
63 
64 	/*
65 	 * Require at least as long as KCSAN_REPORT_ONCE_IN_MS, to ensure at
66 	 * least one race is reported.
67 	 */
68 	end_time = jiffies + msecs_to_jiffies(CONFIG_KCSAN_REPORT_ONCE_IN_MS + 500);
69 
70 	/* Signal start; release potential initialization of shared data. */
71 	smp_store_release(&access_kernels[0], func1);
72 	smp_store_release(&access_kernels[1], func2);
73 }
74 
75 /* End test checking loop. */
76 static __no_kcsan inline bool
77 end_test_checks(bool stop)
78 {
79 	if (!stop && time_before(jiffies, end_time)) {
80 		/* Continue checking */
81 		might_sleep();
82 		return false;
83 	}
84 
85 	kcsan_enable_current();
86 	return true;
87 }
88 
89 /*
90  * Probe for console output: checks if a race was reported, and obtains observed
91  * lines of interest.
92  */
93 __no_kcsan
94 static void probe_console(void *ignore, const char *buf, size_t len)
95 {
96 	unsigned long flags;
97 	int nlines;
98 
99 	/*
100 	 * Note that KCSAN reports under a global lock, so we do not risk the
101 	 * possibility of having multiple reports interleaved. If that were the
102 	 * case, we'd expect tests to fail.
103 	 */
104 
105 	spin_lock_irqsave(&observed.lock, flags);
106 	nlines = observed.nlines;
107 
108 	if (strnstr(buf, "BUG: KCSAN: ", len) && strnstr(buf, "test_", len)) {
109 		/*
110 		 * KCSAN report and related to the test.
111 		 *
112 		 * The provided @buf is not NUL-terminated; copy no more than
113 		 * @len bytes and let strscpy() add the missing NUL-terminator.
114 		 */
115 		strscpy(observed.lines[0], buf, min(len + 1, sizeof(observed.lines[0])));
116 		nlines = 1;
117 	} else if ((nlines == 1 || nlines == 2) && strnstr(buf, "bytes by", len)) {
118 		strscpy(observed.lines[nlines++], buf, min(len + 1, sizeof(observed.lines[0])));
119 
120 		if (strnstr(buf, "race at unknown origin", len)) {
121 			if (WARN_ON(nlines != 2))
122 				goto out;
123 
124 			/* No second line of interest. */
125 			strcpy(observed.lines[nlines++], "<none>");
126 		}
127 	}
128 
129 out:
130 	WRITE_ONCE(observed.nlines, nlines); /* Publish new nlines. */
131 	spin_unlock_irqrestore(&observed.lock, flags);
132 }
133 
134 /* Check if a report related to the test exists. */
135 __no_kcsan
136 static bool report_available(void)
137 {
138 	return READ_ONCE(observed.nlines) == ARRAY_SIZE(observed.lines);
139 }
140 
141 /* Report information we expect in a report. */
142 struct expect_report {
143 	/* Access information of both accesses. */
144 	struct {
145 		void *fn;    /* Function pointer to expected function of top frame. */
146 		void *addr;  /* Address of access; unchecked if NULL. */
147 		size_t size; /* Size of access; unchecked if @addr is NULL. */
148 		int type;    /* Access type, see KCSAN_ACCESS definitions. */
149 	} access[2];
150 };
151 
152 /* Check observed report matches information in @r. */
153 __no_kcsan
154 static bool __report_matches(const struct expect_report *r)
155 {
156 	const bool is_assert = (r->access[0].type | r->access[1].type) & KCSAN_ACCESS_ASSERT;
157 	bool ret = false;
158 	unsigned long flags;
159 	typeof(observed.lines) expect;
160 	const char *end;
161 	char *cur;
162 	int i;
163 
164 	/* Doubled-checked locking. */
165 	if (!report_available())
166 		return false;
167 
168 	/* Generate expected report contents. */
169 
170 	/* Title */
171 	cur = expect[0];
172 	end = &expect[0][sizeof(expect[0]) - 1];
173 	cur += scnprintf(cur, end - cur, "BUG: KCSAN: %s in ",
174 			 is_assert ? "assert: race" : "data-race");
175 	if (r->access[1].fn) {
176 		char tmp[2][64];
177 		int cmp;
178 
179 		/* Expect lexographically sorted function names in title. */
180 		scnprintf(tmp[0], sizeof(tmp[0]), "%pS", r->access[0].fn);
181 		scnprintf(tmp[1], sizeof(tmp[1]), "%pS", r->access[1].fn);
182 		cmp = strcmp(tmp[0], tmp[1]);
183 		cur += scnprintf(cur, end - cur, "%ps / %ps",
184 				 cmp < 0 ? r->access[0].fn : r->access[1].fn,
185 				 cmp < 0 ? r->access[1].fn : r->access[0].fn);
186 	} else {
187 		scnprintf(cur, end - cur, "%pS", r->access[0].fn);
188 		/* The exact offset won't match, remove it. */
189 		cur = strchr(expect[0], '+');
190 		if (cur)
191 			*cur = '\0';
192 	}
193 
194 	/* Access 1 */
195 	cur = expect[1];
196 	end = &expect[1][sizeof(expect[1]) - 1];
197 	if (!r->access[1].fn)
198 		cur += scnprintf(cur, end - cur, "race at unknown origin, with ");
199 
200 	/* Access 1 & 2 */
201 	for (i = 0; i < 2; ++i) {
202 		const int ty = r->access[i].type;
203 		const char *const access_type =
204 			(ty & KCSAN_ACCESS_ASSERT) ?
205 				      ((ty & KCSAN_ACCESS_WRITE) ?
206 					       "assert no accesses" :
207 					       "assert no writes") :
208 				      ((ty & KCSAN_ACCESS_WRITE) ?
209 					       ((ty & KCSAN_ACCESS_COMPOUND) ?
210 							"read-write" :
211 							"write") :
212 					       "read");
213 		const bool is_atomic = (ty & KCSAN_ACCESS_ATOMIC);
214 		const bool is_scoped = (ty & KCSAN_ACCESS_SCOPED);
215 		const char *const access_type_aux =
216 				(is_atomic && is_scoped)	? " (marked, reordered)"
217 				: (is_atomic			? " (marked)"
218 				   : (is_scoped			? " (reordered)" : ""));
219 
220 		if (i == 1) {
221 			/* Access 2 */
222 			cur = expect[2];
223 			end = &expect[2][sizeof(expect[2]) - 1];
224 
225 			if (!r->access[1].fn) {
226 				/* Dummy string if no second access is available. */
227 				strcpy(cur, "<none>");
228 				break;
229 			}
230 		}
231 
232 		cur += scnprintf(cur, end - cur, "%s%s to ", access_type,
233 				 access_type_aux);
234 
235 		if (r->access[i].addr) /* Address is optional. */
236 			cur += scnprintf(cur, end - cur, "0x%px of %zu bytes",
237 					 r->access[i].addr, r->access[i].size);
238 	}
239 
240 	spin_lock_irqsave(&observed.lock, flags);
241 	if (!report_available())
242 		goto out; /* A new report is being captured. */
243 
244 	/* Finally match expected output to what we actually observed. */
245 	ret = strstr(observed.lines[0], expect[0]) &&
246 	      /* Access info may appear in any order. */
247 	      ((strstr(observed.lines[1], expect[1]) &&
248 		strstr(observed.lines[2], expect[2])) ||
249 	       (strstr(observed.lines[1], expect[2]) &&
250 		strstr(observed.lines[2], expect[1])));
251 out:
252 	spin_unlock_irqrestore(&observed.lock, flags);
253 	return ret;
254 }
255 
256 static __always_inline const struct expect_report *
257 __report_set_scoped(struct expect_report *r, int accesses)
258 {
259 	BUILD_BUG_ON(accesses > 3);
260 
261 	if (accesses & 1)
262 		r->access[0].type |= KCSAN_ACCESS_SCOPED;
263 	else
264 		r->access[0].type &= ~KCSAN_ACCESS_SCOPED;
265 
266 	if (accesses & 2)
267 		r->access[1].type |= KCSAN_ACCESS_SCOPED;
268 	else
269 		r->access[1].type &= ~KCSAN_ACCESS_SCOPED;
270 
271 	return r;
272 }
273 
274 __no_kcsan
275 static bool report_matches_any_reordered(struct expect_report *r)
276 {
277 	return __report_matches(__report_set_scoped(r, 0)) ||
278 	       __report_matches(__report_set_scoped(r, 1)) ||
279 	       __report_matches(__report_set_scoped(r, 2)) ||
280 	       __report_matches(__report_set_scoped(r, 3));
281 }
282 
283 #ifdef CONFIG_KCSAN_WEAK_MEMORY
284 /* Due to reordering accesses, any access may appear as "(reordered)". */
285 #define report_matches report_matches_any_reordered
286 #else
287 #define report_matches __report_matches
288 #endif
289 
290 /* ===== Test kernels ===== */
291 
292 static long test_sink;
293 static long test_var;
294 /* @test_array should be large enough to fall into multiple watchpoint slots. */
295 static long test_array[3 * PAGE_SIZE / sizeof(long)];
296 static struct {
297 	long val[8];
298 } test_struct;
299 static DEFINE_SEQLOCK(test_seqlock);
300 
301 /*
302  * Helper to avoid compiler optimizing out reads, and to generate source values
303  * for writes.
304  */
305 __no_kcsan
306 static noinline void sink_value(long v) { WRITE_ONCE(test_sink, v); }
307 
308 static noinline void test_kernel_read(void) { sink_value(test_var); }
309 
310 static noinline void test_kernel_write(void)
311 {
312 	test_var = READ_ONCE_NOCHECK(test_sink) + 1;
313 }
314 
315 static noinline void test_kernel_write_nochange(void) { test_var = 42; }
316 
317 /* Suffixed by value-change exception filter. */
318 static noinline void test_kernel_write_nochange_rcu(void) { test_var = 42; }
319 
320 static noinline void test_kernel_read_atomic(void)
321 {
322 	sink_value(READ_ONCE(test_var));
323 }
324 
325 static noinline void test_kernel_write_atomic(void)
326 {
327 	WRITE_ONCE(test_var, READ_ONCE_NOCHECK(test_sink) + 1);
328 }
329 
330 static noinline void test_kernel_atomic_rmw(void)
331 {
332 	/* Use builtin, so we can set up the "bad" atomic/non-atomic scenario. */
333 	__atomic_fetch_add(&test_var, 1, __ATOMIC_RELAXED);
334 }
335 
336 __no_kcsan
337 static noinline void test_kernel_write_uninstrumented(void) { test_var++; }
338 
339 static noinline void test_kernel_data_race(void) { data_race(test_var++); }
340 
341 static noinline void test_kernel_assert_writer(void)
342 {
343 	ASSERT_EXCLUSIVE_WRITER(test_var);
344 }
345 
346 static noinline void test_kernel_assert_access(void)
347 {
348 	ASSERT_EXCLUSIVE_ACCESS(test_var);
349 }
350 
351 #define TEST_CHANGE_BITS 0xff00ff00
352 
353 static noinline void test_kernel_change_bits(void)
354 {
355 	if (IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS)) {
356 		/*
357 		 * Avoid race of unknown origin for this test, just pretend they
358 		 * are atomic.
359 		 */
360 		kcsan_nestable_atomic_begin();
361 		test_var ^= TEST_CHANGE_BITS;
362 		kcsan_nestable_atomic_end();
363 	} else
364 		WRITE_ONCE(test_var, READ_ONCE(test_var) ^ TEST_CHANGE_BITS);
365 }
366 
367 static noinline void test_kernel_assert_bits_change(void)
368 {
369 	ASSERT_EXCLUSIVE_BITS(test_var, TEST_CHANGE_BITS);
370 }
371 
372 static noinline void test_kernel_assert_bits_nochange(void)
373 {
374 	ASSERT_EXCLUSIVE_BITS(test_var, ~TEST_CHANGE_BITS);
375 }
376 
377 /*
378  * Scoped assertions do trigger anywhere in scope. However, the report should
379  * still only point at the start of the scope.
380  */
381 static noinline void test_enter_scope(void)
382 {
383 	int x = 0;
384 
385 	/* Unrelated accesses to scoped assert. */
386 	READ_ONCE(test_sink);
387 	kcsan_check_read(&x, sizeof(x));
388 }
389 
390 static noinline void test_kernel_assert_writer_scoped(void)
391 {
392 	ASSERT_EXCLUSIVE_WRITER_SCOPED(test_var);
393 	test_enter_scope();
394 }
395 
396 static noinline void test_kernel_assert_access_scoped(void)
397 {
398 	ASSERT_EXCLUSIVE_ACCESS_SCOPED(test_var);
399 	test_enter_scope();
400 }
401 
402 static noinline void test_kernel_rmw_array(void)
403 {
404 	int i;
405 
406 	for (i = 0; i < ARRAY_SIZE(test_array); ++i)
407 		test_array[i]++;
408 }
409 
410 static noinline void test_kernel_write_struct(void)
411 {
412 	kcsan_check_write(&test_struct, sizeof(test_struct));
413 	kcsan_disable_current();
414 	test_struct.val[3]++; /* induce value change */
415 	kcsan_enable_current();
416 }
417 
418 static noinline void test_kernel_write_struct_part(void)
419 {
420 	test_struct.val[3] = 42;
421 }
422 
423 static noinline void test_kernel_read_struct_zero_size(void)
424 {
425 	kcsan_check_read(&test_struct.val[3], 0);
426 }
427 
428 static noinline void test_kernel_jiffies_reader(void)
429 {
430 	sink_value((long)jiffies);
431 }
432 
433 static noinline void test_kernel_seqlock_reader(void)
434 {
435 	unsigned int seq;
436 
437 	do {
438 		seq = read_seqbegin(&test_seqlock);
439 		sink_value(test_var);
440 	} while (read_seqretry(&test_seqlock, seq));
441 }
442 
443 static noinline void test_kernel_seqlock_writer(void)
444 {
445 	unsigned long flags;
446 
447 	write_seqlock_irqsave(&test_seqlock, flags);
448 	test_var++;
449 	write_sequnlock_irqrestore(&test_seqlock, flags);
450 }
451 
452 static noinline void test_kernel_atomic_builtins(void)
453 {
454 	/*
455 	 * Generate concurrent accesses, expecting no reports, ensuring KCSAN
456 	 * treats builtin atomics as actually atomic.
457 	 */
458 	__atomic_load_n(&test_var, __ATOMIC_RELAXED);
459 }
460 
461 static noinline void test_kernel_xor_1bit(void)
462 {
463 	/* Do not report data races between the read-writes. */
464 	kcsan_nestable_atomic_begin();
465 	test_var ^= 0x10000;
466 	kcsan_nestable_atomic_end();
467 }
468 
469 /* ===== Test cases ===== */
470 
471 /* Simple test with normal data race. */
472 __no_kcsan
473 static void test_basic(struct kunit *test)
474 {
475 	struct expect_report expect = {
476 		.access = {
477 			{ test_kernel_write, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
478 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
479 		},
480 	};
481 	struct expect_report never = {
482 		.access = {
483 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
484 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
485 		},
486 	};
487 	bool match_expect = false;
488 	bool match_never = false;
489 
490 	begin_test_checks(test_kernel_write, test_kernel_read);
491 	do {
492 		match_expect |= report_matches(&expect);
493 		match_never = report_matches(&never);
494 	} while (!end_test_checks(match_never));
495 	KUNIT_EXPECT_TRUE(test, match_expect);
496 	KUNIT_EXPECT_FALSE(test, match_never);
497 }
498 
499 /*
500  * Stress KCSAN with lots of concurrent races on different addresses until
501  * timeout.
502  */
503 __no_kcsan
504 static void test_concurrent_races(struct kunit *test)
505 {
506 	struct expect_report expect = {
507 		.access = {
508 			/* NULL will match any address. */
509 			{ test_kernel_rmw_array, NULL, 0, __KCSAN_ACCESS_RW(KCSAN_ACCESS_WRITE) },
510 			{ test_kernel_rmw_array, NULL, 0, __KCSAN_ACCESS_RW(0) },
511 		},
512 	};
513 	struct expect_report never = {
514 		.access = {
515 			{ test_kernel_rmw_array, NULL, 0, 0 },
516 			{ test_kernel_rmw_array, NULL, 0, 0 },
517 		},
518 	};
519 	bool match_expect = false;
520 	bool match_never = false;
521 
522 	begin_test_checks(test_kernel_rmw_array, test_kernel_rmw_array);
523 	do {
524 		match_expect |= report_matches(&expect);
525 		match_never |= report_matches(&never);
526 	} while (!end_test_checks(false));
527 	KUNIT_EXPECT_TRUE(test, match_expect); /* Sanity check matches exist. */
528 	KUNIT_EXPECT_FALSE(test, match_never);
529 }
530 
531 /* Test the KCSAN_REPORT_VALUE_CHANGE_ONLY option. */
532 __no_kcsan
533 static void test_novalue_change(struct kunit *test)
534 {
535 	struct expect_report expect_rw = {
536 		.access = {
537 			{ test_kernel_write_nochange, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
538 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
539 		},
540 	};
541 	struct expect_report expect_ww = {
542 		.access = {
543 			{ test_kernel_write_nochange, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
544 			{ test_kernel_write_nochange, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
545 		},
546 	};
547 	bool match_expect = false;
548 
549 	test_kernel_write_nochange(); /* Reset value. */
550 	begin_test_checks(test_kernel_write_nochange, test_kernel_read);
551 	do {
552 		match_expect = report_matches(&expect_rw) || report_matches(&expect_ww);
553 	} while (!end_test_checks(match_expect));
554 	if (IS_ENABLED(CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY))
555 		KUNIT_EXPECT_FALSE(test, match_expect);
556 	else
557 		KUNIT_EXPECT_TRUE(test, match_expect);
558 }
559 
560 /*
561  * Test that the rules where the KCSAN_REPORT_VALUE_CHANGE_ONLY option should
562  * never apply work.
563  */
564 __no_kcsan
565 static void test_novalue_change_exception(struct kunit *test)
566 {
567 	struct expect_report expect_rw = {
568 		.access = {
569 			{ test_kernel_write_nochange_rcu, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
570 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
571 		},
572 	};
573 	struct expect_report expect_ww = {
574 		.access = {
575 			{ test_kernel_write_nochange_rcu, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
576 			{ test_kernel_write_nochange_rcu, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
577 		},
578 	};
579 	bool match_expect = false;
580 
581 	test_kernel_write_nochange_rcu(); /* Reset value. */
582 	begin_test_checks(test_kernel_write_nochange_rcu, test_kernel_read);
583 	do {
584 		match_expect = report_matches(&expect_rw) || report_matches(&expect_ww);
585 	} while (!end_test_checks(match_expect));
586 	KUNIT_EXPECT_TRUE(test, match_expect);
587 }
588 
589 /* Test that data races of unknown origin are reported. */
590 __no_kcsan
591 static void test_unknown_origin(struct kunit *test)
592 {
593 	struct expect_report expect = {
594 		.access = {
595 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
596 			{ NULL },
597 		},
598 	};
599 	bool match_expect = false;
600 
601 	begin_test_checks(test_kernel_write_uninstrumented, test_kernel_read);
602 	do {
603 		match_expect = report_matches(&expect);
604 	} while (!end_test_checks(match_expect));
605 	if (IS_ENABLED(CONFIG_KCSAN_REPORT_RACE_UNKNOWN_ORIGIN))
606 		KUNIT_EXPECT_TRUE(test, match_expect);
607 	else
608 		KUNIT_EXPECT_FALSE(test, match_expect);
609 }
610 
611 /* Test KCSAN_ASSUME_PLAIN_WRITES_ATOMIC if it is selected. */
612 __no_kcsan
613 static void test_write_write_assume_atomic(struct kunit *test)
614 {
615 	struct expect_report expect = {
616 		.access = {
617 			{ test_kernel_write, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
618 			{ test_kernel_write, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
619 		},
620 	};
621 	bool match_expect = false;
622 
623 	begin_test_checks(test_kernel_write, test_kernel_write);
624 	do {
625 		sink_value(READ_ONCE(test_var)); /* induce value-change */
626 		match_expect = report_matches(&expect);
627 	} while (!end_test_checks(match_expect));
628 	if (IS_ENABLED(CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC))
629 		KUNIT_EXPECT_FALSE(test, match_expect);
630 	else
631 		KUNIT_EXPECT_TRUE(test, match_expect);
632 }
633 
634 /*
635  * Test that data races with writes larger than word-size are always reported,
636  * even if KCSAN_ASSUME_PLAIN_WRITES_ATOMIC is selected.
637  */
638 __no_kcsan
639 static void test_write_write_struct(struct kunit *test)
640 {
641 	struct expect_report expect = {
642 		.access = {
643 			{ test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
644 			{ test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
645 		},
646 	};
647 	bool match_expect = false;
648 
649 	begin_test_checks(test_kernel_write_struct, test_kernel_write_struct);
650 	do {
651 		match_expect = report_matches(&expect);
652 	} while (!end_test_checks(match_expect));
653 	KUNIT_EXPECT_TRUE(test, match_expect);
654 }
655 
656 /*
657  * Test that data races where only one write is larger than word-size are always
658  * reported, even if KCSAN_ASSUME_PLAIN_WRITES_ATOMIC is selected.
659  */
660 __no_kcsan
661 static void test_write_write_struct_part(struct kunit *test)
662 {
663 	struct expect_report expect = {
664 		.access = {
665 			{ test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
666 			{ test_kernel_write_struct_part, &test_struct.val[3], sizeof(test_struct.val[3]), KCSAN_ACCESS_WRITE },
667 		},
668 	};
669 	bool match_expect = false;
670 
671 	begin_test_checks(test_kernel_write_struct, test_kernel_write_struct_part);
672 	do {
673 		match_expect = report_matches(&expect);
674 	} while (!end_test_checks(match_expect));
675 	KUNIT_EXPECT_TRUE(test, match_expect);
676 }
677 
678 /* Test that races with atomic accesses never result in reports. */
679 __no_kcsan
680 static void test_read_atomic_write_atomic(struct kunit *test)
681 {
682 	bool match_never = false;
683 
684 	begin_test_checks(test_kernel_read_atomic, test_kernel_write_atomic);
685 	do {
686 		match_never = report_available();
687 	} while (!end_test_checks(match_never));
688 	KUNIT_EXPECT_FALSE(test, match_never);
689 }
690 
691 /* Test that a race with an atomic and plain access result in reports. */
692 __no_kcsan
693 static void test_read_plain_atomic_write(struct kunit *test)
694 {
695 	struct expect_report expect = {
696 		.access = {
697 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
698 			{ test_kernel_write_atomic, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ATOMIC },
699 		},
700 	};
701 	bool match_expect = false;
702 
703 	KCSAN_TEST_REQUIRES(test, !IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS));
704 
705 	begin_test_checks(test_kernel_read, test_kernel_write_atomic);
706 	do {
707 		match_expect = report_matches(&expect);
708 	} while (!end_test_checks(match_expect));
709 	KUNIT_EXPECT_TRUE(test, match_expect);
710 }
711 
712 /* Test that atomic RMWs generate correct report. */
713 __no_kcsan
714 static void test_read_plain_atomic_rmw(struct kunit *test)
715 {
716 	struct expect_report expect = {
717 		.access = {
718 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
719 			{ test_kernel_atomic_rmw, &test_var, sizeof(test_var),
720 				KCSAN_ACCESS_COMPOUND | KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ATOMIC },
721 		},
722 	};
723 	bool match_expect = false;
724 
725 	KCSAN_TEST_REQUIRES(test, !IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS));
726 
727 	begin_test_checks(test_kernel_read, test_kernel_atomic_rmw);
728 	do {
729 		match_expect = report_matches(&expect);
730 	} while (!end_test_checks(match_expect));
731 	KUNIT_EXPECT_TRUE(test, match_expect);
732 }
733 
734 /* Zero-sized accesses should never cause data race reports. */
735 __no_kcsan
736 static void test_zero_size_access(struct kunit *test)
737 {
738 	struct expect_report expect = {
739 		.access = {
740 			{ test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
741 			{ test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
742 		},
743 	};
744 	struct expect_report never = {
745 		.access = {
746 			{ test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
747 			{ test_kernel_read_struct_zero_size, &test_struct.val[3], 0, 0 },
748 		},
749 	};
750 	bool match_expect = false;
751 	bool match_never = false;
752 
753 	begin_test_checks(test_kernel_write_struct, test_kernel_read_struct_zero_size);
754 	do {
755 		match_expect |= report_matches(&expect);
756 		match_never = report_matches(&never);
757 	} while (!end_test_checks(match_never));
758 	KUNIT_EXPECT_TRUE(test, match_expect); /* Sanity check. */
759 	KUNIT_EXPECT_FALSE(test, match_never);
760 }
761 
762 /* Test the data_race() macro. */
763 __no_kcsan
764 static void test_data_race(struct kunit *test)
765 {
766 	bool match_never = false;
767 
768 	begin_test_checks(test_kernel_data_race, test_kernel_data_race);
769 	do {
770 		match_never = report_available();
771 	} while (!end_test_checks(match_never));
772 	KUNIT_EXPECT_FALSE(test, match_never);
773 }
774 
775 __no_kcsan
776 static void test_assert_exclusive_writer(struct kunit *test)
777 {
778 	struct expect_report expect = {
779 		.access = {
780 			{ test_kernel_assert_writer, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT },
781 			{ test_kernel_write_nochange, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
782 		},
783 	};
784 	bool match_expect = false;
785 
786 	begin_test_checks(test_kernel_assert_writer, test_kernel_write_nochange);
787 	do {
788 		match_expect = report_matches(&expect);
789 	} while (!end_test_checks(match_expect));
790 	KUNIT_EXPECT_TRUE(test, match_expect);
791 }
792 
793 __no_kcsan
794 static void test_assert_exclusive_access(struct kunit *test)
795 {
796 	struct expect_report expect = {
797 		.access = {
798 			{ test_kernel_assert_access, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE },
799 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
800 		},
801 	};
802 	bool match_expect = false;
803 
804 	begin_test_checks(test_kernel_assert_access, test_kernel_read);
805 	do {
806 		match_expect = report_matches(&expect);
807 	} while (!end_test_checks(match_expect));
808 	KUNIT_EXPECT_TRUE(test, match_expect);
809 }
810 
811 __no_kcsan
812 static void test_assert_exclusive_access_writer(struct kunit *test)
813 {
814 	struct expect_report expect_access_writer = {
815 		.access = {
816 			{ test_kernel_assert_access, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE },
817 			{ test_kernel_assert_writer, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT },
818 		},
819 	};
820 	struct expect_report expect_access_access = {
821 		.access = {
822 			{ test_kernel_assert_access, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE },
823 			{ test_kernel_assert_access, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE },
824 		},
825 	};
826 	struct expect_report never = {
827 		.access = {
828 			{ test_kernel_assert_writer, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT },
829 			{ test_kernel_assert_writer, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT },
830 		},
831 	};
832 	bool match_expect_access_writer = false;
833 	bool match_expect_access_access = false;
834 	bool match_never = false;
835 
836 	begin_test_checks(test_kernel_assert_access, test_kernel_assert_writer);
837 	do {
838 		match_expect_access_writer |= report_matches(&expect_access_writer);
839 		match_expect_access_access |= report_matches(&expect_access_access);
840 		match_never |= report_matches(&never);
841 	} while (!end_test_checks(match_never));
842 	KUNIT_EXPECT_TRUE(test, match_expect_access_writer);
843 	KUNIT_EXPECT_TRUE(test, match_expect_access_access);
844 	KUNIT_EXPECT_FALSE(test, match_never);
845 }
846 
847 __no_kcsan
848 static void test_assert_exclusive_bits_change(struct kunit *test)
849 {
850 	struct expect_report expect = {
851 		.access = {
852 			{ test_kernel_assert_bits_change, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT },
853 			{ test_kernel_change_bits, &test_var, sizeof(test_var),
854 				KCSAN_ACCESS_WRITE | (IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS) ? 0 : KCSAN_ACCESS_ATOMIC) },
855 		},
856 	};
857 	bool match_expect = false;
858 
859 	begin_test_checks(test_kernel_assert_bits_change, test_kernel_change_bits);
860 	do {
861 		match_expect = report_matches(&expect);
862 	} while (!end_test_checks(match_expect));
863 	KUNIT_EXPECT_TRUE(test, match_expect);
864 }
865 
866 __no_kcsan
867 static void test_assert_exclusive_bits_nochange(struct kunit *test)
868 {
869 	bool match_never = false;
870 
871 	begin_test_checks(test_kernel_assert_bits_nochange, test_kernel_change_bits);
872 	do {
873 		match_never = report_available();
874 	} while (!end_test_checks(match_never));
875 	KUNIT_EXPECT_FALSE(test, match_never);
876 }
877 
878 __no_kcsan
879 static void test_assert_exclusive_writer_scoped(struct kunit *test)
880 {
881 	struct expect_report expect_start = {
882 		.access = {
883 			{ test_kernel_assert_writer_scoped, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_SCOPED },
884 			{ test_kernel_write_nochange, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
885 		},
886 	};
887 	struct expect_report expect_inscope = {
888 		.access = {
889 			{ test_enter_scope, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_SCOPED },
890 			{ test_kernel_write_nochange, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
891 		},
892 	};
893 	bool match_expect_start = false;
894 	bool match_expect_inscope = false;
895 
896 	begin_test_checks(test_kernel_assert_writer_scoped, test_kernel_write_nochange);
897 	do {
898 		match_expect_start |= report_matches(&expect_start);
899 		match_expect_inscope |= report_matches(&expect_inscope);
900 	} while (!end_test_checks(match_expect_inscope));
901 	KUNIT_EXPECT_TRUE(test, match_expect_start);
902 	KUNIT_EXPECT_FALSE(test, match_expect_inscope);
903 }
904 
905 __no_kcsan
906 static void test_assert_exclusive_access_scoped(struct kunit *test)
907 {
908 	struct expect_report expect_start1 = {
909 		.access = {
910 			{ test_kernel_assert_access_scoped, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE | KCSAN_ACCESS_SCOPED },
911 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
912 		},
913 	};
914 	struct expect_report expect_start2 = {
915 		.access = { expect_start1.access[0], expect_start1.access[0] },
916 	};
917 	struct expect_report expect_inscope = {
918 		.access = {
919 			{ test_enter_scope, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE | KCSAN_ACCESS_SCOPED },
920 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
921 		},
922 	};
923 	bool match_expect_start = false;
924 	bool match_expect_inscope = false;
925 
926 	begin_test_checks(test_kernel_assert_access_scoped, test_kernel_read);
927 	end_time += msecs_to_jiffies(1000); /* This test requires a bit more time. */
928 	do {
929 		match_expect_start |= report_matches(&expect_start1) || report_matches(&expect_start2);
930 		match_expect_inscope |= report_matches(&expect_inscope);
931 	} while (!end_test_checks(match_expect_inscope));
932 	KUNIT_EXPECT_TRUE(test, match_expect_start);
933 	KUNIT_EXPECT_FALSE(test, match_expect_inscope);
934 }
935 
936 /*
937  * jiffies is special (declared to be volatile) and its accesses are typically
938  * not marked; this test ensures that the compiler nor KCSAN gets confused about
939  * jiffies's declaration on different architectures.
940  */
941 __no_kcsan
942 static void test_jiffies_noreport(struct kunit *test)
943 {
944 	bool match_never = false;
945 
946 	begin_test_checks(test_kernel_jiffies_reader, test_kernel_jiffies_reader);
947 	do {
948 		match_never = report_available();
949 	} while (!end_test_checks(match_never));
950 	KUNIT_EXPECT_FALSE(test, match_never);
951 }
952 
953 /* Test that racing accesses in seqlock critical sections are not reported. */
954 __no_kcsan
955 static void test_seqlock_noreport(struct kunit *test)
956 {
957 	bool match_never = false;
958 
959 	begin_test_checks(test_kernel_seqlock_reader, test_kernel_seqlock_writer);
960 	do {
961 		match_never = report_available();
962 	} while (!end_test_checks(match_never));
963 	KUNIT_EXPECT_FALSE(test, match_never);
964 }
965 
966 /*
967  * Test atomic builtins work and required instrumentation functions exist. We
968  * also test that KCSAN understands they're atomic by racing with them via
969  * test_kernel_atomic_builtins(), and expect no reports.
970  *
971  * The atomic builtins _SHOULD NOT_ be used in normal kernel code!
972  */
973 static void test_atomic_builtins(struct kunit *test)
974 {
975 	bool match_never = false;
976 
977 	begin_test_checks(test_kernel_atomic_builtins, test_kernel_atomic_builtins);
978 	do {
979 		long tmp;
980 
981 		kcsan_enable_current();
982 
983 		__atomic_store_n(&test_var, 42L, __ATOMIC_RELAXED);
984 		KUNIT_EXPECT_EQ(test, 42L, __atomic_load_n(&test_var, __ATOMIC_RELAXED));
985 
986 		KUNIT_EXPECT_EQ(test, 42L, __atomic_exchange_n(&test_var, 20, __ATOMIC_RELAXED));
987 		KUNIT_EXPECT_EQ(test, 20L, test_var);
988 
989 		tmp = 20L;
990 		KUNIT_EXPECT_TRUE(test, __atomic_compare_exchange_n(&test_var, &tmp, 30L,
991 								    0, __ATOMIC_RELAXED,
992 								    __ATOMIC_RELAXED));
993 		KUNIT_EXPECT_EQ(test, tmp, 20L);
994 		KUNIT_EXPECT_EQ(test, test_var, 30L);
995 		KUNIT_EXPECT_FALSE(test, __atomic_compare_exchange_n(&test_var, &tmp, 40L,
996 								     1, __ATOMIC_RELAXED,
997 								     __ATOMIC_RELAXED));
998 		KUNIT_EXPECT_EQ(test, tmp, 30L);
999 		KUNIT_EXPECT_EQ(test, test_var, 30L);
1000 
1001 		KUNIT_EXPECT_EQ(test, 30L, __atomic_fetch_add(&test_var, 1, __ATOMIC_RELAXED));
1002 		KUNIT_EXPECT_EQ(test, 31L, __atomic_fetch_sub(&test_var, 1, __ATOMIC_RELAXED));
1003 		KUNIT_EXPECT_EQ(test, 30L, __atomic_fetch_and(&test_var, 0xf, __ATOMIC_RELAXED));
1004 		KUNIT_EXPECT_EQ(test, 14L, __atomic_fetch_xor(&test_var, 0xf, __ATOMIC_RELAXED));
1005 		KUNIT_EXPECT_EQ(test, 1L, __atomic_fetch_or(&test_var, 0xf0, __ATOMIC_RELAXED));
1006 		KUNIT_EXPECT_EQ(test, 241L, __atomic_fetch_nand(&test_var, 0xf, __ATOMIC_RELAXED));
1007 		KUNIT_EXPECT_EQ(test, -2L, test_var);
1008 
1009 		__atomic_thread_fence(__ATOMIC_SEQ_CST);
1010 		__atomic_signal_fence(__ATOMIC_SEQ_CST);
1011 
1012 		kcsan_disable_current();
1013 
1014 		match_never = report_available();
1015 	} while (!end_test_checks(match_never));
1016 	KUNIT_EXPECT_FALSE(test, match_never);
1017 }
1018 
1019 __no_kcsan
1020 static void test_1bit_value_change(struct kunit *test)
1021 {
1022 	struct expect_report expect = {
1023 		.access = {
1024 			{ test_kernel_read, &test_var, sizeof(test_var), 0 },
1025 			{ test_kernel_xor_1bit, &test_var, sizeof(test_var), __KCSAN_ACCESS_RW(KCSAN_ACCESS_WRITE) },
1026 		},
1027 	};
1028 	bool match = false;
1029 
1030 	begin_test_checks(test_kernel_read, test_kernel_xor_1bit);
1031 	do {
1032 		match = IS_ENABLED(CONFIG_KCSAN_PERMISSIVE)
1033 				? report_available()
1034 				: report_matches(&expect);
1035 	} while (!end_test_checks(match));
1036 	if (IS_ENABLED(CONFIG_KCSAN_PERMISSIVE))
1037 		KUNIT_EXPECT_FALSE(test, match);
1038 	else
1039 		KUNIT_EXPECT_TRUE(test, match);
1040 }
1041 
1042 /*
1043  * Generate thread counts for all test cases. Values generated are in interval
1044  * [2, 5] followed by exponentially increasing thread counts from 8 to 32.
1045  *
1046  * The thread counts are chosen to cover potentially interesting boundaries and
1047  * corner cases (2 to 5), and then stress the system with larger counts.
1048  */
1049 static const void *nthreads_gen_params(const void *prev, char *desc)
1050 {
1051 	long nthreads = (long)prev;
1052 
1053 	if (nthreads < 0 || nthreads >= 32)
1054 		nthreads = 0; /* stop */
1055 	else if (!nthreads)
1056 		nthreads = 2; /* initial value */
1057 	else if (nthreads < 5)
1058 		nthreads++;
1059 	else if (nthreads == 5)
1060 		nthreads = 8;
1061 	else
1062 		nthreads *= 2;
1063 
1064 	if (!IS_ENABLED(CONFIG_PREEMPT) || !IS_ENABLED(CONFIG_KCSAN_INTERRUPT_WATCHER)) {
1065 		/*
1066 		 * Without any preemption, keep 2 CPUs free for other tasks, one
1067 		 * of which is the main test case function checking for
1068 		 * completion or failure.
1069 		 */
1070 		const long min_unused_cpus = IS_ENABLED(CONFIG_PREEMPT_NONE) ? 2 : 0;
1071 		const long min_required_cpus = 2 + min_unused_cpus;
1072 
1073 		if (num_online_cpus() < min_required_cpus) {
1074 			pr_err_once("Too few online CPUs (%u < %ld) for test\n",
1075 				    num_online_cpus(), min_required_cpus);
1076 			nthreads = 0;
1077 		} else if (nthreads >= num_online_cpus() - min_unused_cpus) {
1078 			/* Use negative value to indicate last param. */
1079 			nthreads = -(num_online_cpus() - min_unused_cpus);
1080 			pr_warn_once("Limiting number of threads to %ld (only %d online CPUs)\n",
1081 				     -nthreads, num_online_cpus());
1082 		}
1083 	}
1084 
1085 	snprintf(desc, KUNIT_PARAM_DESC_SIZE, "threads=%ld", abs(nthreads));
1086 	return (void *)nthreads;
1087 }
1088 
1089 #define KCSAN_KUNIT_CASE(test_name) KUNIT_CASE_PARAM(test_name, nthreads_gen_params)
1090 static struct kunit_case kcsan_test_cases[] = {
1091 	KCSAN_KUNIT_CASE(test_basic),
1092 	KCSAN_KUNIT_CASE(test_concurrent_races),
1093 	KCSAN_KUNIT_CASE(test_novalue_change),
1094 	KCSAN_KUNIT_CASE(test_novalue_change_exception),
1095 	KCSAN_KUNIT_CASE(test_unknown_origin),
1096 	KCSAN_KUNIT_CASE(test_write_write_assume_atomic),
1097 	KCSAN_KUNIT_CASE(test_write_write_struct),
1098 	KCSAN_KUNIT_CASE(test_write_write_struct_part),
1099 	KCSAN_KUNIT_CASE(test_read_atomic_write_atomic),
1100 	KCSAN_KUNIT_CASE(test_read_plain_atomic_write),
1101 	KCSAN_KUNIT_CASE(test_read_plain_atomic_rmw),
1102 	KCSAN_KUNIT_CASE(test_zero_size_access),
1103 	KCSAN_KUNIT_CASE(test_data_race),
1104 	KCSAN_KUNIT_CASE(test_assert_exclusive_writer),
1105 	KCSAN_KUNIT_CASE(test_assert_exclusive_access),
1106 	KCSAN_KUNIT_CASE(test_assert_exclusive_access_writer),
1107 	KCSAN_KUNIT_CASE(test_assert_exclusive_bits_change),
1108 	KCSAN_KUNIT_CASE(test_assert_exclusive_bits_nochange),
1109 	KCSAN_KUNIT_CASE(test_assert_exclusive_writer_scoped),
1110 	KCSAN_KUNIT_CASE(test_assert_exclusive_access_scoped),
1111 	KCSAN_KUNIT_CASE(test_jiffies_noreport),
1112 	KCSAN_KUNIT_CASE(test_seqlock_noreport),
1113 	KCSAN_KUNIT_CASE(test_atomic_builtins),
1114 	KCSAN_KUNIT_CASE(test_1bit_value_change),
1115 	{},
1116 };
1117 
1118 /* ===== End test cases ===== */
1119 
1120 /* Concurrent accesses from interrupts. */
1121 __no_kcsan
1122 static void access_thread_timer(struct timer_list *timer)
1123 {
1124 	static atomic_t cnt = ATOMIC_INIT(0);
1125 	unsigned int idx;
1126 	void (*func)(void);
1127 
1128 	idx = (unsigned int)atomic_inc_return(&cnt) % ARRAY_SIZE(access_kernels);
1129 	/* Acquire potential initialization. */
1130 	func = smp_load_acquire(&access_kernels[idx]);
1131 	if (func)
1132 		func();
1133 }
1134 
1135 /* The main loop for each thread. */
1136 __no_kcsan
1137 static int access_thread(void *arg)
1138 {
1139 	struct timer_list timer;
1140 	unsigned int cnt = 0;
1141 	unsigned int idx;
1142 	void (*func)(void);
1143 
1144 	timer_setup_on_stack(&timer, access_thread_timer, 0);
1145 	do {
1146 		might_sleep();
1147 
1148 		if (!timer_pending(&timer))
1149 			mod_timer(&timer, jiffies + 1);
1150 		else {
1151 			/* Iterate through all kernels. */
1152 			idx = cnt++ % ARRAY_SIZE(access_kernels);
1153 			/* Acquire potential initialization. */
1154 			func = smp_load_acquire(&access_kernels[idx]);
1155 			if (func)
1156 				func();
1157 		}
1158 	} while (!torture_must_stop());
1159 	del_timer_sync(&timer);
1160 	destroy_timer_on_stack(&timer);
1161 
1162 	torture_kthread_stopping("access_thread");
1163 	return 0;
1164 }
1165 
1166 __no_kcsan
1167 static int test_init(struct kunit *test)
1168 {
1169 	unsigned long flags;
1170 	int nthreads;
1171 	int i;
1172 
1173 	spin_lock_irqsave(&observed.lock, flags);
1174 	for (i = 0; i < ARRAY_SIZE(observed.lines); ++i)
1175 		observed.lines[i][0] = '\0';
1176 	observed.nlines = 0;
1177 	spin_unlock_irqrestore(&observed.lock, flags);
1178 
1179 	if (!torture_init_begin((char *)test->name, 1))
1180 		return -EBUSY;
1181 
1182 	if (WARN_ON(threads))
1183 		goto err;
1184 
1185 	for (i = 0; i < ARRAY_SIZE(access_kernels); ++i) {
1186 		if (WARN_ON(access_kernels[i]))
1187 			goto err;
1188 	}
1189 
1190 	nthreads = abs((long)test->param_value);
1191 	if (WARN_ON(!nthreads))
1192 		goto err;
1193 
1194 	threads = kcalloc(nthreads + 1, sizeof(struct task_struct *), GFP_KERNEL);
1195 	if (WARN_ON(!threads))
1196 		goto err;
1197 
1198 	threads[nthreads] = NULL;
1199 	for (i = 0; i < nthreads; ++i) {
1200 		if (torture_create_kthread(access_thread, NULL, threads[i]))
1201 			goto err;
1202 	}
1203 
1204 	torture_init_end();
1205 
1206 	return 0;
1207 
1208 err:
1209 	kfree(threads);
1210 	threads = NULL;
1211 	torture_init_end();
1212 	return -EINVAL;
1213 }
1214 
1215 __no_kcsan
1216 static void test_exit(struct kunit *test)
1217 {
1218 	struct task_struct **stop_thread;
1219 	int i;
1220 
1221 	if (torture_cleanup_begin())
1222 		return;
1223 
1224 	for (i = 0; i < ARRAY_SIZE(access_kernels); ++i)
1225 		WRITE_ONCE(access_kernels[i], NULL);
1226 
1227 	if (threads) {
1228 		for (stop_thread = threads; *stop_thread; stop_thread++)
1229 			torture_stop_kthread(reader_thread, *stop_thread);
1230 
1231 		kfree(threads);
1232 		threads = NULL;
1233 	}
1234 
1235 	torture_cleanup_end();
1236 }
1237 
1238 static struct kunit_suite kcsan_test_suite = {
1239 	.name = "kcsan",
1240 	.test_cases = kcsan_test_cases,
1241 	.init = test_init,
1242 	.exit = test_exit,
1243 };
1244 static struct kunit_suite *kcsan_test_suites[] = { &kcsan_test_suite, NULL };
1245 
1246 __no_kcsan
1247 static void register_tracepoints(struct tracepoint *tp, void *ignore)
1248 {
1249 	check_trace_callback_type_console(probe_console);
1250 	if (!strcmp(tp->name, "console"))
1251 		WARN_ON(tracepoint_probe_register(tp, probe_console, NULL));
1252 }
1253 
1254 __no_kcsan
1255 static void unregister_tracepoints(struct tracepoint *tp, void *ignore)
1256 {
1257 	if (!strcmp(tp->name, "console"))
1258 		tracepoint_probe_unregister(tp, probe_console, NULL);
1259 }
1260 
1261 /*
1262  * We only want to do tracepoints setup and teardown once, therefore we have to
1263  * customize the init and exit functions and cannot rely on kunit_test_suite().
1264  */
1265 static int __init kcsan_test_init(void)
1266 {
1267 	/*
1268 	 * Because we want to be able to build the test as a module, we need to
1269 	 * iterate through all known tracepoints, since the static registration
1270 	 * won't work here.
1271 	 */
1272 	for_each_kernel_tracepoint(register_tracepoints, NULL);
1273 	return __kunit_test_suites_init(kcsan_test_suites);
1274 }
1275 
1276 static void kcsan_test_exit(void)
1277 {
1278 	__kunit_test_suites_exit(kcsan_test_suites);
1279 	for_each_kernel_tracepoint(unregister_tracepoints, NULL);
1280 	tracepoint_synchronize_unregister();
1281 }
1282 
1283 late_initcall_sync(kcsan_test_init);
1284 module_exit(kcsan_test_exit);
1285 
1286 MODULE_LICENSE("GPL v2");
1287 MODULE_AUTHOR("Marco Elver <[email protected]>");
1288