Rust for Linux List
 help / color / mirror / Atom feed
* [PATCH v1] rust: bug: Add bug_on macro
@ 2026-07-07 14:30 FUJITA Tomonori
  2026-07-07 14:51 ` Danilo Krummrich
  0 siblings, 1 reply; 5+ messages in thread
From: FUJITA Tomonori @ 2026-07-07 14:30 UTC (permalink / raw)
  To: ojeda
  Cc: a.hindborg, acourbot, aliceryhl, bjorn3_gh, boqun, dakr,
	daniel.almeida, gary, lossin, tamird, tmgross, work,
	rust-for-linux, FUJITA Tomonori

From: FUJITA Tomonori <fujita.tomonori@gmail.com>

Add bug_on macro(), the Rust equivalent of the C's BUG_ON(), which
uses the BUG/WARN feature (lib/bug.c) via assembly for
x86_64/arm64/riscv/s390 like warn_on() macro.

Use of this macro is heavily discouraged. Prefer warn_on() macro with
recovery code where feasible. See the documentation for C's BUG_ON()
for guidance on when it is rarely justified.

Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
---
 rust/kernel/bug.rs | 105 ++++++++++++++++++++++++++++++++-------------
 1 file changed, 76 insertions(+), 29 deletions(-)

diff --git a/rust/kernel/bug.rs b/rust/kernel/bug.rs
index ed943960f851..0f904c4614a2 100644
--- a/rust/kernel/bug.rs
+++ b/rust/kernel/bug.rs
@@ -11,9 +11,13 @@
 #[cfg(all(CONFIG_BUG, not(CONFIG_UML), not(CONFIG_LOONGARCH), not(CONFIG_ARM)))]
 #[cfg(CONFIG_DEBUG_BUGVERBOSE)]
 macro_rules! warn_flags {
-    ($file:expr, $flags:expr) => {
-        const FLAGS: u32 = $crate::bindings::BUGFLAG_WARNING | $flags;
-        const _FILE: &[u8] = $file.as_bytes();
+    ($cond:expr, $flags:expr, $asm_tail:expr) => {{
+        #[cfg(CONFIG_DEBUG_BUGVERBOSE_DETAILED)]
+        const _COND_STR: &str = concat!("[", stringify!($cond), "] ", file!());
+        #[cfg(not(CONFIG_DEBUG_BUGVERBOSE_DETAILED))]
+        const _COND_STR: &str = file!();
+
+        const _FILE: &[u8] = _COND_STR.as_bytes();
         // Plus one for null-terminator.
         static FILE: [u8; _FILE.len() + 1] = {
             let mut bytes = [0; _FILE.len() + 1];
@@ -24,6 +28,7 @@ macro_rules! warn_flags {
             }
             bytes
         };
+        const FLAGS: u32 = $flags;
 
         // SAFETY:
         // - `file`, `line`, `flags`, and `size` are all compile-time constants or
@@ -35,14 +40,14 @@ macro_rules! warn_flags {
                 concat!(
                     "/* {size} */",
                     include!(concat!(env!("OBJTREE"), "/rust/kernel/generated_arch_warn_asm.rs")),
-                    include!(concat!(env!("OBJTREE"), "/rust/kernel/generated_arch_reachable_asm.rs")));
+                    $asm_tail);
                 file = sym FILE,
                 line = const line!(),
                 flags = const FLAGS,
                 size = const ::core::mem::size_of::<$crate::bindings::bug_entry>(),
             );
         }
-    }
+    }};
 }
 
 #[macro_export]
@@ -50,8 +55,8 @@ macro_rules! warn_flags {
 #[cfg(all(CONFIG_BUG, not(CONFIG_UML), not(CONFIG_LOONGARCH), not(CONFIG_ARM)))]
 #[cfg(not(CONFIG_DEBUG_BUGVERBOSE))]
 macro_rules! warn_flags {
-    ($file:expr, $flags:expr) => {
-        const FLAGS: u32 = $crate::bindings::BUGFLAG_WARNING | $flags;
+    ($cond:expr, $flags:expr, $asm_tail:expr) => {
+        const FLAGS: u32 = $flags;
 
         // SAFETY:
         // - `flags` and `size` are all compile-time constants, preventing
@@ -63,7 +68,7 @@ macro_rules! warn_flags {
                 concat!(
                     "/* {size} */",
                     include!(concat!(env!("OBJTREE"), "/rust/kernel/generated_arch_warn_asm.rs")),
-                    include!(concat!(env!("OBJTREE"), "/rust/kernel/generated_arch_reachable_asm.rs")));
+                    $asm_tail);
                 flags = const FLAGS,
                 size = const ::core::mem::size_of::<$crate::bindings::bug_entry>(),
             );
@@ -75,16 +80,23 @@ macro_rules! warn_flags {
 #[doc(hidden)]
 #[cfg(all(CONFIG_BUG, CONFIG_UML))]
 macro_rules! warn_flags {
-    ($file:expr, $flags:expr) => {
-        // SAFETY: It is always safe to call `warn_slowpath_fmt()`
-        // with a valid null-terminated string.
-        unsafe {
-            $crate::bindings::warn_slowpath_fmt(
-                $crate::c_str!(::core::file!()).as_char_ptr(),
-                line!() as $crate::ffi::c_int,
-                $flags as $crate::ffi::c_uint,
-                ::core::ptr::null(),
-            );
+    ($cond:expr, $flags:expr, $asm_tail:expr) => {
+        // bug_on!() sets $flags to 0, so we can use that to determine
+        // whether to call BUG() or WARN_ON().
+        if $flags == 0 {
+            // SAFETY: It is always safe to call `BUG()`.
+            unsafe { $crate::bindings::BUG() }
+        } else {
+            // SAFETY: It is always safe to call `warn_slowpath_fmt()`
+            // with a valid null-terminated string.
+            unsafe {
+                $crate::bindings::warn_slowpath_fmt(
+                    $crate::c_str!(::core::file!()).as_char_ptr(),
+                    line!() as $crate::ffi::c_int,
+                    $flags as $crate::ffi::c_uint,
+                    ::core::ptr::null(),
+                );
+            }
         }
     };
 }
@@ -93,9 +105,16 @@ macro_rules! warn_flags {
 #[doc(hidden)]
 #[cfg(all(CONFIG_BUG, any(CONFIG_LOONGARCH, CONFIG_ARM)))]
 macro_rules! warn_flags {
-    ($file:expr, $flags:expr) => {
-        // SAFETY: It is always safe to call `WARN_ON()`.
-        unsafe { $crate::bindings::WARN_ON(true) }
+    ($cond:expr, $flags:expr, $asm_tail:expr) => {
+        // bug_on!() sets $flags to 0, so we can use that to determine
+        // whether to call BUG() or WARN_ON().
+        if $flags == 0 {
+            // SAFETY: It is always safe to call `BUG()`.
+            unsafe { $crate::bindings::BUG() }
+        } else {
+            // SAFETY: It is always safe to call `WARN_ON()`.
+            unsafe { $crate::bindings::WARN_ON(true) }
+        }
     };
 }
 
@@ -103,7 +122,7 @@ macro_rules! warn_flags {
 #[doc(hidden)]
 #[cfg(not(CONFIG_BUG))]
 macro_rules! warn_flags {
-    ($file:expr, $flags:expr) => {};
+    ($cond:expr, $flags:expr, $asm_tail:expr) => {};
 }
 
 #[doc(hidden)]
@@ -117,16 +136,44 @@ macro_rules! warn_on {
     ($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);
+            #[cfg(any(not(CONFIG_BUG), CONFIG_UML))]
+            const WARN_ON_FLAGS: u32 = $crate::bindings::TAINT_WARN;
+            #[cfg(all(CONFIG_BUG, not(CONFIG_UML)))]
+            const WARN_ON_FLAGS: u32 = $crate::bindings::BUGFLAG_WARNING
+                | $crate::bug::bugflag_taint($crate::bindings::TAINT_WARN);
 
-            $crate::warn_flags!(_COND_STR, WARN_ON_FLAGS);
+            $crate::warn_flags!(
+                $cond,
+                WARN_ON_FLAGS,
+                include!(concat!(
+                    env!("OBJTREE"),
+                    "/rust/kernel/generated_arch_reachable_asm.rs"
+                ))
+            );
         }
         cond
     }};
 }
+
+/// Reports an unrecoverable kernel bug if `cond` is true.
+///
+/// This is the Rust equivalent of the C macro [`BUG_ON()`]. Unlike [`warn_on!`], it never
+/// returns control to the caller when `cond` is true.
+///
+/// Use of this macro is *heavily discouraged*. Prefer [`warn_on!`] with recovery code where
+/// feasible. Please see the documentation for the C macro [`BUG_ON()`] for guidance on when it
+/// is (rarely) justified.
+///
+/// [`BUG_ON()`]: https://docs.kernel.org/process/deprecated.html#bug-and-bug-on
+#[macro_export]
+macro_rules! bug_on {
+    ($cond:expr) => {{
+        let cond = $cond;
+        if cond {
+            $crate::warn_flags!($cond, 0, "");
+            // SAFETY: We call `BUG()` above so this block will never be reached.
+            unsafe { core::hint::unreachable_unchecked() }
+        }
+    }};
+}

base-commit: dc59e4fea9d83f03bad6bddf3fa2e52491777482
-- 
2.43.0


^ permalink raw reply related	[flat|nested] 5+ messages in thread

* Re: [PATCH v1] rust: bug: Add bug_on macro
  2026-07-07 14:30 [PATCH v1] rust: bug: Add bug_on macro FUJITA Tomonori
@ 2026-07-07 14:51 ` Danilo Krummrich
  2026-07-07 15:20   ` Greg KH
  0 siblings, 1 reply; 5+ messages in thread
From: Danilo Krummrich @ 2026-07-07 14:51 UTC (permalink / raw)
  To: FUJITA Tomonori
  Cc: ojeda, a.hindborg, acourbot, aliceryhl, bjorn3_gh, boqun,
	daniel.almeida, gary, lossin, tamird, tmgross, work,
	rust-for-linux, FUJITA Tomonori

On Tue Jul 7, 2026 at 4:30 PM CEST, FUJITA Tomonori wrote:
> Use of this macro is heavily discouraged. Prefer warn_on() macro with
> recovery code where feasible. See the documentation for C's BUG_ON()
> for guidance on when it is rarely justified.

Given that, can you please spell out the motivation for this patch?

^ permalink raw reply	[flat|nested] 5+ messages in thread

* Re: [PATCH v1] rust: bug: Add bug_on macro
  2026-07-07 14:51 ` Danilo Krummrich
@ 2026-07-07 15:20   ` Greg KH
  2026-07-07 22:48     ` FUJITA Tomonori
  0 siblings, 1 reply; 5+ messages in thread
From: Greg KH @ 2026-07-07 15:20 UTC (permalink / raw)
  To: Danilo Krummrich
  Cc: FUJITA Tomonori, ojeda, a.hindborg, acourbot, aliceryhl,
	bjorn3_gh, boqun, daniel.almeida, gary, lossin, tamird, tmgross,
	work, rust-for-linux, FUJITA Tomonori

On Tue, Jul 07, 2026 at 04:51:40PM +0200, Danilo Krummrich wrote:
> On Tue Jul 7, 2026 at 4:30 PM CEST, FUJITA Tomonori wrote:
> > Use of this macro is heavily discouraged. Prefer warn_on() macro with
> > recovery code where feasible. See the documentation for C's BUG_ON()
> > for guidance on when it is rarely justified.
> 
> Given that, can you please spell out the motivation for this patch?

I agree, this should probably NOT be added unless there is a real user
for it that requires it and we all agree that crashing the system is the
only way out.

thanks,

greg k-h

^ permalink raw reply	[flat|nested] 5+ messages in thread

* Re: [PATCH v1] rust: bug: Add bug_on macro
  2026-07-07 15:20   ` Greg KH
@ 2026-07-07 22:48     ` FUJITA Tomonori
  2026-07-08  5:29       ` Greg KH
  0 siblings, 1 reply; 5+ messages in thread
From: FUJITA Tomonori @ 2026-07-07 22:48 UTC (permalink / raw)
  To: gregkh
  Cc: dakr, tomo, ojeda, a.hindborg, acourbot, aliceryhl, bjorn3_gh,
	boqun, daniel.almeida, gary, lossin, tamird, tmgross, work,
	rust-for-linux, fujita.tomonori

On Tue, 7 Jul 2026 17:20:10 +0200
Greg KH <gregkh@linuxfoundation.org> wrote:

> On Tue, Jul 07, 2026 at 04:51:40PM +0200, Danilo Krummrich wrote:
>> On Tue Jul 7, 2026 at 4:30 PM CEST, FUJITA Tomonori wrote:
>> > Use of this macro is heavily discouraged. Prefer warn_on() macro with
>> > recovery code where feasible. See the documentation for C's BUG_ON()
>> > for guidance on when it is rarely justified.
>> 
>> Given that, can you please spell out the motivation for this patch?
> 
> I agree, this should probably NOT be added unless there is a real user
> for it that requires it and we all agree that crashing the system is the
> only way out.

bindings::BUG() is already in use today, indirectly, from the kernel
crate itself and from drivers such as binder and nova-core, via
panic!()/.exepct().unwrap() on invariants that "can't happen". All of
those funnel through panic() in kernel/lib.rs (#[panic_handler]),
which itself calls BUG().

The motivation for this patch is narrow: replace that bindings::BUG()
call in lib.rs's panic() with bug_on!(), for a somewhat better
trace. It isn't adding a new decision to crash the system -- that
decision is already made at each of the existing panic!()/.expect()
call sites.

Separately, calling bug_on!() directly at a call site, instead of going
through panic!()/.expect(), gives an accurate trace, since the location
is captured at the actual check rather than inside the shared panic
handler.

How about marking the macro #[doc(hidden)], to make it clear it isn't
meant to be called directly by driver authors?

^ permalink raw reply	[flat|nested] 5+ messages in thread

* Re: [PATCH v1] rust: bug: Add bug_on macro
  2026-07-07 22:48     ` FUJITA Tomonori
@ 2026-07-08  5:29       ` Greg KH
  0 siblings, 0 replies; 5+ messages in thread
From: Greg KH @ 2026-07-08  5:29 UTC (permalink / raw)
  To: FUJITA Tomonori
  Cc: dakr, ojeda, a.hindborg, acourbot, aliceryhl, bjorn3_gh, boqun,
	daniel.almeida, gary, lossin, tamird, tmgross, work,
	rust-for-linux, fujita.tomonori

On Wed, Jul 08, 2026 at 07:48:59AM +0900, FUJITA Tomonori wrote:
> On Tue, 7 Jul 2026 17:20:10 +0200
> Greg KH <gregkh@linuxfoundation.org> wrote:
> 
> > On Tue, Jul 07, 2026 at 04:51:40PM +0200, Danilo Krummrich wrote:
> >> On Tue Jul 7, 2026 at 4:30 PM CEST, FUJITA Tomonori wrote:
> >> > Use of this macro is heavily discouraged. Prefer warn_on() macro with
> >> > recovery code where feasible. See the documentation for C's BUG_ON()
> >> > for guidance on when it is rarely justified.
> >> 
> >> Given that, can you please spell out the motivation for this patch?
> > 
> > I agree, this should probably NOT be added unless there is a real user
> > for it that requires it and we all agree that crashing the system is the
> > only way out.
> 
> bindings::BUG() is already in use today, indirectly, from the kernel
> crate itself and from drivers such as binder and nova-core, via
> panic!()/.exepct().unwrap() on invariants that "can't happen". All of
> those funnel through panic() in kernel/lib.rs (#[panic_handler]),
> which itself calls BUG().
> 
> The motivation for this patch is narrow: replace that bindings::BUG()
> call in lib.rs's panic() with bug_on!(), for a somewhat better
> trace. It isn't adding a new decision to crash the system -- that
> decision is already made at each of the existing panic!()/.expect()
> call sites.

That wasn't obvious that this was the reason why this change was being
introduced, perhaps the changelog should have said that?

thanks,

greg k-h

^ permalink raw reply	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2026-07-08  5:29 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-07-07 14:30 [PATCH v1] rust: bug: Add bug_on macro FUJITA Tomonori
2026-07-07 14:51 ` Danilo Krummrich
2026-07-07 15:20   ` Greg KH
2026-07-07 22:48     ` FUJITA Tomonori
2026-07-08  5:29       ` Greg KH

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox