1 // SPDX-License-Identifier: GPL-2.0
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.
9 * Makes use of KUnit for test organization, and the Torture framework for test
12 * Copyright (C) 2020, Google LLC.
13 * Author: Marco Elver <elver@google.com>
16 #include <kunit/test.h>
17 #include <linux/jiffies.h>
18 #include <linux/kcsan-checks.h>
19 #include <linux/kernel.h>
20 #include <linux/sched.h>
21 #include <linux/seqlock.h>
22 #include <linux/spinlock.h>
23 #include <linux/string.h>
24 #include <linux/timer.h>
25 #include <linux/torture.h>
26 #include <linux/tracepoint.h>
27 #include <linux/types.h>
28 #include <trace/events/printk.h>
30 #ifdef CONFIG_CC_HAS_TSAN_COMPOUND_READ_BEFORE_WRITE
31 #define __KCSAN_ACCESS_RW(alt) (KCSAN_ACCESS_COMPOUND | KCSAN_ACCESS_WRITE)
33 #define __KCSAN_ACCESS_RW(alt) (alt)
36 /* Points to current test-case memory access "kernels". */
37 static void (*access_kernels[2])(void);
39 static struct task_struct **threads; /* Lists of threads. */
40 static unsigned long end_time; /* End time of test. */
42 /* Report as observed from console. */
48 .lock = __SPIN_LOCK_UNLOCKED(observed.lock),
51 /* Setup test checking loop. */
52 static __no_kcsan inline void
53 begin_test_checks(void (*func1)(void), void (*func2)(void))
55 kcsan_disable_current();
58 * Require at least as long as KCSAN_REPORT_ONCE_IN_MS, to ensure at
59 * least one race is reported.
61 end_time = jiffies + msecs_to_jiffies(CONFIG_KCSAN_REPORT_ONCE_IN_MS + 500);
63 /* Signal start; release potential initialization of shared data. */
64 smp_store_release(&access_kernels[0], func1);
65 smp_store_release(&access_kernels[1], func2);
68 /* End test checking loop. */
69 static __no_kcsan inline bool
70 end_test_checks(bool stop)
72 if (!stop && time_before(jiffies, end_time)) {
73 /* Continue checking */
78 kcsan_enable_current();
83 * Probe for console output: checks if a race was reported, and obtains observed
87 static void probe_console(void *ignore, const char *buf, size_t len)
93 * Note that KCSAN reports under a global lock, so we do not risk the
94 * possibility of having multiple reports interleaved. If that were the
95 * case, we'd expect tests to fail.
98 spin_lock_irqsave(&observed.lock, flags);
99 nlines = observed.nlines;
101 if (strnstr(buf, "BUG: KCSAN: ", len) && strnstr(buf, "test_", len)) {
103 * KCSAN report and related to the test.
105 * The provided @buf is not NUL-terminated; copy no more than
106 * @len bytes and let strscpy() add the missing NUL-terminator.
108 strscpy(observed.lines[0], buf, min(len + 1, sizeof(observed.lines[0])));
110 } else if ((nlines == 1 || nlines == 2) && strnstr(buf, "bytes by", len)) {
111 strscpy(observed.lines[nlines++], buf, min(len + 1, sizeof(observed.lines[0])));
113 if (strnstr(buf, "race at unknown origin", len)) {
114 if (WARN_ON(nlines != 2))
117 /* No second line of interest. */
118 strcpy(observed.lines[nlines++], "<none>");
123 WRITE_ONCE(observed.nlines, nlines); /* Publish new nlines. */
124 spin_unlock_irqrestore(&observed.lock, flags);
127 /* Check if a report related to the test exists. */
129 static bool report_available(void)
131 return READ_ONCE(observed.nlines) == ARRAY_SIZE(observed.lines);
134 /* Report information we expect in a report. */
135 struct expect_report {
136 /* Access information of both accesses. */
138 void *fn; /* Function pointer to expected function of top frame. */
139 void *addr; /* Address of access; unchecked if NULL. */
140 size_t size; /* Size of access; unchecked if @addr is NULL. */
141 int type; /* Access type, see KCSAN_ACCESS definitions. */
145 /* Check observed report matches information in @r. */
147 static bool report_matches(const struct expect_report *r)
149 const bool is_assert = (r->access[0].type | r->access[1].type) & KCSAN_ACCESS_ASSERT;
152 typeof(*observed.lines) *expect;
157 /* Doubled-checked locking. */
158 if (!report_available())
161 expect = kmalloc(sizeof(observed.lines), GFP_KERNEL);
162 if (WARN_ON(!expect))
165 /* Generate expected report contents. */
169 end = &expect[0][sizeof(expect[0]) - 1];
170 cur += scnprintf(cur, end - cur, "BUG: KCSAN: %s in ",
171 is_assert ? "assert: race" : "data-race");
172 if (r->access[1].fn) {
176 /* Expect lexographically sorted function names in title. */
177 scnprintf(tmp[0], sizeof(tmp[0]), "%pS", r->access[0].fn);
178 scnprintf(tmp[1], sizeof(tmp[1]), "%pS", r->access[1].fn);
179 cmp = strcmp(tmp[0], tmp[1]);
180 cur += scnprintf(cur, end - cur, "%ps / %ps",
181 cmp < 0 ? r->access[0].fn : r->access[1].fn,
182 cmp < 0 ? r->access[1].fn : r->access[0].fn);
184 scnprintf(cur, end - cur, "%pS", r->access[0].fn);
185 /* The exact offset won't match, remove it. */
186 cur = strchr(expect[0], '+');
193 end = &expect[1][sizeof(expect[1]) - 1];
194 if (!r->access[1].fn)
195 cur += scnprintf(cur, end - cur, "race at unknown origin, with ");
198 for (i = 0; i < 2; ++i) {
199 const int ty = r->access[i].type;
200 const char *const access_type =
201 (ty & KCSAN_ACCESS_ASSERT) ?
202 ((ty & KCSAN_ACCESS_WRITE) ?
203 "assert no accesses" :
204 "assert no writes") :
205 ((ty & KCSAN_ACCESS_WRITE) ?
206 ((ty & KCSAN_ACCESS_COMPOUND) ?
210 const char *const access_type_aux =
211 (ty & KCSAN_ACCESS_ATOMIC) ?
213 ((ty & KCSAN_ACCESS_SCOPED) ? " (scoped)" : "");
218 end = &expect[2][sizeof(expect[2]) - 1];
220 if (!r->access[1].fn) {
221 /* Dummy string if no second access is available. */
222 strcpy(cur, "<none>");
227 cur += scnprintf(cur, end - cur, "%s%s to ", access_type,
230 if (r->access[i].addr) /* Address is optional. */
231 cur += scnprintf(cur, end - cur, "0x%px of %zu bytes",
232 r->access[i].addr, r->access[i].size);
235 spin_lock_irqsave(&observed.lock, flags);
236 if (!report_available())
237 goto out; /* A new report is being captured. */
239 /* Finally match expected output to what we actually observed. */
240 ret = strstr(observed.lines[0], expect[0]) &&
241 /* Access info may appear in any order. */
242 ((strstr(observed.lines[1], expect[1]) &&
243 strstr(observed.lines[2], expect[2])) ||
244 (strstr(observed.lines[1], expect[2]) &&
245 strstr(observed.lines[2], expect[1])));
247 spin_unlock_irqrestore(&observed.lock, flags);
252 /* ===== Test kernels ===== */
254 static long test_sink;
255 static long test_var;
256 /* @test_array should be large enough to fall into multiple watchpoint slots. */
257 static long test_array[3 * PAGE_SIZE / sizeof(long)];
261 static DEFINE_SEQLOCK(test_seqlock);
264 * Helper to avoid compiler optimizing out reads, and to generate source values
268 static noinline void sink_value(long v) { WRITE_ONCE(test_sink, v); }
270 static noinline void test_kernel_read(void) { sink_value(test_var); }
272 static noinline void test_kernel_write(void)
274 test_var = READ_ONCE_NOCHECK(test_sink) + 1;
277 static noinline void test_kernel_write_nochange(void) { test_var = 42; }
279 /* Suffixed by value-change exception filter. */
280 static noinline void test_kernel_write_nochange_rcu(void) { test_var = 42; }
282 static noinline void test_kernel_read_atomic(void)
284 sink_value(READ_ONCE(test_var));
287 static noinline void test_kernel_write_atomic(void)
289 WRITE_ONCE(test_var, READ_ONCE_NOCHECK(test_sink) + 1);
292 static noinline void test_kernel_atomic_rmw(void)
294 /* Use builtin, so we can set up the "bad" atomic/non-atomic scenario. */
295 __atomic_fetch_add(&test_var, 1, __ATOMIC_RELAXED);
299 static noinline void test_kernel_write_uninstrumented(void) { test_var++; }
301 static noinline void test_kernel_data_race(void) { data_race(test_var++); }
303 static noinline void test_kernel_assert_writer(void)
305 ASSERT_EXCLUSIVE_WRITER(test_var);
308 static noinline void test_kernel_assert_access(void)
310 ASSERT_EXCLUSIVE_ACCESS(test_var);
313 #define TEST_CHANGE_BITS 0xff00ff00
315 static noinline void test_kernel_change_bits(void)
317 if (IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS)) {
319 * Avoid race of unknown origin for this test, just pretend they
322 kcsan_nestable_atomic_begin();
323 test_var ^= TEST_CHANGE_BITS;
324 kcsan_nestable_atomic_end();
326 WRITE_ONCE(test_var, READ_ONCE(test_var) ^ TEST_CHANGE_BITS);
329 static noinline void test_kernel_assert_bits_change(void)
331 ASSERT_EXCLUSIVE_BITS(test_var, TEST_CHANGE_BITS);
334 static noinline void test_kernel_assert_bits_nochange(void)
336 ASSERT_EXCLUSIVE_BITS(test_var, ~TEST_CHANGE_BITS);
339 /* To check that scoped assertions do trigger anywhere in scope. */
340 static noinline void test_enter_scope(void)
344 /* Unrelated accesses to scoped assert. */
345 READ_ONCE(test_sink);
346 kcsan_check_read(&x, sizeof(x));
349 static noinline void test_kernel_assert_writer_scoped(void)
351 ASSERT_EXCLUSIVE_WRITER_SCOPED(test_var);
355 static noinline void test_kernel_assert_access_scoped(void)
357 ASSERT_EXCLUSIVE_ACCESS_SCOPED(test_var);
361 static noinline void test_kernel_rmw_array(void)
365 for (i = 0; i < ARRAY_SIZE(test_array); ++i)
369 static noinline void test_kernel_write_struct(void)
371 kcsan_check_write(&test_struct, sizeof(test_struct));
372 kcsan_disable_current();
373 test_struct.val[3]++; /* induce value change */
374 kcsan_enable_current();
377 static noinline void test_kernel_write_struct_part(void)
379 test_struct.val[3] = 42;
382 static noinline void test_kernel_read_struct_zero_size(void)
384 kcsan_check_read(&test_struct.val[3], 0);
387 static noinline void test_kernel_jiffies_reader(void)
389 sink_value((long)jiffies);
392 static noinline void test_kernel_seqlock_reader(void)
397 seq = read_seqbegin(&test_seqlock);
398 sink_value(test_var);
399 } while (read_seqretry(&test_seqlock, seq));
402 static noinline void test_kernel_seqlock_writer(void)
406 write_seqlock_irqsave(&test_seqlock, flags);
408 write_sequnlock_irqrestore(&test_seqlock, flags);
411 static noinline void test_kernel_atomic_builtins(void)
414 * Generate concurrent accesses, expecting no reports, ensuring KCSAN
415 * treats builtin atomics as actually atomic.
417 __atomic_load_n(&test_var, __ATOMIC_RELAXED);
420 /* ===== Test cases ===== */
422 /* Simple test with normal data race. */
424 static void test_basic(struct kunit *test)
426 const struct expect_report expect = {
428 { test_kernel_write, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
429 { test_kernel_read, &test_var, sizeof(test_var), 0 },
432 static const struct expect_report never = {
434 { test_kernel_read, &test_var, sizeof(test_var), 0 },
435 { test_kernel_read, &test_var, sizeof(test_var), 0 },
438 bool match_expect = false;
439 bool match_never = false;
441 begin_test_checks(test_kernel_write, test_kernel_read);
443 match_expect |= report_matches(&expect);
444 match_never = report_matches(&never);
445 } while (!end_test_checks(match_never));
446 KUNIT_EXPECT_TRUE(test, match_expect);
447 KUNIT_EXPECT_FALSE(test, match_never);
451 * Stress KCSAN with lots of concurrent races on different addresses until
455 static void test_concurrent_races(struct kunit *test)
457 const struct expect_report expect = {
459 /* NULL will match any address. */
460 { test_kernel_rmw_array, NULL, 0, __KCSAN_ACCESS_RW(KCSAN_ACCESS_WRITE) },
461 { test_kernel_rmw_array, NULL, 0, __KCSAN_ACCESS_RW(0) },
464 static const struct expect_report never = {
466 { test_kernel_rmw_array, NULL, 0, 0 },
467 { test_kernel_rmw_array, NULL, 0, 0 },
470 bool match_expect = false;
471 bool match_never = false;
473 begin_test_checks(test_kernel_rmw_array, test_kernel_rmw_array);
475 match_expect |= report_matches(&expect);
476 match_never |= report_matches(&never);
477 } while (!end_test_checks(false));
478 KUNIT_EXPECT_TRUE(test, match_expect); /* Sanity check matches exist. */
479 KUNIT_EXPECT_FALSE(test, match_never);
482 /* Test the KCSAN_REPORT_VALUE_CHANGE_ONLY option. */
484 static void test_novalue_change(struct kunit *test)
486 const struct expect_report expect = {
488 { test_kernel_write_nochange, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
489 { test_kernel_read, &test_var, sizeof(test_var), 0 },
492 bool match_expect = false;
494 begin_test_checks(test_kernel_write_nochange, test_kernel_read);
496 match_expect = report_matches(&expect);
497 } while (!end_test_checks(match_expect));
498 if (IS_ENABLED(CONFIG_KCSAN_REPORT_VALUE_CHANGE_ONLY))
499 KUNIT_EXPECT_FALSE(test, match_expect);
501 KUNIT_EXPECT_TRUE(test, match_expect);
505 * Test that the rules where the KCSAN_REPORT_VALUE_CHANGE_ONLY option should
509 static void test_novalue_change_exception(struct kunit *test)
511 const struct expect_report expect = {
513 { test_kernel_write_nochange_rcu, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
514 { test_kernel_read, &test_var, sizeof(test_var), 0 },
517 bool match_expect = false;
519 begin_test_checks(test_kernel_write_nochange_rcu, test_kernel_read);
521 match_expect = report_matches(&expect);
522 } while (!end_test_checks(match_expect));
523 KUNIT_EXPECT_TRUE(test, match_expect);
526 /* Test that data races of unknown origin are reported. */
528 static void test_unknown_origin(struct kunit *test)
530 const struct expect_report expect = {
532 { test_kernel_read, &test_var, sizeof(test_var), 0 },
536 bool match_expect = false;
538 begin_test_checks(test_kernel_write_uninstrumented, test_kernel_read);
540 match_expect = report_matches(&expect);
541 } while (!end_test_checks(match_expect));
542 if (IS_ENABLED(CONFIG_KCSAN_REPORT_RACE_UNKNOWN_ORIGIN))
543 KUNIT_EXPECT_TRUE(test, match_expect);
545 KUNIT_EXPECT_FALSE(test, match_expect);
548 /* Test KCSAN_ASSUME_PLAIN_WRITES_ATOMIC if it is selected. */
550 static void test_write_write_assume_atomic(struct kunit *test)
552 const struct expect_report expect = {
554 { test_kernel_write, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
555 { test_kernel_write, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
558 bool match_expect = false;
560 begin_test_checks(test_kernel_write, test_kernel_write);
562 sink_value(READ_ONCE(test_var)); /* induce value-change */
563 match_expect = report_matches(&expect);
564 } while (!end_test_checks(match_expect));
565 if (IS_ENABLED(CONFIG_KCSAN_ASSUME_PLAIN_WRITES_ATOMIC))
566 KUNIT_EXPECT_FALSE(test, match_expect);
568 KUNIT_EXPECT_TRUE(test, match_expect);
572 * Test that data races with writes larger than word-size are always reported,
573 * even if KCSAN_ASSUME_PLAIN_WRITES_ATOMIC is selected.
576 static void test_write_write_struct(struct kunit *test)
578 const struct expect_report expect = {
580 { test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
581 { test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
584 bool match_expect = false;
586 begin_test_checks(test_kernel_write_struct, test_kernel_write_struct);
588 match_expect = report_matches(&expect);
589 } while (!end_test_checks(match_expect));
590 KUNIT_EXPECT_TRUE(test, match_expect);
594 * Test that data races where only one write is larger than word-size are always
595 * reported, even if KCSAN_ASSUME_PLAIN_WRITES_ATOMIC is selected.
598 static void test_write_write_struct_part(struct kunit *test)
600 const struct expect_report expect = {
602 { test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
603 { test_kernel_write_struct_part, &test_struct.val[3], sizeof(test_struct.val[3]), KCSAN_ACCESS_WRITE },
606 bool match_expect = false;
608 begin_test_checks(test_kernel_write_struct, test_kernel_write_struct_part);
610 match_expect = report_matches(&expect);
611 } while (!end_test_checks(match_expect));
612 KUNIT_EXPECT_TRUE(test, match_expect);
615 /* Test that races with atomic accesses never result in reports. */
617 static void test_read_atomic_write_atomic(struct kunit *test)
619 bool match_never = false;
621 begin_test_checks(test_kernel_read_atomic, test_kernel_write_atomic);
623 match_never = report_available();
624 } while (!end_test_checks(match_never));
625 KUNIT_EXPECT_FALSE(test, match_never);
628 /* Test that a race with an atomic and plain access result in reports. */
630 static void test_read_plain_atomic_write(struct kunit *test)
632 const struct expect_report expect = {
634 { test_kernel_read, &test_var, sizeof(test_var), 0 },
635 { test_kernel_write_atomic, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ATOMIC },
638 bool match_expect = false;
640 if (IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS))
643 begin_test_checks(test_kernel_read, test_kernel_write_atomic);
645 match_expect = report_matches(&expect);
646 } while (!end_test_checks(match_expect));
647 KUNIT_EXPECT_TRUE(test, match_expect);
650 /* Test that atomic RMWs generate correct report. */
652 static void test_read_plain_atomic_rmw(struct kunit *test)
654 const struct expect_report expect = {
656 { test_kernel_read, &test_var, sizeof(test_var), 0 },
657 { test_kernel_atomic_rmw, &test_var, sizeof(test_var),
658 KCSAN_ACCESS_COMPOUND | KCSAN_ACCESS_WRITE | KCSAN_ACCESS_ATOMIC },
661 bool match_expect = false;
663 if (IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS))
666 begin_test_checks(test_kernel_read, test_kernel_atomic_rmw);
668 match_expect = report_matches(&expect);
669 } while (!end_test_checks(match_expect));
670 KUNIT_EXPECT_TRUE(test, match_expect);
673 /* Zero-sized accesses should never cause data race reports. */
675 static void test_zero_size_access(struct kunit *test)
677 const struct expect_report expect = {
679 { test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
680 { test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
683 const struct expect_report never = {
685 { test_kernel_write_struct, &test_struct, sizeof(test_struct), KCSAN_ACCESS_WRITE },
686 { test_kernel_read_struct_zero_size, &test_struct.val[3], 0, 0 },
689 bool match_expect = false;
690 bool match_never = false;
692 begin_test_checks(test_kernel_write_struct, test_kernel_read_struct_zero_size);
694 match_expect |= report_matches(&expect);
695 match_never = report_matches(&never);
696 } while (!end_test_checks(match_never));
697 KUNIT_EXPECT_TRUE(test, match_expect); /* Sanity check. */
698 KUNIT_EXPECT_FALSE(test, match_never);
701 /* Test the data_race() macro. */
703 static void test_data_race(struct kunit *test)
705 bool match_never = false;
707 begin_test_checks(test_kernel_data_race, test_kernel_data_race);
709 match_never = report_available();
710 } while (!end_test_checks(match_never));
711 KUNIT_EXPECT_FALSE(test, match_never);
715 static void test_assert_exclusive_writer(struct kunit *test)
717 const struct expect_report expect = {
719 { test_kernel_assert_writer, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT },
720 { test_kernel_write_nochange, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
723 bool match_expect = false;
725 begin_test_checks(test_kernel_assert_writer, test_kernel_write_nochange);
727 match_expect = report_matches(&expect);
728 } while (!end_test_checks(match_expect));
729 KUNIT_EXPECT_TRUE(test, match_expect);
733 static void test_assert_exclusive_access(struct kunit *test)
735 const struct expect_report expect = {
737 { test_kernel_assert_access, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE },
738 { test_kernel_read, &test_var, sizeof(test_var), 0 },
741 bool match_expect = false;
743 begin_test_checks(test_kernel_assert_access, test_kernel_read);
745 match_expect = report_matches(&expect);
746 } while (!end_test_checks(match_expect));
747 KUNIT_EXPECT_TRUE(test, match_expect);
751 static void test_assert_exclusive_access_writer(struct kunit *test)
753 const struct expect_report expect_access_writer = {
755 { test_kernel_assert_access, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE },
756 { test_kernel_assert_writer, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT },
759 const struct expect_report expect_access_access = {
761 { test_kernel_assert_access, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE },
762 { test_kernel_assert_access, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE },
765 const struct expect_report never = {
767 { test_kernel_assert_writer, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT },
768 { test_kernel_assert_writer, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT },
771 bool match_expect_access_writer = false;
772 bool match_expect_access_access = false;
773 bool match_never = false;
775 begin_test_checks(test_kernel_assert_access, test_kernel_assert_writer);
777 match_expect_access_writer |= report_matches(&expect_access_writer);
778 match_expect_access_access |= report_matches(&expect_access_access);
779 match_never |= report_matches(&never);
780 } while (!end_test_checks(match_never));
781 KUNIT_EXPECT_TRUE(test, match_expect_access_writer);
782 KUNIT_EXPECT_TRUE(test, match_expect_access_access);
783 KUNIT_EXPECT_FALSE(test, match_never);
787 static void test_assert_exclusive_bits_change(struct kunit *test)
789 const struct expect_report expect = {
791 { test_kernel_assert_bits_change, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT },
792 { test_kernel_change_bits, &test_var, sizeof(test_var),
793 KCSAN_ACCESS_WRITE | (IS_ENABLED(CONFIG_KCSAN_IGNORE_ATOMICS) ? 0 : KCSAN_ACCESS_ATOMIC) },
796 bool match_expect = false;
798 begin_test_checks(test_kernel_assert_bits_change, test_kernel_change_bits);
800 match_expect = report_matches(&expect);
801 } while (!end_test_checks(match_expect));
802 KUNIT_EXPECT_TRUE(test, match_expect);
806 static void test_assert_exclusive_bits_nochange(struct kunit *test)
808 bool match_never = false;
810 begin_test_checks(test_kernel_assert_bits_nochange, test_kernel_change_bits);
812 match_never = report_available();
813 } while (!end_test_checks(match_never));
814 KUNIT_EXPECT_FALSE(test, match_never);
818 static void test_assert_exclusive_writer_scoped(struct kunit *test)
820 const struct expect_report expect_start = {
822 { test_kernel_assert_writer_scoped, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_SCOPED },
823 { test_kernel_write_nochange, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
826 const struct expect_report expect_anywhere = {
828 { test_enter_scope, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_SCOPED },
829 { test_kernel_write_nochange, &test_var, sizeof(test_var), KCSAN_ACCESS_WRITE },
832 bool match_expect_start = false;
833 bool match_expect_anywhere = false;
835 begin_test_checks(test_kernel_assert_writer_scoped, test_kernel_write_nochange);
837 match_expect_start |= report_matches(&expect_start);
838 match_expect_anywhere |= report_matches(&expect_anywhere);
839 } while (!end_test_checks(match_expect_start && match_expect_anywhere));
840 KUNIT_EXPECT_TRUE(test, match_expect_start);
841 KUNIT_EXPECT_TRUE(test, match_expect_anywhere);
845 static void test_assert_exclusive_access_scoped(struct kunit *test)
847 const struct expect_report expect_start1 = {
849 { test_kernel_assert_access_scoped, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE | KCSAN_ACCESS_SCOPED },
850 { test_kernel_read, &test_var, sizeof(test_var), 0 },
853 const struct expect_report expect_start2 = {
854 .access = { expect_start1.access[0], expect_start1.access[0] },
856 const struct expect_report expect_inscope = {
858 { test_enter_scope, &test_var, sizeof(test_var), KCSAN_ACCESS_ASSERT | KCSAN_ACCESS_WRITE | KCSAN_ACCESS_SCOPED },
859 { test_kernel_read, &test_var, sizeof(test_var), 0 },
862 bool match_expect_start = false;
863 bool match_expect_inscope = false;
865 begin_test_checks(test_kernel_assert_access_scoped, test_kernel_read);
866 end_time += msecs_to_jiffies(1000); /* This test requires a bit more time. */
868 match_expect_start |= report_matches(&expect_start1) || report_matches(&expect_start2);
869 match_expect_inscope |= report_matches(&expect_inscope);
870 } while (!end_test_checks(match_expect_start && match_expect_inscope));
871 KUNIT_EXPECT_TRUE(test, match_expect_start);
872 KUNIT_EXPECT_TRUE(test, match_expect_inscope);
876 * jiffies is special (declared to be volatile) and its accesses are typically
877 * not marked; this test ensures that the compiler nor KCSAN gets confused about
878 * jiffies's declaration on different architectures.
881 static void test_jiffies_noreport(struct kunit *test)
883 bool match_never = false;
885 begin_test_checks(test_kernel_jiffies_reader, test_kernel_jiffies_reader);
887 match_never = report_available();
888 } while (!end_test_checks(match_never));
889 KUNIT_EXPECT_FALSE(test, match_never);
892 /* Test that racing accesses in seqlock critical sections are not reported. */
894 static void test_seqlock_noreport(struct kunit *test)
896 bool match_never = false;
898 begin_test_checks(test_kernel_seqlock_reader, test_kernel_seqlock_writer);
900 match_never = report_available();
901 } while (!end_test_checks(match_never));
902 KUNIT_EXPECT_FALSE(test, match_never);
906 * Test atomic builtins work and required instrumentation functions exist. We
907 * also test that KCSAN understands they're atomic by racing with them via
908 * test_kernel_atomic_builtins(), and expect no reports.
910 * The atomic builtins _SHOULD NOT_ be used in normal kernel code!
912 static void test_atomic_builtins(struct kunit *test)
914 bool match_never = false;
916 begin_test_checks(test_kernel_atomic_builtins, test_kernel_atomic_builtins);
920 kcsan_enable_current();
922 __atomic_store_n(&test_var, 42L, __ATOMIC_RELAXED);
923 KUNIT_EXPECT_EQ(test, 42L, __atomic_load_n(&test_var, __ATOMIC_RELAXED));
925 KUNIT_EXPECT_EQ(test, 42L, __atomic_exchange_n(&test_var, 20, __ATOMIC_RELAXED));
926 KUNIT_EXPECT_EQ(test, 20L, test_var);
929 KUNIT_EXPECT_TRUE(test, __atomic_compare_exchange_n(&test_var, &tmp, 30L,
932 KUNIT_EXPECT_EQ(test, tmp, 20L);
933 KUNIT_EXPECT_EQ(test, test_var, 30L);
934 KUNIT_EXPECT_FALSE(test, __atomic_compare_exchange_n(&test_var, &tmp, 40L,
937 KUNIT_EXPECT_EQ(test, tmp, 30L);
938 KUNIT_EXPECT_EQ(test, test_var, 30L);
940 KUNIT_EXPECT_EQ(test, 30L, __atomic_fetch_add(&test_var, 1, __ATOMIC_RELAXED));
941 KUNIT_EXPECT_EQ(test, 31L, __atomic_fetch_sub(&test_var, 1, __ATOMIC_RELAXED));
942 KUNIT_EXPECT_EQ(test, 30L, __atomic_fetch_and(&test_var, 0xf, __ATOMIC_RELAXED));
943 KUNIT_EXPECT_EQ(test, 14L, __atomic_fetch_xor(&test_var, 0xf, __ATOMIC_RELAXED));
944 KUNIT_EXPECT_EQ(test, 1L, __atomic_fetch_or(&test_var, 0xf0, __ATOMIC_RELAXED));
945 KUNIT_EXPECT_EQ(test, 241L, __atomic_fetch_nand(&test_var, 0xf, __ATOMIC_RELAXED));
946 KUNIT_EXPECT_EQ(test, -2L, test_var);
948 __atomic_thread_fence(__ATOMIC_SEQ_CST);
949 __atomic_signal_fence(__ATOMIC_SEQ_CST);
951 kcsan_disable_current();
953 match_never = report_available();
954 } while (!end_test_checks(match_never));
955 KUNIT_EXPECT_FALSE(test, match_never);
959 * Each test case is run with different numbers of threads. Until KUnit supports
960 * passing arguments for each test case, we encode #threads in the test case
961 * name (read by get_num_threads()). [The '-' was chosen as a stylistic
962 * preference to separate test name and #threads.]
964 * The thread counts are chosen to cover potentially interesting boundaries and
965 * corner cases (range 2-5), and then stress the system with larger counts.
967 #define KCSAN_KUNIT_CASE(test_name) \
968 { .run_case = test_name, .name = #test_name "-02" }, \
969 { .run_case = test_name, .name = #test_name "-03" }, \
970 { .run_case = test_name, .name = #test_name "-04" }, \
971 { .run_case = test_name, .name = #test_name "-05" }, \
972 { .run_case = test_name, .name = #test_name "-08" }, \
973 { .run_case = test_name, .name = #test_name "-16" }
975 static struct kunit_case kcsan_test_cases[] = {
976 KCSAN_KUNIT_CASE(test_basic),
977 KCSAN_KUNIT_CASE(test_concurrent_races),
978 KCSAN_KUNIT_CASE(test_novalue_change),
979 KCSAN_KUNIT_CASE(test_novalue_change_exception),
980 KCSAN_KUNIT_CASE(test_unknown_origin),
981 KCSAN_KUNIT_CASE(test_write_write_assume_atomic),
982 KCSAN_KUNIT_CASE(test_write_write_struct),
983 KCSAN_KUNIT_CASE(test_write_write_struct_part),
984 KCSAN_KUNIT_CASE(test_read_atomic_write_atomic),
985 KCSAN_KUNIT_CASE(test_read_plain_atomic_write),
986 KCSAN_KUNIT_CASE(test_read_plain_atomic_rmw),
987 KCSAN_KUNIT_CASE(test_zero_size_access),
988 KCSAN_KUNIT_CASE(test_data_race),
989 KCSAN_KUNIT_CASE(test_assert_exclusive_writer),
990 KCSAN_KUNIT_CASE(test_assert_exclusive_access),
991 KCSAN_KUNIT_CASE(test_assert_exclusive_access_writer),
992 KCSAN_KUNIT_CASE(test_assert_exclusive_bits_change),
993 KCSAN_KUNIT_CASE(test_assert_exclusive_bits_nochange),
994 KCSAN_KUNIT_CASE(test_assert_exclusive_writer_scoped),
995 KCSAN_KUNIT_CASE(test_assert_exclusive_access_scoped),
996 KCSAN_KUNIT_CASE(test_jiffies_noreport),
997 KCSAN_KUNIT_CASE(test_seqlock_noreport),
998 KCSAN_KUNIT_CASE(test_atomic_builtins),
1002 /* ===== End test cases ===== */
1004 /* Get number of threads encoded in test name. */
1005 static bool __no_kcsan
1006 get_num_threads(const char *test, int *nthreads)
1008 int len = strlen(test);
1010 if (WARN_ON(len < 3))
1013 *nthreads = test[len - 1] - '0';
1014 *nthreads += (test[len - 2] - '0') * 10;
1016 if (WARN_ON(*nthreads < 0))
1022 /* Concurrent accesses from interrupts. */
1024 static void access_thread_timer(struct timer_list *timer)
1026 static atomic_t cnt = ATOMIC_INIT(0);
1030 idx = (unsigned int)atomic_inc_return(&cnt) % ARRAY_SIZE(access_kernels);
1031 /* Acquire potential initialization. */
1032 func = smp_load_acquire(&access_kernels[idx]);
1037 /* The main loop for each thread. */
1039 static int access_thread(void *arg)
1041 struct timer_list timer;
1042 unsigned int cnt = 0;
1046 timer_setup_on_stack(&timer, access_thread_timer, 0);
1050 if (!timer_pending(&timer))
1051 mod_timer(&timer, jiffies + 1);
1053 /* Iterate through all kernels. */
1054 idx = cnt++ % ARRAY_SIZE(access_kernels);
1055 /* Acquire potential initialization. */
1056 func = smp_load_acquire(&access_kernels[idx]);
1060 } while (!torture_must_stop());
1061 del_timer_sync(&timer);
1062 destroy_timer_on_stack(&timer);
1064 torture_kthread_stopping("access_thread");
1069 static int test_init(struct kunit *test)
1071 unsigned long flags;
1075 spin_lock_irqsave(&observed.lock, flags);
1076 for (i = 0; i < ARRAY_SIZE(observed.lines); ++i)
1077 observed.lines[i][0] = '\0';
1078 observed.nlines = 0;
1079 spin_unlock_irqrestore(&observed.lock, flags);
1081 if (!torture_init_begin((char *)test->name, 1))
1084 if (!get_num_threads(test->name, &nthreads))
1087 if (WARN_ON(threads))
1090 for (i = 0; i < ARRAY_SIZE(access_kernels); ++i) {
1091 if (WARN_ON(access_kernels[i]))
1095 if (!IS_ENABLED(CONFIG_PREEMPT) || !IS_ENABLED(CONFIG_KCSAN_INTERRUPT_WATCHER)) {
1097 * Without any preemption, keep 2 CPUs free for other tasks, one
1098 * of which is the main test case function checking for
1099 * completion or failure.
1101 const int min_unused_cpus = IS_ENABLED(CONFIG_PREEMPT_NONE) ? 2 : 0;
1102 const int min_required_cpus = 2 + min_unused_cpus;
1104 if (num_online_cpus() < min_required_cpus) {
1105 pr_err("%s: too few online CPUs (%u < %d) for test",
1106 test->name, num_online_cpus(), min_required_cpus);
1108 } else if (nthreads > num_online_cpus() - min_unused_cpus) {
1109 nthreads = num_online_cpus() - min_unused_cpus;
1110 pr_warn("%s: limiting number of threads to %d\n",
1111 test->name, nthreads);
1116 threads = kcalloc(nthreads + 1, sizeof(struct task_struct *),
1118 if (WARN_ON(!threads))
1121 threads[nthreads] = NULL;
1122 for (i = 0; i < nthreads; ++i) {
1123 if (torture_create_kthread(access_thread, NULL,
1141 static void test_exit(struct kunit *test)
1143 struct task_struct **stop_thread;
1146 if (torture_cleanup_begin())
1149 for (i = 0; i < ARRAY_SIZE(access_kernels); ++i)
1150 WRITE_ONCE(access_kernels[i], NULL);
1153 for (stop_thread = threads; *stop_thread; stop_thread++)
1154 torture_stop_kthread(reader_thread, *stop_thread);
1160 torture_cleanup_end();
1163 static struct kunit_suite kcsan_test_suite = {
1164 .name = "kcsan-test",
1165 .test_cases = kcsan_test_cases,
1169 static struct kunit_suite *kcsan_test_suites[] = { &kcsan_test_suite, NULL };
1172 static void register_tracepoints(struct tracepoint *tp, void *ignore)
1174 check_trace_callback_type_console(probe_console);
1175 if (!strcmp(tp->name, "console"))
1176 WARN_ON(tracepoint_probe_register(tp, probe_console, NULL));
1180 static void unregister_tracepoints(struct tracepoint *tp, void *ignore)
1182 if (!strcmp(tp->name, "console"))
1183 tracepoint_probe_unregister(tp, probe_console, NULL);
1187 * We only want to do tracepoints setup and teardown once, therefore we have to
1188 * customize the init and exit functions and cannot rely on kunit_test_suite().
1190 static int __init kcsan_test_init(void)
1193 * Because we want to be able to build the test as a module, we need to
1194 * iterate through all known tracepoints, since the static registration
1197 for_each_kernel_tracepoint(register_tracepoints, NULL);
1198 return __kunit_test_suites_init(kcsan_test_suites);
1201 static void kcsan_test_exit(void)
1203 __kunit_test_suites_exit(kcsan_test_suites);
1204 for_each_kernel_tracepoint(unregister_tracepoints, NULL);
1205 tracepoint_synchronize_unregister();
1208 late_initcall(kcsan_test_init);
1209 module_exit(kcsan_test_exit);
1211 MODULE_LICENSE("GPL v2");
1212 MODULE_AUTHOR("Marco Elver <elver@google.com>");