Skip to contentSkip to conversation

rust: bug: add warn_once! macro

PATCH In review Ivan Tverdokhleb 5 participants 7 messages Nov 24 – Nov 26

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 rust: bug: add warn_once! macro

Add a Rust counterpart of the C WARN_ONCE() macro. It behaves like warn_on!(), but additionally sets BUGFLAG_ONCE, so the warning is reported only the first time a given call site triggers.

The macro returns the evaluated condition, like warn_on!(), so it can be used directly in an if.

Use it in Vma::zap_vma_range() to report an invalid range, which resolves the pending TODO there.

On configurations where warn_flags!() ignores the flags (UML, ARM and LoongArch), the macro behaves like warn_on!() and warns every time.

---
 rust/kernel/bug.rs     | 46 ++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/mm/virt.rs |  3 +--
 2 files changed, 47 insertions(+), 2 deletions(-)
rust/kernel/bug.rs +46 -0
index 3b40b0bd3..a0db5c902 100644
@@ -156,6 +156,27 @@ macro_rules! warn_on {
     }};
 }
 
+/// Report a warning on the first time `cond` is true and return the condition's evaluation result.
+#[macro_export]
+macro_rules! warn_once {
+    ($cond:expr) => {{
+        let cond = $cond;
+
+        #[cfg(CONFIG_DEBUG_BUGVERBOSE_DETAILED)]
+        const COND_STR: &str = concat!("[", stringify!($cond), "] ", file!());
+        #[cfg(not(CONFIG_DEBUG_BUGVERBOSE_DETAILED))]
+        const COND_STR: &str = file!();
+
+        if cond {
+            const WARN_ON_FLAGS: u32 = $crate::bug::bugflag_taint($crate::bindings::TAINT_WARN)
+                | $crate::bindings::BUGFLAG_ONCE;
+
+            $crate::warn_flags!(COND_STR, WARN_ON_FLAGS);
+        }
+        cond
+    }};
+}
+
 #[cfg(CONFIG_RUST_BUG_KUNIT_TEST)]
 #[macros::kunit_tests(rust_kernel_bug)]
 mod tests {
@@ -184,4 +205,29 @@ fn test_warn_on() {
 
         assert_eq!(suppressed_count, 1);
     }
+
+    #[test]
+    fn test_warn_once() {
+        // SAFETY: `kunit_get_current_test()` is always safe to call (it has
+        // fallbacks for when no KUnit test is running).
+        let test = unsafe { bindings::kunit_get_current_test() };
+
+        // SAFETY: This function runs only as a KUnit test case, so `test` is a
+        // valid pointer to the running test.
+        let handle = unsafe { bindings::kunit_start_suppress_warning(test) };
+
+        for _ in 0..2 {
+            assert!(warn_once!(true));
+        }
+
+        // SAFETY: `kunit_suppressed_warning_count()` accepts any value returned by
+        // `kunit_start_suppress_warning()`.
+        let suppressed_count = unsafe { bindings::kunit_suppressed_warning_count(handle) };
+
+        // SAFETY: `test` is valid as above. `kunit_end_suppress_warning()` accepts any
+        // value returned by `kunit_start_suppress_warning()`.
+        unsafe { bindings::kunit_end_suppress_warning(test, handle) };
+
+        assert_eq!(suppressed_count, 1);
+    }
 }
rust/kernel/mm/virt.rs +1 -2
index 63eb730b0..567665958 100644
@@ -115,8 +115,7 @@ pub fn end(&self) -> usize {
     #[inline]
     pub fn zap_vma_range(&self, address: usize, size: usize) {
         let (end, did_overflow) = address.overflowing_add(size);
-        if did_overflow || address < self.start() || self.end() < end {
-            // TODO: call WARN_ONCE once Rust version of it is added
+        if crate::warn_once!(did_overflow || address < self.start() || self.end() < end) {
             return;
         }
 
Signature · 1 line
2.56.1
#1 lore raw
Quoted 3 lines · On Tue, 24 Nov 2026 15:27:07 +0200 Ivan Tverdokhleb…

Add a Rust counterpart of the C WARN_ONCE() macro. It behaves like warn_on!(), but additionally sets BUGFLAG_ONCE, so the warning is reported only the first time a given call site triggers.

C WARN_ONCE() takes a format string. This macro is the Rust version of WARN_ON_ONCE().

Quoted 8 lines

The macro returns the evaluated condition, like warn_on!(), so it can be used directly in an if.

Use it in Vma::zap_vma_range() to report an invalid range, which resolves the pending TODO there.

On configurations where warn_flags!() ignores the flags (UML, ARM and LoongArch), the macro behaves like warn_on!() and warns every time.

C WARN_ON_ONCE() warns only once on these architectures too. I have a local warn_on_once!() patch that does the same on all architectures. I can post it if needed.

Also, this patch does not build on UML, and test_warn_once fails on x86_64.

rust/kernel/mm/virt.rs pub fn end(&self) -> usize { · line 118

Quoted 9 lines
rust/kernel/mm/virt.rs +1 -2
@@ -115,8 +115,7 @@ pub fn end(&self) -> usize {
     #[inline]
     pub fn zap_vma_range(&self, address: usize, size: usize) {
         let (end, did_overflow) = address.overflowing_add(size);
-        if did_overflow || address < self.start() || self.end() < end {
-            // TODO: call WARN_ONCE once Rust version of it is added
+        if crate::warn_once!(did_overflow || address < self.start() || self.end() < end) {

Miguel said that "Erroneous Behavior" cases like this should use debug_assert!() plus pr_warn_once!() [1]. Also, the C side uses VM_WARN_ON_ONCE() in __zap_vma_range(), which warns only with CONFIG_DEBUG_VM.

[1] https://lore.kernel.org/rust-for-linux/CANiq72=tKVD13GD2Bzmt_LnC4SiOX1nkHQPcz2BS=P=b23e0Yw@mail.gmail.com/

#2 lore raw

Hi Fujita,
Thank you very much for the quick review and explanation! Please go ahead and post your warn_on_once!() patch since it properly handles all architectures including UML. I'll drop this patch and look into updating Vma::zap_vma_range() using debug_assert!() + pr_warn_once!() as Miguel suggested.
Best regards,
Ivan

вт, 24 нояб. 2026 г. в 15:51, FUJITA Tomonori <[email protected]>:

Quoted 43 lines
Quoted 3 lines · On Tue, 24 Nov 2026 15:27:07 +0200 Ivan Tverdokhleb…

Add a Rust counterpart of the C WARN_ONCE() macro. It behaves like warn_on!(), but additionally sets BUGFLAG_ONCE, so the warning is reported only the first time a given call site triggers.

C WARN_ONCE() takes a format string. This macro is the Rust version of WARN_ON_ONCE().

Quoted 8 lines

The macro returns the evaluated condition, like warn_on!(), so it can be used directly in an if.

Use it in Vma::zap_vma_range() to report an invalid range, which resolves the pending TODO there.

On configurations where warn_flags!() ignores the flags (UML, ARM and LoongArch), the macro behaves like warn_on!() and warns every time.

C WARN_ON_ONCE() warns only once on these architectures too. I have a local warn_on_once!() patch that does the same on all architectures. I can post it if needed.

Also, this patch does not build on UML, and test_warn_once fails on x86_64.

rust/kernel/mm/virt.rs pub fn end(&self) -> usize { · line 118

Quoted 9 lines
rust/kernel/mm/virt.rs +1 -2
@@ -115,8 +115,7 @@ pub fn end(&self) -> usize {
     #[inline]
     pub fn zap_vma_range(&self, address: usize, size: usize) {
         let (end, did_overflow) = address.overflowing_add(size);
-        if did_overflow || address < self.start() || self.end() < end {
-            // TODO: call WARN_ONCE once Rust version of it is added
+        if crate::warn_once!(did_overflow || address < self.start() || self.end() < end) {

Miguel said that "Erroneous Behavior" cases like this should use debug_assert!() plus pr_warn_once!() [1]. Also, the C side uses VM_WARN_ON_ONCE() in __zap_vma_range(), which warns only with CONFIG_DEBUG_VM.

[1] https://lore.kernel.org/rust-for-linux/CANiq72=tKVD13GD2Bzmt_LnC4SiOX1nkHQPcz2BS=P=b23e0Yw@mail.gmail.com/

#5 lore raw
In reply to Ivan Tverdokhleb
kernel test robot noticed the following build errors:

Hi Ivan,

kernel test robot noticed the following build errors:

[auto build test ERROR on rust/rust-next]
[also build test ERROR on akpm-mm/mm-everything linus/master v7.4-rc4 next-20261123] [cannot apply to ah-configfs/configfs-next]
[If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]

url:    https://github.com/intel-lab-lkp/linux/commits/Ivan-Tverdokhleb/rust-bug-add-warn_once-macro/20261124-152707
base:   https://github.com/Rust-for-Linux/linux rust-next
patch link:    https://lore.kernel.org/r/20261124132707.101769-1-mbkchelofficialdev%40gmail.com
patch subject: [PATCH] rust: bug: add warn_once! macro
config: um-allmodconfig (https://download.01.org/0day-ci/archive/20261125/[email protected]/config)
compiler: clang version 17.0.6 (https://github.com/llvm/llvm-project 6009708b4367171ccdbf4b5905cb6a803753fe18)
rustc: rustc 1.96.0 (ac68faa20 2026-05-25)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261125/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

In file included from kernel/sched/rq-offsets.c:5:
In file included from kernel/sched/sched.h:28:
In file included from include/linux/cgroup_api.h:1:
In file included from include/linux/cgroup.h:27:
In file included from include/linux/kernel_stat.h:8:
In file included from include/linux/interrupt.h:11:
In file included from include/linux/hardirq.h:11:
In file included from arch/um/include/asm/hardirq.h:24:
In file included from include/linux/irq.h:20:
In file included from include/linux/io.h:12:
In file included from arch/um/include/asm/io.h:24:
include/asm-generic/io.h:1209:55: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]
1209 | return (port > MMIO_UPPER_LIMIT) ? NULL : PCI_IOBASE + port;
| ~~~~~~~~~~ ^
1 warning generated.
llvm-nm: error: rust/helpers/helpers.o: No such file or directory
clang diag: include/asm-generic/io.h:1209:55: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic] clang diag: include/asm-generic/io.h:1209:55: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic] clang diag: include/asm-generic/io.h:1209:55: warning: performing pointer arithmetic on a null pointer has undefined behavior [-Wnull-pointer-arithmetic]

>> error[E0425]: cannot find value `BUGFLAG_ONCE` in crate `$crate::bindings`

--> rust/kernel/bug.rs:172:37
|
172 | | $crate::bindings::BUGFLAG_ONCE;
| ^^^^^^^^^^^^ not found in $crate::bindings
|
::: rust/kernel/mm/virt.rs:118:12
|
118 | if crate::warn_once!(did_overflow || address < self.start() || self.end() < end) {
| ----------------------------------------------------------------------------- in this macro invocation
|
= note: this error originates in the macro crate::warn_once (in Nightly builds, run with -Z macro-backtrace for more info)

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#6 lore raw
In reply to Ivan Tverdokhleb
Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] rust: bug: warn_once! breaks build when CONFIG_GENERIC_BUG is disabled - [Medium] rust: bug…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] rust: bug: warn_once! breaks build when CONFIG_GENERIC_BUG is disabled
- [Medium] rust: bug: test_warn_once() always fails with suppressed_count == 2
- [Low] rust: bug: condition-only macro is named warn_once! instead of warn_on_once!
--

commit a4018fab2b94d6f23a5439e460aa5e9ca9e0714c
Author: Ivan Tverdokhleb <[email protected]>

rust: bug: add warn_once! macro

This commit adds a warn_once! macro that sets BUGFLAG_ONCE when reporting a warning, adds a KUnit test for it, and uses it in VmaRef::zap_vma_range().

rust/kernel/bug.rs macro_rules! warn_on { · line 162

Quoted 12 lines
rust/kernel/bug.rs +4 -0
index 3b40b0bd37b50..a0db5c902ecba 100644
@@ -156,6 +156,27 @@ macro_rules! warn_on {
     }};
 }
 
+/// Report a warning on the first time `cond` is true and return the condition's evaluation result.
+#[macro_export]
+macro_rules! warn_once {
+    ($cond:expr) => {{

[Severity: Low]
Should this macro be named warn_on_once! rather than warn_once!? In C, WARN_ON(cond) and WARN_ON_ONCE(cond) take only a condition, whereas WARN(cond, fmt, ...) and WARN_ONCE(cond, fmt, ...) take a format string. Since the existing condition-only macro in this file is warn_on!, naming this warn_on_once! would stay consistent and leave warn_once! available for formatted warnings.

rust/kernel/bug.rs macro_rules! warn_on { · line 172

Quoted 10 lines
rust/kernel/bug.rs +10 -0
+        let cond = $cond;
+
+        #[cfg(CONFIG_DEBUG_BUGVERBOSE_DETAILED)]
+        const COND_STR: &str = concat!("[", stringify!($cond), "] ", file!());
+        #[cfg(not(CONFIG_DEBUG_BUGVERBOSE_DETAILED))]
+        const COND_STR: &str = file!();
+
+        if cond {
+            const WARN_ON_FLAGS: u32 = $crate::bug::bugflag_taint($crate::bindings::TAINT_WARN)
+                | $crate::bindings::BUGFLAG_ONCE;

[Severity: Medium]
Does referencing $crate::bindings::BUGFLAG_ONCE unconditionally here break the build when CONFIG_GENERIC_BUG is disabled, such as on CONFIG_UML=y or CONFIG_BUG=n?

In include/asm-generic/bug.h, BUGFLAG_ONCE is only defined under #ifdef CONFIG_GENERIC_BUG, so bindgen does not generate bindings::BUGFLAG_ONCE when CONFIG_GENERIC_BUG is not set, and VmaRef::zap_vma_range() expands warn_once! unconditionally in the kernel crate.

Quoted 30 lines
rust/kernel/bug.rs +23 -0
+
+            $crate::warn_flags!(COND_STR, WARN_ON_FLAGS);
+        }
+        cond
+    }};
+}
+
 #[cfg(CONFIG_RUST_BUG_KUNIT_TEST)]
 #[macros::kunit_tests(rust_kernel_bug)]
 mod tests {
@@ -184,4 +205,29 @@ fn test_warn_on() {
 
         assert_eq!(suppressed_count, 1);
     }
+
+    #[test]
+    fn test_warn_once() {
+        // SAFETY: `kunit_get_current_test()` is always safe to call (it has
+        // fallbacks for when no KUnit test is running).
+        let test = unsafe { bindings::kunit_get_current_test() };
+
+        // SAFETY: This function runs only as a KUnit test case, so `test` is a
+        // valid pointer to the running test.
+        let handle = unsafe { bindings::kunit_start_suppress_warning(test) };
+
+        for _ in 0..2 {
+            assert!(warn_once!(true));
+        }
+
+        // SAFETY: `kunit_suppressed_warning_count()` accepts any value returned by

rust/kernel/bug.rs fn test_warn_on() { · line 233

Quoted 10 lines
rust/kernel/bug.rs +9 -0
+        // `kunit_start_suppress_warning()`.
+        let suppressed_count = unsafe { bindings::kunit_suppressed_warning_count(handle) };
+
+        // SAFETY: `test` is valid as above. `kunit_end_suppress_warning()` accepts any
+        // value returned by `kunit_start_suppress_warning()`.
+        unsafe { bindings::kunit_end_suppress_warning(test, handle) };
+
+        assert_eq!(suppressed_count, 1);
+    }
 }

[Severity: Medium]
Does test_warn_once() always fail with suppressed_count == 2?

On CONFIG_GENERIC_BUG architectures, __report_bug() checks KUnit warning suppression and returns before checking BUGFLAG_ONCE or setting BUGFLAG_DONE:

lib/bug.c:__report_bug() {
	...
	/*
	 * Before the once logic so suppressed warnings do not consume
	 * the single-fire budget of WARN_ON_ONCE().
	 */
	if (warning && kunit_is_suppressed_warning(true))
		return BUG_TRAP_TYPE_WARN;

	disable_trace_on_warning();

	if (warning && once) {
		if (done)
			return BUG_TRAP_TYPE_WARN;

		/*
		 * Since this is the only store, concurrency is not an issue.
		 */
		bug->flags |= BUGFLAG_DONE;
	}
	...
}

And on CONFIG_ARM, CONFIG_LOONGARCH and CONFIG_UML, warn_flags! ignores $flags and warns on every call. In both cases, both loop iterations increment the suppressed warning counter, so assert_eq!(suppressed_count, 1) fails.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
reviewer
#3 lore raw
In reply to FUJITA Tomonori
Quoted 41 lines · FUJITA Tomonori
Quoted 3 lines · On Tue, 24 Nov 2026 15:27:07 +0200 Ivan Tverdokhleb…

Add a Rust counterpart of the C WARN_ONCE() macro. It behaves like warn_on!(), but additionally sets BUGFLAG_ONCE, so the warning is reported only the first time a given call site triggers.

C WARN_ONCE() takes a format string. This macro is the Rust version of WARN_ON_ONCE().

Quoted 8 lines

The macro returns the evaluated condition, like warn_on!(), so it can be used directly in an if.

Use it in Vma::zap_vma_range() to report an invalid range, which resolves the pending TODO there.

On configurations where warn_flags!() ignores the flags (UML, ARM and LoongArch), the macro behaves like warn_on!() and warns every time.

C WARN_ON_ONCE() warns only once on these architectures too. I have a local warn_on_once!() patch that does the same on all architectures. I can post it if needed.

Also, this patch does not build on UML, and test_warn_once fails on x86_64.

rust/kernel/mm/virt.rs pub fn end(&self) -> usize { · line 118

Quoted 9 lines
rust/kernel/mm/virt.rs +1 -2
@@ -115,8 +115,7 @@ pub fn end(&self) -> usize {
     #[inline]
     pub fn zap_vma_range(&self, address: usize, size: usize) {
         let (end, did_overflow) = address.overflowing_add(size);
-        if did_overflow || address < self.start() || self.end() < end {
-            // TODO: call WARN_ONCE once Rust version of it is added
+        if crate::warn_once!(did_overflow || address < self.start() || self.end() < end) {

Miguel said that "Erroneous Behavior" cases like this should use debug_assert!() plus pr_warn_once!() [1]. Also, the C side uses VM_WARN_ON_ONCE() in __zap_vma_range(), which warns only with CONFIG_DEBUG_VM.

Quoted 1 line

[1] https://lore.kernel.org/rust-for-linux/CANiq72=tKVD13GD2Bzmt_LnC4SiOX1nkHQPcz2BS=P=b23e0Yw@mail.gmail.com/

For zap_vma_range I think we do actually want WARN_ONCE. For something important like zapping a VMA range if thngs are used incorrectly we do want to figure out.

A debug_assert is not as useful because it's not enabled on kernel shipped to end users. A pr_warn_once is not useful because you don't know who's calling the library and causing issue, and also a dmesg warning is mostly ignored by people like a WARN.

I think a condition is unlikely to be triggered from invalid userspace inputs, and the misuse is actually a bug, we should prefer WARN_ON because that's how can get things fixed.

Best,
Gary

#4 lore raw

Hi Gary,
Thanks for the feedback!

I've actually already sent out v2 and v3, where I dropped the warn_once!() macro and switched to debug_assert!() and pr_warn_once!() (gated behind CONFIG_DEBUG_VM) in Vma::zap_vma_range(), following suggestions from Miguel and Nicolás.
You can find the v3 thread here:
https://lore.kernel.org/rust-for-linux/[email protected]/T/#u
Let's continue the discussion there if you think we should still reconsider bringing back WARN_ONCE!
Best,
Ivan

чт, 26 нояб. 2026 г. в 17:49, Gary Guo <[email protected]>:

Quoted 59 lines · FUJITA Tomonori
Quoted 41 lines
Quoted 3 lines · On Tue, 24 Nov 2026 15:27:07 +0200 Ivan Tverdokhleb…

Add a Rust counterpart of the C WARN_ONCE() macro. It behaves like warn_on!(), but additionally sets BUGFLAG_ONCE, so the warning is reported only the first time a given call site triggers.

C WARN_ONCE() takes a format string. This macro is the Rust version of WARN_ON_ONCE().

Quoted 8 lines

The macro returns the evaluated condition, like warn_on!(), so it can be used directly in an if.

Use it in Vma::zap_vma_range() to report an invalid range, which resolves the pending TODO there.

On configurations where warn_flags!() ignores the flags (UML, ARM and LoongArch), the macro behaves like warn_on!() and warns every time.

C WARN_ON_ONCE() warns only once on these architectures too. I have a local warn_on_once!() patch that does the same on all architectures. I can post it if needed.

Also, this patch does not build on UML, and test_warn_once fails on x86_64.

rust/kernel/mm/virt.rs pub fn end(&self) -> usize { · line 118

Quoted 9 lines
rust/kernel/mm/virt.rs +1 -2
@@ -115,8 +115,7 @@ pub fn end(&self) -> usize {
     #[inline]
     pub fn zap_vma_range(&self, address: usize, size: usize) {
         let (end, did_overflow) = address.overflowing_add(size);
-        if did_overflow || address < self.start() || self.end() < end {
-            // TODO: call WARN_ONCE once Rust version of it is added
+        if crate::warn_once!(did_overflow || address < self.start() || self.end() < end) {

Miguel said that "Erroneous Behavior" cases like this should use debug_assert!() plus pr_warn_once!() [1]. Also, the C side uses VM_WARN_ON_ONCE() in __zap_vma_range(), which warns only with CONFIG_DEBUG_VM.

Quoted 1 line

[1] https://lore.kernel.org/rust-for-linux/CANiq72=tKVD13GD2Bzmt_LnC4SiOX1nkHQPcz2BS=P=b23e0Yw@mail.gmail.com/

For zap_vma_range I think we do actually want WARN_ONCE. For something important like zapping a VMA range if thngs are used incorrectly we do want to figure out.

A debug_assert is not as useful because it's not enabled on kernel shipped to end users. A pr_warn_once is not useful because you don't know who's calling the library and causing issue, and also a dmesg warning is mostly ignored by people like a WARN.

I think a condition is unlikely to be triggered from invalid userspace inputs, and the misuse is actually a bug, we should prefer WARN_ON because that's how can get things fixed.

Best,
Gary