Skip to contentSkip to conversation

kbuild: rust: enable KCSAN support

PATCH Superseded Marco Elver 5 participants 16 messages Oct 12 – Oct 13 1 message not in the archive

Subsystems (6)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Marco Elver

author maintainer
#0 lore raw

PATCH 1/2 kbuild: rust: enable KCSAN support

Rust supports ThreadSanitizer instrumentation via LLVM, which is what KCSAN relies on; however, Rust code is not currently instrumented.

Pass -Zsanitizer=thread and the same TSan backend options used for C code to rustc. Wire up KCSAN_SANITIZE in scripts/Makefile.lib for parity with C (though rustc currently rejects linking crates with mismatched instrumentation).

rustc only accepts -Zsanitizer=thread for targets that declare support for it. Of the targets used by the kernel, this is only possible for the generated x86_64 target specification, so restrict instrumentation of Rust code to x86_64 for now via HAVE_KCSAN_RUSTC. On other architectures Rust code remains uninstrumented as before.

All TSan options used are supported by the LLVM versions of the minimum supported rustc, so no rustc-option checks are needed (they would also fail, because x86_64-unknown-none used for option checks does not support -Zsanitizer=thread).

With this enabled we can detect data races in kernel Rust code and between Rust and C code.

---
 Documentation/dev-tools/kcsan.rst |  7 +++++++
 lib/Kconfig.kcsan                 |  7 +++++++
 scripts/Makefile.kcsan            | 13 +++++++++++++
 scripts/Makefile.lib              |  3 +++
 scripts/generate_rust_target.rs   |  2 +-
 5 files changed, 31 insertions(+), 1 deletion(-)
Documentation/dev-tools/kcsan.rst +7 -0
index 8575178aa87f..3bb8754f844b 100644
@@ -14,6 +14,9 @@ Usage
 KCSAN is supported by both GCC and Clang. With GCC we require version 11 or
 later, and with Clang also require version 11 or later.
 
+Rust code is instrumented as well on architectures whose Rust target supports
+it (currently only x86_64; see ``CONFIG_HAVE_KCSAN_RUSTC``).
+
 To enable KCSAN configure the kernel with::
 
     CONFIG_KCSAN = y
@@ -121,6 +124,10 @@ the below options are available:
 
     KCSAN_SANITIZE := n
 
+  Note that ``rustc`` rejects linking crates built with and without KCSAN
+  instrumentation, so ``KCSAN_SANITIZE`` and ``KCSAN_SANITIZE_<target>.o``
+  cannot currently be used for Rust code.
+
 .. _"Marking Shared-Memory Accesses" in the LKMM: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/memory-model/Documentation/access-marking.txt
 
 Furthermore, it is possible to tell KCSAN to show or hide entire classes of
lib/Kconfig.kcsan +7 -0
index 4ce4b0c0109c..f0096e1c8b61 100644
@@ -10,6 +10,13 @@ config HAVE_KCSAN_COMPILER
 	  For the list of compilers that support KCSAN, please see
 	  <file:Documentation/dev-tools/kcsan.rst>.
 
+config HAVE_KCSAN_RUSTC
+	def_bool RUST && X86_64
+	help
+	  rustc only accepts -Zsanitizer=thread for targets that declare
+	  support for it; of the kernel's Rust targets, only x86_64 does.
+	  Elsewhere, Rust code is not instrumented.
+
 menuconfig KCSAN
 	bool "KCSAN: dynamic data race detector"
 	depends on HAVE_ARCH_KCSAN && HAVE_KCSAN_COMPILER
scripts/Makefile.kcsan +13 -0
index 19f693b68a96..01af6fd71006 100644
@@ -24,3 +24,16 @@ kcsan-cflags += $(call cc-option,$(call cc-param,tsan-instrument-func-entry-exit
 endif
 
 export CFLAGS_KCSAN := $(kcsan-cflags)
+
+ifdef CONFIG_HAVE_KCSAN_RUSTC
+# The minimum supported rustc's LLVM supports all of these options.
+rustc-param = -Cllvm-args=-$(1)
+kcsan-rustflags := -Zsanitizer=thread \
+	$(call rustc-param,tsan-compound-read-before-write=1) \
+	$(call rustc-param,tsan-distinguish-volatile=1)
+ifndef CONFIG_KCSAN_WEAK_MEMORY
+kcsan-rustflags += $(call rustc-param,tsan-instrument-func-entry-exit=0)
+endif
+endif
+
+export RUSTFLAGS_KCSAN := $(kcsan-rustflags)
scripts/Makefile.lib +3 -0
index 0a4fdd8bd975..78f1c23e54be 100644
@@ -98,6 +98,9 @@ ifeq ($(CONFIG_KCSAN),y)
 _c_flags += $(if $(patsubst n%,, \
 	$(KCSAN_SANITIZE_$(target-stem).o)$(KCSAN_SANITIZE)$(is-kernel-object)), \
 	$(CFLAGS_KCSAN))
+_rust_flags += $(if $(patsubst n%,, \
+	$(KCSAN_SANITIZE_$(target-stem).o)$(KCSAN_SANITIZE)$(is-kernel-object)), \
+	$(RUSTFLAGS_KCSAN))
 # Some uninstrumented files provide implied barriers required to avoid false
 # positives: set KCSAN_INSTRUMENT_BARRIERS for barrier instrumentation only.
 _c_flags += $(if $(patsubst n%,, \
scripts/generate_rust_target.rs +1 -1
index 7687b0dd5474..4b02bffa6b46 100644
@@ -231,7 +231,7 @@ fn main() {
         }
         ts.push("features", features);
         ts.push("llvm-target", "x86_64-linux-gnu");
-        ts.push("supported-sanitizers", ["kcfi", "kernel-address"]);
+        ts.push("supported-sanitizers", ["kcfi", "kernel-address", "thread"]);
         if cfg.rustc_version_atleast(1, 91, 0) {
             ts.push("target-pointer-width", 64);
         } else {
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
author maintainer
#1 lore raw

PATCH 2/2 rust: kcsan: add KUnit test for data race detection

Add a minimal KUnit test that checks that KCSAN detects data races in Rust code: two threads concurrently increment a shared counter without synchronization, and a probe on the console tracepoint waits for the KCSAN report (similar to kcsan_test.c):

| BUG: KCSAN: data-race in _RNvNtNtCskctMpSfuwL9_6kernel10kcsan_test5tests8racy_inc / _RNvNtNtCskctMpSfuwL9_6kernel10kcsan_test5tests8racy_inc
|
| read-write to 0xffffffffb751ae28 of 8 bytes by task 116 on cpu 5:
|  _RNvNtNtCskctMpSfuwL9_6kernel10kcsan_test5tests8racy_inc+0x1c/0x30
|  _RNvNtNtCskctMpSfuwL9_6kernel10kcsan_test5tests28kunit_rust_wrapper_data_race+0x28c/0x850
|  kunit_try_run_case+0xdf/0x2a0
|  kunit_generic_run_threadfn_adapter+0x48/0x80
|  kthread+0x234/0x280
|  ret_from_fork+0xf8/0x280
|  ret_from_fork_asm+0x1a/0x30
|
| read-write to 0xffffffffb751ae28 of 8 bytes by task 12 on cpu 3:
|  _RNvNtNtCskctMpSfuwL9_6kernel10kcsan_test5tests8racy_inc+0x1c/0x30
|  _RNvXsb_NtCskctMpSfuwL9_6kernel9workqueueINtNtCs1G77UTwpz6o_4core3pin3PinINtNtNtB7_5alloc4kbox3BoxINtB5_11ClosureWorkNCNvNtNtB7_10kcsan_test5tests9data_races_0ENtNtB1d_9allocator7KmallocEEINtB5_15WorkItemPointerKy0_E3runB7_+0x55/0x120
|  process_scheduled_works+0x4cd/0x970
|  worker_thread+0x4de/0x6e0
|  kthread+0x234/0x280
|  ret_from_fork+0xf8/0x280
|  ret_from_fork_asm+0x1a/0x30
|
| value changed: 0x000000000000022b -> 0x00000000000005a2
| [...]

The test is intentionally kept minimal; comprehensive tests of KCSAN's runtime behaviour are in kernel/kcsan/kcsan_test.c.

Assisted-by Antigravity
---
 MAINTAINERS                     |   1 +
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/Kconfig.test        |  11 +++
 rust/kernel/kcsan_test.rs       | 120 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   2 +
 5 files changed, 135 insertions(+)
 create mode 100644 rust/kernel/kcsan_test.rs
MAINTAINERS +1 -0
index cc3cae2e378b..3fbbfbb31f5d 100644
@@ -14089,6 +14089,7 @@ F:	Documentation/dev-tools/kcsan.rst
 F:	include/linux/kcsan*.h
 F:	kernel/kcsan/
 F:	lib/Kconfig.kcsan
+F:	rust/kernel/kcsan_test.rs
 F:	scripts/Makefile.kcsan
 
 KDUMP
rust/bindings/bindings_helper.h +1 -0
index 4b31aa7f432f..b06d5142d6e1 100644
@@ -97,6 +97,7 @@
 #include <linux/xarray.h>
 #include <net/genetlink.h>
 #include <net/netlink.h>
+#include <trace/events/printk.h>
 #include <trace/events/rust_sample.h>
 
 /*
rust/kernel/Kconfig.test +11 -0
index e6a5c7a795f0..caf98a23de76 100644
@@ -83,4 +83,15 @@ config RUST_BITFIELD_KUNIT_TEST
 
 	  If unsure, say N.
 
+config RUST_KCSAN_KUNIT_TEST
+	bool "KUnit test for KCSAN instrumentation of Rust code" if !KUNIT_ALL_TESTS
+	depends on KCSAN && HAVE_KCSAN_RUSTC && TRACEPOINTS
+	default KUNIT_ALL_TESTS
+	help
+	  This option enables a KUnit test checking that KCSAN detects data
+	  races in Rust code. The test needs at least 2 CPUs to reliably
+	  observe a data race.
+
+	  If unsure, say N.
+
 endif
rust/kernel/kcsan_test.rs new file +120 -0

120 lines not on this page · raw message

rust/kernel/lib.rs +2 -0
index 4d5c96ddc49c..009efda9e7a4 100644
@@ -94,6 +94,8 @@
 pub mod iov;
 pub mod irq;
 pub mod jump_label;
+#[cfg(CONFIG_RUST_KCSAN_KUNIT_TEST)]
+mod kcsan_test;
 #[cfg(CONFIG_KUNIT)]
 pub mod kunit;
 pub mod list;
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
author maintainer
#3 lore raw

Re: [PATCH 2/2] rust: kcsan: add KUnit test for data race detection

In reply to a message not in the archive
Quoted 38 lines · On Mon, 12 Oct 2026 at 15:53, <[email protected]> wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] kcsan: tight spin loops cause soft lockups and test failure on UP --

commit 8ac72d90aef2333ef5245e04889d3d20386d5d6c
Author: Marco Elver <[email protected]>

rust: kcsan: add KUnit test for data race detection

Add a minimal KUnit test that checks that KCSAN detects data races in Rust code: two threads concurrently increment a shared counter without synchronization, and a probe on the console tracepoint waits for the KCSAN report.

Quoted 5 lines
rust/kernel/kcsan_test.rs new file +0 -0
new file mode 100644
index 0000000000000..5ddc9090cd6ef

[ ... ]

rust/kernel/kcsan_test.rs line 111

Quoted 12 lines
rust/kernel/kcsan_test.rs new file +12 -0
+        let worker = ctx.clone();
+        workqueue::system_unbound().try_spawn(GFP_KERNEL, move || {
+            while !worker.stop.load(Relaxed) {
+                racy_inc();
+            }
+            worker.done.complete_all();
+        })?;
+
+        let start = Instant::<Monotonic>::now();
+        while !OBSERVED.load(Relaxed) && start.elapsed() < Delta::from_secs(10) {
+            racy_inc();
+        }

[Severity: Medium]
Will these tight loops monopolize the CPU for up to 10 seconds on kernels configured with CONFIG_PREEMPT_NONE=y?

Quoted 6 lines

Neither the worker thread's loop nor the main thread's loop invokes cond_resched(), cpu_relax(), or any other CPU yielding mechanism. This could trigger soft lockup panics and RCU stall warnings.

Furthermore, on single-CPU systems, could the main thread completely starve the worker thread and prevent the data race from ever occurring?

If CONFIG_KCSAN_INTERRUPT_WATCHER=n. But if CONFIG_KCSAN_STRICT=y that's not a problem. It's the same as with the C kunit test, and I'd rather be able to run the test and get a test failure because the system was misconfigured, than no indication that something is wrong.

Quoted 4 lines

The Kconfig notes that 2 CPUs are required to reliably observe a data race, but there does not seem to be a runtime check (such as verifying if online CPUs are >= 2) to skip the test on uniprocessor systems, which would cause the test to unconditionally time out and fail.

The race is expected to happen very quickly, unless something is wrong with the instrumentation. So in the common case, there's no risk of soft lockup or stall warning.

Acked-by on v1 1/2
#12 lore raw
In reply to Marco Elver

Documentation/dev-tools/kcsan.rst Usage · line 18

Quoted 3 lines · Marco Elver
Documentation/dev-tools/kcsan.rst +2 -0
+Rust code is instrumented as well on architectures whose Rust target supports
+it (currently only x86_64; see ``CONFIG_HAVE_KCSAN_RUSTC``).

Maybe we can omit the x86_64 bit, to avoid maintaining the list in two places, although it is convenient to know in the docs (but risks getting out of date, of course).

Documentation/dev-tools/kcsan.rst the below options are available: · line 129

Quoted 3 lines
Documentation/dev-tools/kcsan.rst +3 -0
+  Note that ``rustc`` rejects linking crates built with and without KCSAN
+  instrumentation, so ``KCSAN_SANITIZE`` and ``KCSAN_SANITIZE_<target>.o``
+  cannot currently be used for Rust code.

Would -Cunsafe-allow-abi-mismatch=sanitizer work? Not a blocker for the patch (and in fact I don't know if we would like to actually support it even if it works), but perhaps in the future we can relax it using that.

(If it doesn't work for some reason, and we want it, then we can ask upstream for an "escape hatch" as we usually do, since things like this should normally have one...)

Quoted 1 line

+# The minimum supported rustc's LLVM supports all of these options.

Just to double-check: does this refer to the LLVM version of the upstream rustc binary (LLVM 19.1.7) or the actual minimum they support in that minimum rustc version (LLVM 18 major)?

I think all the options exist for a long time, so it doesn't matter, but just to confirm...

In any case, this sounds all reasonable:

Thanks!

Cheers,
Miguel

author maintainer
#13 lore raw
Quoted 9 lines · Miguel Ojeda

Documentation/dev-tools/kcsan.rst Usage · line 18

Quoted 3 lines · Marco Elver
Documentation/dev-tools/kcsan.rst +2 -0
+Rust code is instrumented as well on architectures whose Rust target supports
+it (currently only x86_64; see ``CONFIG_HAVE_KCSAN_RUSTC``).

Maybe we can omit the x86_64 bit, to avoid maintaining the list in two places, although it is convenient to know in the docs (but risks getting out of date, of course).

I think any future patch that enables more architectures, can also update the docs. We have historically maintained the set of supported compilers + architectures (if that set was still small) in the sanitizer docs. Once that set grows large enough, we can omit.

Quoted 8 lines

Documentation/dev-tools/kcsan.rst the below options are available: · line 129

Quoted 3 lines
Documentation/dev-tools/kcsan.rst +3 -0
+  Note that ``rustc`` rejects linking crates built with and without KCSAN
+  instrumentation, so ``KCSAN_SANITIZE`` and ``KCSAN_SANITIZE_<target>.o``
+  cannot currently be used for Rust code.

Would -Cunsafe-allow-abi-mismatch=sanitizer work? Not a blocker for the patch (and in fact I don't know if we would like to actually support it even if it works), but perhaps in the future we can relax it using that.

If rustc's sanitizer instrumentation is similar to clang's, and rustc doesn't introduce other ABI divergence due to sanitizers, then it should work. Same with KASAN + Rust, so this would need to be a general Rust + sanitizers decision.

The only exception is KMSAN (which I think is not yet enabled for Rust), which does affect ABI.

Quoted 4 lines

(If it doesn't work for some reason, and we want it, then we can ask upstream for an "escape hatch" as we usually do, since things like this should normally have one...)

Quoted 8 lines
Quoted 1 line

+# The minimum supported rustc's LLVM supports all of these options.

Just to double-check: does this refer to the LLVM version of the upstream rustc binary (LLVM 19.1.7) or the actual minimum they support in that minimum rustc version (LLVM 18 major)?

I think all the options exist for a long time, so it doesn't matter, but just to confirm...

Whichever minimum we could ever see the kernel compiled with, which looks like LLVM 18 in some custom setups? But yeah, all we need is at least LLVM 12...

Quoted 3 lines

In any case, this sounds all reasonable:

Thanks!

reviewer Acked-by on v1 1/2
#14 lore raw
In reply to Marco Elver
Quoted 14 lines · Marco Elver

Rust supports ThreadSanitizer instrumentation via LLVM, which is what KCSAN relies on; however, Rust code is not currently instrumented.

Pass -Zsanitizer=thread and the same TSan backend options used for C code to rustc. Wire up KCSAN_SANITIZE in scripts/Makefile.lib for parity with C (though rustc currently rejects linking crates with mismatched instrumentation).

rustc only accepts -Zsanitizer=thread for targets that declare support for it. Of the targets used by the kernel, this is only possible for the generated x86_64 target specification, so restrict instrumentation of Rust code to x86_64 for now via HAVE_KCSAN_RUSTC. On other architectures Rust code remains uninstrumented as before.

Quoted 8 lines

All TSan options used are supported by the LLVM versions of the minimum supported rustc, so no rustc-option checks are needed (they would also fail, because x86_64-unknown-none used for option checks does not support -Zsanitizer=thread).

With this enabled we can detect data races in kernel Rust code and between Rust and C code.

Help has finally arrived! :)

Thank you for looking into this, for both patches:

Regards,
Boqun

Quoted 103 lines
---
 Documentation/dev-tools/kcsan.rst |  7 +++++++
 lib/Kconfig.kcsan                 |  7 +++++++
 scripts/Makefile.kcsan            | 13 +++++++++++++
 scripts/Makefile.lib              |  3 +++
 scripts/generate_rust_target.rs   |  2 +-
 5 files changed, 31 insertions(+), 1 deletion(-)
Documentation/dev-tools/kcsan.rst +7 -0
index 8575178aa87f..3bb8754f844b 100644
@@ -14,6 +14,9 @@ Usage
 KCSAN is supported by both GCC and Clang. With GCC we require version 11 or
 later, and with Clang also require version 11 or later.
 
+Rust code is instrumented as well on architectures whose Rust target supports
+it (currently only x86_64; see ``CONFIG_HAVE_KCSAN_RUSTC``).
+
 To enable KCSAN configure the kernel with::
 
     CONFIG_KCSAN = y
@@ -121,6 +124,10 @@ the below options are available:
 
     KCSAN_SANITIZE := n
 
+  Note that ``rustc`` rejects linking crates built with and without KCSAN
+  instrumentation, so ``KCSAN_SANITIZE`` and ``KCSAN_SANITIZE_<target>.o``
+  cannot currently be used for Rust code.
+
 .. _"Marking Shared-Memory Accesses" in the LKMM: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/memory-model/Documentation/access-marking.txt
 
 Furthermore, it is possible to tell KCSAN to show or hide entire classes of
lib/Kconfig.kcsan +7 -0
index 4ce4b0c0109c..f0096e1c8b61 100644
@@ -10,6 +10,13 @@ config HAVE_KCSAN_COMPILER
 	  For the list of compilers that support KCSAN, please see
 	  <file:Documentation/dev-tools/kcsan.rst>.
 
+config HAVE_KCSAN_RUSTC
+	def_bool RUST && X86_64
+	help
+	  rustc only accepts -Zsanitizer=thread for targets that declare
+	  support for it; of the kernel's Rust targets, only x86_64 does.
+	  Elsewhere, Rust code is not instrumented.
+
 menuconfig KCSAN
 	bool "KCSAN: dynamic data race detector"
 	depends on HAVE_ARCH_KCSAN && HAVE_KCSAN_COMPILER
scripts/Makefile.kcsan +13 -0
index 19f693b68a96..01af6fd71006 100644
@@ -24,3 +24,16 @@ kcsan-cflags += $(call cc-option,$(call cc-param,tsan-instrument-func-entry-exit
 endif
 
 export CFLAGS_KCSAN := $(kcsan-cflags)
+
+ifdef CONFIG_HAVE_KCSAN_RUSTC
+# The minimum supported rustc's LLVM supports all of these options.
+rustc-param = -Cllvm-args=-$(1)
+kcsan-rustflags := -Zsanitizer=thread \
+	$(call rustc-param,tsan-compound-read-before-write=1) \
+	$(call rustc-param,tsan-distinguish-volatile=1)
+ifndef CONFIG_KCSAN_WEAK_MEMORY
+kcsan-rustflags += $(call rustc-param,tsan-instrument-func-entry-exit=0)
+endif
+endif
+
+export RUSTFLAGS_KCSAN := $(kcsan-rustflags)
scripts/Makefile.lib +3 -0
index 0a4fdd8bd975..78f1c23e54be 100644
@@ -98,6 +98,9 @@ ifeq ($(CONFIG_KCSAN),y)
 _c_flags += $(if $(patsubst n%,, \
 	$(KCSAN_SANITIZE_$(target-stem).o)$(KCSAN_SANITIZE)$(is-kernel-object)), \
 	$(CFLAGS_KCSAN))
+_rust_flags += $(if $(patsubst n%,, \
+	$(KCSAN_SANITIZE_$(target-stem).o)$(KCSAN_SANITIZE)$(is-kernel-object)), \
+	$(RUSTFLAGS_KCSAN))
 # Some uninstrumented files provide implied barriers required to avoid false
 # positives: set KCSAN_INSTRUMENT_BARRIERS for barrier instrumentation only.
 _c_flags += $(if $(patsubst n%,, \
scripts/generate_rust_target.rs +1 -1
index 7687b0dd5474..4b02bffa6b46 100644
@@ -231,7 +231,7 @@ fn main() {
         }
         ts.push("features", features);
         ts.push("llvm-target", "x86_64-linux-gnu");
-        ts.push("supported-sanitizers", ["kcfi", "kernel-address"]);
+        ts.push("supported-sanitizers", ["kcfi", "kernel-address", "thread"]);
         if cfg.rustc_version_atleast(1, 91, 0) {
             ts.push("target-pointer-width", 64);
         } else {
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#4 lore raw

Re: [PATCH 2/2] rust: kcsan: add KUnit test for data race detection

In reply to Marco Elver
Quoted 6 lines
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/Kconfig.test        |  11 +++
 rust/kernel/kcsan_test.rs       | 120 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   2 +
 5 files changed, 135 insertions(+)
 create mode 100644 rust/kernel/kcsan_test.rs

FWIW make rustfmtcheck fails for me on kcsan_test.rs

author maintainer
#5 lore raw

Re: [PATCH 2/2] rust: kcsan: add KUnit test for data race detection

Quoted 9 lines · Alexander Potapenko
Quoted 7 lines
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/Kconfig.test        |  11 +++
 rust/kernel/kcsan_test.rs       | 120 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   2 +
 5 files changed, 135 insertions(+)
 create mode 100644 rust/kernel/kcsan_test.rs

FWIW make rustfmtcheck fails for me on kcsan_test.rs

Oops. I guess we'll make a v2.

#15 lore raw
In reply to Marco Elver

scripts/Makefile.kcsan kcsan-cflags += $(call cc-option,$(call cc-param,tsan-instrument-func-entry-exit · line 33

Quoted 6 lines
scripts/Makefile.kcsan +6 -0
+ifdef CONFIG_HAVE_KCSAN_RUSTC
+# The minimum supported rustc's LLVM supports all of these options.
+rustc-param = -Cllvm-args=-$(1)
+kcsan-rustflags := -Zsanitizer=thread \
+       $(call rustc-param,tsan-compound-read-before-write=1) \
+       $(call rustc-param,tsan-distinguish-volatile=1)

Do we also need -fno-optimize-sibling-calls here?

Quoted 34 lines
scripts/Makefile.kcsan +6 -0
+ifndef CONFIG_KCSAN_WEAK_MEMORY
+kcsan-rustflags += $(call rustc-param,tsan-instrument-func-entry-exit=0)
+endif
+endif
+
+export RUSTFLAGS_KCSAN := $(kcsan-rustflags)
scripts/Makefile.lib +3 -0
index 0a4fdd8bd975..78f1c23e54be 100644
@@ -98,6 +98,9 @@ ifeq ($(CONFIG_KCSAN),y)
 _c_flags += $(if $(patsubst n%,, \
        $(KCSAN_SANITIZE_$(target-stem).o)$(KCSAN_SANITIZE)$(is-kernel-object)), \
        $(CFLAGS_KCSAN))
+_rust_flags += $(if $(patsubst n%,, \
+       $(KCSAN_SANITIZE_$(target-stem).o)$(KCSAN_SANITIZE)$(is-kernel-object)), \
+       $(RUSTFLAGS_KCSAN))
 # Some uninstrumented files provide implied barriers required to avoid false
 # positives: set KCSAN_INSTRUMENT_BARRIERS for barrier instrumentation only.
 _c_flags += $(if $(patsubst n%,, \
scripts/generate_rust_target.rs +1 -2
index 7687b0dd5474..4b02bffa6b46 100644
@@ -231,7 +231,7 @@ fn main() {
         }
         ts.push("features", features);
         ts.push("llvm-target", "x86_64-linux-gnu");
-        ts.push("supported-sanitizers", ["kcfi", "kernel-address"]);
+        ts.push("supported-sanitizers", ["kcfi", "kernel-address", "thread"]);
         if cfg.rustc_version_atleast(1, 91, 0) {
             ts.push("target-pointer-width", 64);
         } else {
--
Quoted 2 lines

2.56.0.385.gd3acb90ef8-goog

--
Alexander Potapenko
Software Engineer

Google Germany GmbH
Erika-Mann-Straße, 33
80636 München

Geschäftsführer: Paul Manicle, Liana Sebastian
Registergericht und -nummer: Hamburg, HRB 86891
Sitz der Gesellschaft: Hamburg

#7 lore raw

Re: [PATCH 2/2] rust: kcsan: add KUnit test for data race detection

In reply to Marco Elver
Quoted 13 lines
rust/kernel/kcsan_test.rs new file +13 -0
+        // SAFETY: `probe_console` has the signature expected by the `console` tracepoint. Being
+        // part of the kernel image, it and `OBSERVED` outlive the registration, so there is no
+        // need to synchronize with in-flight probes after unregistering.
+        to_result(unsafe {
+            bindings::tracepoint_probe_register(
+                &raw mut bindings::__tracepoint_console,
+                probe_console as *mut c_void,
+                ptr::null_mut(),
+            )
+        })?;
+        let _unregister = ScopeGuard::new(|| {
+            // SAFETY: The probe was registered above.
+            unsafe {

rust/kernel/kcsan_test.rs line 101

Quoted 10 lines
rust/kernel/kcsan_test.rs new file +10 -0
+                bindings::tracepoint_probe_unregister(
+                    &raw mut bindings::__tracepoint_console,
+                    probe_console as *mut c_void,
+                    ptr::null_mut(),
+                );
+            }
+        });
+
+        let worker = ctx.clone();
+        workqueue::system_unbound().try_spawn(GFP_KERNEL, move || {

I ran this locally and got the following warning:

[  623.232012] workqueue: work func

_RNvXsb_NtCskctMpSfuwL9_6kernel9workqueueINtNtCs1G77UTwpz6o_4core3pin3PinINtNtNtB7_5alloc4kbox3BoxINtB5_11ClosureWorkNCNvNtNtB7_10kcsan_test5tests9data_races_0ENtNtB1d_9allocator7KmallocEEINtB5_15WorkItemPointerKy0_E3runB7_ enqueued on deprecated workqueue. Use system_{percpu|dfl}_wq instead.

Do we need to use a different workqueue?

Quoted 33 lines
rust/kernel/kcsan_test.rs new file +19 -0
+            while !worker.stop.load(Relaxed) {
+                racy_inc();
+            }
+            worker.done.complete_all();
+        })?;
+
+        let start = Instant::<Monotonic>::now();
+        while !OBSERVED.load(Relaxed) && start.elapsed() < Delta::from_secs(10) {
+            racy_inc();
+        }
+
+        ctx.stop.store(true, Relaxed);
+        ctx.done.wait_for_completion();
+        drop(_unregister);
+
+        assert!(OBSERVED.load(Relaxed));
+        Ok(())
+    }
+}
rust/kernel/lib.rs +2 -1
index 4d5c96ddc49c..009efda9e7a4 100644
@@ -94,6 +94,8 @@
 pub mod iov;
 pub mod irq;
 pub mod jump_label;
+#[cfg(CONFIG_RUST_KCSAN_KUNIT_TEST)]
+mod kcsan_test;
 #[cfg(CONFIG_KUNIT)]
 pub mod kunit;
 pub mod list;
--
Quoted 2 lines

2.56.0.385.gd3acb90ef8-goog

--
Alexander Potapenko
Software Engineer

Google Germany GmbH
Erika-Mann-Straße, 33
80636 München

Geschäftsführer: Paul Manicle, Liana Sebastian
Registergericht und -nummer: Hamburg, HRB 86891
Sitz der Gesellschaft: Hamburg

author maintainer
#16 lore raw
In reply to Alexander Potapenko
Quoted 9 lines · Alexander Potapenko

scripts/Makefile.kcsan kcsan-cflags += $(call cc-option,$(call cc-param,tsan-instrument-func-entry-exit · line 33

Quoted 7 lines
scripts/Makefile.kcsan +6 -0
+ifdef CONFIG_HAVE_KCSAN_RUSTC
+# The minimum supported rustc's LLVM supports all of these options.
+rustc-param = -Cllvm-args=-$(1)
+kcsan-rustflags := -Zsanitizer=thread \
+       $(call rustc-param,tsan-compound-read-before-write=1) \
+       $(call rustc-param,tsan-distinguish-volatile=1)

Do we also need -fno-optimize-sibling-calls here?

It's optional - I added it for Clang so that stack traces are always complete. But rustc doesn't have an equivalent option (neither do some of the hidden llvm options work). So this is the best we can do for now. I might want to note it in the commit message, though.

author maintainer
#8 lore raw

Re: [PATCH 2/2] rust: kcsan: add KUnit test for data race detection

In reply to Alexander Potapenko
Quoted 24 lines · Alexander Potapenko
Quoted 13 lines
(quoted diff) +13 -0
+        // SAFETY: `probe_console` has the signature expected by the `console` tracepoint. Being
+        // part of the kernel image, it and `OBSERVED` outlive the registration, so there is no
+        // need to synchronize with in-flight probes after unregistering.
+        to_result(unsafe {
+            bindings::tracepoint_probe_register(
+                &raw mut bindings::__tracepoint_console,
+                probe_console as *mut c_void,
+                ptr::null_mut(),
+            )
+        })?;
+        let _unregister = ScopeGuard::new(|| {
+            // SAFETY: The probe was registered above.
+            unsafe {

Review

Quoted 10 lines
(quoted diff) +10 -0
+                bindings::tracepoint_probe_unregister(
+                    &raw mut bindings::__tracepoint_console,
+                    probe_console as *mut c_void,
+                    ptr::null_mut(),
+                );
+            }
+        });
+
+        let worker = ctx.clone();
+        workqueue::system_unbound().try_spawn(GFP_KERNEL, move || {
Quoted 7 lines

I ran this locally and got the following warning:

[  623.232012] workqueue: work func

_RNvXsb_NtCskctMpSfuwL9_6kernel9workqueueINtNtCs1G77UTwpz6o_4core3pin3PinINtNtNtB7_5alloc4kbox3BoxINtB5_11ClosureWorkNCNvNtNtB7_10kcsan_test5tests9data_races_0ENtNtB1d_9allocator7KmallocEEINtB5_15WorkItemPointerKy0_E3runB7_ enqueued on deprecated workqueue. Use system_{percpu|dfl}_wq instead.

Do we need to use a different workqueue?

Looks like it, and we need this patch to use system_dfl_wq:

From: Marco Elver <[email protected]>
Date: Tue, 13 Oct 2026 10:05:52 +0000
Subject: [PATCH] rust: workqueue: add system_dfl()

The C kernel deprecated system_unbound_wq in favor of system_dfl_wq (commit 64d8eae3f895 ("workqueue: Add warnings and fallback if system_{unbound}_wq is used")).

Add system_dfl() to provide a safe wrapper around system_dfl_wq.

---
 rust/kernel/workqueue.rs | 10 ++++++++++
 1 file changed, 10 insertions(+)
rust/kernel/workqueue.rs +10 -0
index 7e253b6f299c..e46d3acf903d 100644
@@ -1063,6 +1063,16 @@ pub fn system_unbound() -> &'static Queue {
     unsafe { Queue::from_raw(bindings::system_unbound_wq) }
 }
 
+/// Returns the system default work queue (`system_dfl_wq`).
+///
+/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
+/// are executed immediately as long as `max_active` limit is not reached and resources are
+/// available.
+pub fn system_dfl() -> &'static Queue {
+    // SAFETY: `system_dfl_wq` is a C global, always available.
+    unsafe { Queue::from_raw(bindings::system_dfl_wq) }
+}
+
 /// Returns the system freezable work queue (`system_freezable_wq`).
 ///
 /// It is equivalent to the one returned by [`system`] except that it's freezable.
Signature · 1 line
2.56.0.385.gd3acb90ef8-goog
#9 lore raw

Re: [PATCH 2/2] rust: kcsan: add KUnit test for data race detection

Quoted 41 lines · Marco Elver

Looks like it, and we need this patch to use system_dfl_wq:

From: Marco Elver <[email protected]>
Date: Tue, 13 Oct 2026 10:05:52 +0000
Subject: [PATCH] rust: workqueue: add system_dfl()

The C kernel deprecated system_unbound_wq in favor of system_dfl_wq (commit 64d8eae3f895 ("workqueue: Add warnings and fallback if system_{unbound}_wq is used")).

Add system_dfl() to provide a safe wrapper around system_dfl_wq.

---
 rust/kernel/workqueue.rs | 10 ++++++++++
 1 file changed, 10 insertions(+)
rust/kernel/workqueue.rs +10 -1
index 7e253b6f299c..e46d3acf903d 100644
@@ -1063,6 +1063,16 @@ pub fn system_unbound() -> &'static Queue {
     unsafe { Queue::from_raw(bindings::system_unbound_wq) }
 }
 
+/// Returns the system default work queue (`system_dfl_wq`).
+///
+/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
+/// are executed immediately as long as `max_active` limit is not reached and resources are
+/// available.
+pub fn system_dfl() -> &'static Queue {
+    // SAFETY: `system_dfl_wq` is a C global, always available.
+    unsafe { Queue::from_raw(bindings::system_dfl_wq) }
+}
+
 /// Returns the system freezable work queue (`system_freezable_wq`).
 ///
 /// It is equivalent to the one returned by [`system`] except that it's freezable.
--
Quoted 1 line

2.56.0.385.gd3acb90ef8-goog

This is:

https://lore.kernel.org/rust-for-linux/[email protected]/

i.e. we have had a warning like that in one of our current tests for a while, it would be nice to clean it up:

workqueue: work func _RNvXs8_NtCs5lxGbhOOw2k_6kernel9workqueueINtNtNtB7_4sync3arc3ArcNtNtNtNtBH_4lock8spinlock5tests4TestEINtB5_15WorkItemPointerKy0_E3runB7_ enqueued on deprecated workqueue. Use system_{percpu|dfl}_wq instead.

Cc'ing workqueue: Tejun and Lai.

Cheers,
Miguel

author maintainer
#10 lore raw

Re: [PATCH 2/2] rust: kcsan: add KUnit test for data race detection

Quoted 49 lines · Miguel Ojeda
Quoted 41 lines · Marco Elver

Looks like it, and we need this patch to use system_dfl_wq:

From: Marco Elver <[email protected]>
Date: Tue, 13 Oct 2026 10:05:52 +0000
Subject: [PATCH] rust: workqueue: add system_dfl()

The C kernel deprecated system_unbound_wq in favor of system_dfl_wq (commit 64d8eae3f895 ("workqueue: Add warnings and fallback if system_{unbound}_wq is used")).

Add system_dfl() to provide a safe wrapper around system_dfl_wq.

---
 rust/kernel/workqueue.rs | 10 ++++++++++
 1 file changed, 10 insertions(+)
rust/kernel/workqueue.rs +10 -1
index 7e253b6f299c..e46d3acf903d 100644
@@ -1063,6 +1063,16 @@ pub fn system_unbound() -> &'static Queue {
     unsafe { Queue::from_raw(bindings::system_unbound_wq) }
 }
 
+/// Returns the system default work queue (`system_dfl_wq`).
+///
+/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
+/// are executed immediately as long as `max_active` limit is not reached and resources are
+/// available.
+pub fn system_dfl() -> &'static Queue {
+    // SAFETY: `system_dfl_wq` is a C global, always available.
+    unsafe { Queue::from_raw(bindings::system_dfl_wq) }
+}
+
 /// Returns the system freezable work queue (`system_freezable_wq`).
 ///
 /// It is equivalent to the one returned by [`system`] except that it's freezable.
--
Quoted 1 line

2.56.0.385.gd3acb90ef8-goog

This is:

https://lore.kernel.org/rust-for-linux/[email protected]/

Quoted 8 lines

i.e. we have had a warning like that in one of our current tests for a while, it would be nice to clean it up:

workqueue: work func _RNvXs8_NtCs5lxGbhOOw2k_6kernel9workqueueINtNtNtB7_4sync3arc3ArcNtNtNtNtBH_4lock8spinlock5tests4TestEINtB5_15WorkItemPointerKy0_E3runB7_ enqueued on deprecated workqueue. Use system_{percpu|dfl}_wq instead.

Cc'ing workqueue: Tejun and Lai.

But I take it that the series above is not yet merged?

So I'll keep the previous interface for my test to avoid introducing conflicting patches.

reviewer
#11 lore raw

Re: [PATCH 2/2] rust: kcsan: add KUnit test for data race detection

In reply to Miguel Ojeda
Quoted 49 lines · Miguel Ojeda
Quoted 41 lines · Marco Elver

Looks like it, and we need this patch to use system_dfl_wq:

From: Marco Elver <[email protected]>
Date: Tue, 13 Oct 2026 10:05:52 +0000
Subject: [PATCH] rust: workqueue: add system_dfl()

The C kernel deprecated system_unbound_wq in favor of system_dfl_wq (commit 64d8eae3f895 ("workqueue: Add warnings and fallback if system_{unbound}_wq is used")).

Add system_dfl() to provide a safe wrapper around system_dfl_wq.

---
 rust/kernel/workqueue.rs | 10 ++++++++++
 1 file changed, 10 insertions(+)
rust/kernel/workqueue.rs +10 -1
index 7e253b6f299c..e46d3acf903d 100644
@@ -1063,6 +1063,16 @@ pub fn system_unbound() -> &'static Queue {
     unsafe { Queue::from_raw(bindings::system_unbound_wq) }
 }
 
+/// Returns the system default work queue (`system_dfl_wq`).
+///
+/// Workers are not bound to any specific CPU, not concurrency managed, and all queued work items
+/// are executed immediately as long as `max_active` limit is not reached and resources are
+/// available.
+pub fn system_dfl() -> &'static Queue {
+    // SAFETY: `system_dfl_wq` is a C global, always available.
+    unsafe { Queue::from_raw(bindings::system_dfl_wq) }
+}
+
 /// Returns the system freezable work queue (`system_freezable_wq`).
 ///
 /// It is equivalent to the one returned by [`system`] except that it's freezable.
--
Quoted 1 line

2.56.0.385.gd3acb90ef8-goog

This is:

https://lore.kernel.org/rust-for-linux/[email protected]/

Quoted 8 lines

i.e. we have had a warning like that in one of our current tests for a while, it would be nice to clean it up:

workqueue: work func _RNvXs8_NtCs5lxGbhOOw2k_6kernel9workqueueINtNtNtB7_4sync3arc3ArcNtNtNtNtBH_4lock8spinlock5tests4TestEINtB5_15WorkItemPointerKy0_E3runB7_ enqueued on deprecated workqueue. Use system_{percpu|dfl}_wq instead.

Cc'ing workqueue: Tejun and Lai.

I was actually working on resending that workqueue patch series, but I think this particular patch should be split out as a separate fix, so I'll go ahead and do that.

Alice