Rust for Linux List
 help / color / mirror / Atom feed
* [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register!
@ 2026-11-30  8:13 Boming Kong
  2026-11-30  8:13 ` [RFC PATCH 1/2] rust: bitfield: added optional overlap argument for bitfield! Boming Kong
                   ` (2 more replies)
  0 siblings, 3 replies; 6+ messages in thread
From: Boming Kong @ 2026-11-30  8:13 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Boming Kong, Alexandre Courbot, Yury Norov, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
	Daniel Almeida, Tamir Duberstein, Onur Özkan, driver-core

This RFC proposes adding optional compile-time overlap checking for
bitfield! and register! to reject overlapping fields.

Currently, register! does not check whether user-defined bitfield
overlap. Accidental overlaps may lead to unintended modification of
other fields and introduce driver bugs. For example:

register! {
    base: Region<0x1000>;
    pub CONFIG(u32) @ 0x100 {
        7:0 mode;
        11:4 index;
    }
}

Modifying either field may unintentionally affect the other, as they
share bits 7:4.

I propose adding optional overlap checking to bitfield! and enabling
it by default in register!, while keeping it disabled by default in
bitfield!. Users can explicitly enable or disable the check like:


// This code will not compile
register! {
    base: Region<0x1000>;
    pub CONFIG(u32, overlap=false) @ 0x100 {
        7:0 mode;
        11:4 index;
    }
}

The validation would reuse the existing field masks and be performed
entirely at compile time, introducing no runtime overhead.

Although some hardware registers intentionally provide multiple
interpretations of the same register, these could be represented
using register aliases. Mixing different interpretations within a
single register definition may make the code more error-prone.

Do you think this is a useful feature to add?

Prior discussion:
Overlapping fields were previously discussed and confirmed to be an
intentional feature [1]. This proposal preserves that functionality
while allowing accidental overlaps to be detected if user request for
overlapping check.

[1] https://lkml.iu.edu/hypermail/linux/kernel/2510.0/05029.html


Boming Kong (2):
  added optional overlap argument for bitfield!
  implemented overlap flag inside register!

 rust/kernel/bitfield.rs    | 26 +++++++++++++++++++++++---
 rust/macros/io/register.rs | 24 +++++++++++++++++-------
 2 files changed, 40 insertions(+), 10 deletions(-)

-- 
2.56.1


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

* [RFC PATCH 1/2] rust: bitfield: added optional overlap argument for bitfield!
  2026-11-30  8:13 [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register! Boming Kong
@ 2026-11-30  8:13 ` Boming Kong
  2026-11-30  8:13 ` [RFC PATCH 2/2] rust: io: register: implemented overlap flag inside register! Boming Kong
  2026-11-30 10:34 ` [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register! Miguel Ojeda
  2 siblings, 0 replies; 6+ messages in thread
From: Boming Kong @ 2026-11-30  8:13 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Boming Kong, Alexandre Courbot, Yury Norov, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
	Daniel Almeida, Tamir Duberstein, Onur Özkan, driver-core

Implement bit range overlap check inside bitfield!, set default to
true to stay the same as current implementation

Signed-off-by: Boming Kong <michaelkongboming@gmail.com>
---
 rust/kernel/bitfield.rs | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)

diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
index 8d7d781753..9d9852a7fe 100644
--- a/rust/kernel/bitfield.rs
+++ b/rust/kernel/bitfield.rs
@@ -292,12 +292,12 @@
 macro_rules! bitfield {
     // Entry point defining the bitfield struct, its implementations and its field accessors.
     (
-        $(#[$attr:meta])* $vis:vis struct $name:ident($storage:ty) { $($fields:tt)* }
+        $(#[$attr:meta])* $vis:vis struct $name:ident($storage:ty $(, overlap = $overlap:literal)?) { $($fields:tt)* }
     ) => {
         $crate::bitfield!(@core
             $(#[$attr])* $vis $name $storage
         );
-        $crate::bitfield!(@fields $vis $name $storage { $($fields)* });
+        $crate::bitfield!(@fields $vis $name $storage $(, overlap = $overlap)? { $($fields)* });
     };
 
     // All rules below are helpers.
@@ -358,7 +358,7 @@ unsafe impl $crate::mem::AsReprMut for $name {}
 
     // Definitions requiring knowledge of individual fields: private and public field accessors,
     // and `Debug` implementation.
-    (@fields $vis:vis $name:ident $storage:ty {
+    (@fields $vis:vis $name:ident $storage:ty $(, overlap = $overlap:literal)? {
         $($(#[doc = $doc:expr])* $hi:literal:$lo:literal $field:ident
             $(?=> $try_into_type:ty)?
             $(=> $into_type:ty)?
@@ -379,6 +379,7 @@ impl $name {
         }
 
         $crate::bitfield!(@debug $name { $($field;)* });
+        $crate::bitfield!(@lohi_chk $name $storage $(, overlap = $overlap)? { $($field;)* });
     };
 
     // Private field accessors working with the exact `Bounded` type for the field.
@@ -554,6 +555,25 @@ fn fmt(&self, f: &mut ::kernel::fmt::Formatter<'_>) -> ::kernel::fmt::Result {
             }
         }
     };
+
+    (@lohi_chk $name:ident $storage:ty { $($field:ident;)* }) => {};
+    (@lohi_chk $name:ident $storage:ty, overlap = $overlap:literal { $($field:ident;)* }) => {
+        ::kernel::macros::paste!(
+        const _: () = {
+            let overlap: bool = $overlap;
+            if !overlap {
+                let masks: &[$storage] = &[$($name::[<$field:upper _MASK>]),*];
+                let mut used: $storage = 0;
+                let mut i = 0;
+                while i < masks.len() {
+                    ::core::assert!(used & masks[i] == 0, "bitfields overlap");
+                    used |= masks[i];
+                    i += 1;
+                }
+            }
+        };
+        );
+    };
 }
 
 #[cfg(CONFIG_RUST_BITFIELD_KUNIT_TEST)]
-- 
2.56.1


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

* [RFC PATCH 2/2] rust: io: register: implemented overlap flag inside register!
  2026-11-30  8:13 [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register! Boming Kong
  2026-11-30  8:13 ` [RFC PATCH 1/2] rust: bitfield: added optional overlap argument for bitfield! Boming Kong
@ 2026-11-30  8:13 ` Boming Kong
  2026-11-30 10:34 ` [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register! Miguel Ojeda
  2 siblings, 0 replies; 6+ messages in thread
From: Boming Kong @ 2026-11-30  8:13 UTC (permalink / raw)
  To: rust-for-linux
  Cc: Boming Kong, Alexandre Courbot, Yury Norov, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
	Daniel Almeida, Tamir Duberstein, Onur Özkan, driver-core

Added overlap flag inside register parser so it can generate bitfields!
with overlap=false to trigger bitfields check. register! default use
overlap=false but user can still change it back if overlapping is
intended.

Signed-off-by: Boming Kong <michaelkongboming@gmail.com>
---
 rust/macros/io/register.rs | 24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)

diff --git a/rust/macros/io/register.rs b/rust/macros/io/register.rs
index 420c3ad052..4422095787 100644
--- a/rust/macros/io/register.rs
+++ b/rust/macros/io/register.rs
@@ -23,6 +23,7 @@
     Error,
     Expr,
     Ident,
+    LitBool,
     Path,
     Result,
     Token,
@@ -32,6 +33,7 @@
 
 mod kw {
     syn::custom_keyword!(base);
+    syn::custom_keyword!(overlap);
     syn::custom_keyword!(stride);
 }
 
@@ -67,7 +69,7 @@ struct Reg {
     ty: Type,
     array: Option<RegArrayDef>,
     offset: RegOffset,
-    bitfield: Option<(Type, Group)>,
+    bitfield: Option<(Type, Group, bool)>,
 }
 
 impl Parse for Reg {
@@ -77,7 +79,7 @@ fn parse(input: syn::parse::ParseStream<'_>) -> Result<Self> {
         let name = input.parse()?;
 
         let lh = input.lookahead1();
-        let (unique, ty, bitfield_storage) = if lh.peek(Token![:]) {
+        let (unique, ty, bitfield_storage, overlap) = if lh.peek(Token![:]) {
             let _: Token![:] = input.parse()?;
 
             let mut attrs = input.call(Attribute::parse_outer)?;
@@ -89,14 +91,22 @@ fn parse(input: syn::parse::ParseStream<'_>) -> Result<Self> {
                 Err(Error::new_spanned(&attrs[0], "unexpected attributes"))?
             }
 
-            (unique, input.parse()?, None)
+            (unique, input.parse()?, None, false)
         } else if lh.peek(token::Paren) {
             let content;
             parenthesized!(content in input);
             let bitfield_storage = Some(content.parse()?);
+            let is_overlap = if content.peek(Token![,]) {
+                let _: Token![,] = content.parse()?;
+                let _: kw::overlap = content.parse()?;
+                let _: Token![=] = content.parse()?;
+                content.parse::<LitBool>()?.value
+            } else {
+                false
+            };
 
             // For bitfields, bitfield macro will generate a type with the same name as `name`.
-            (true, parse_quote!(#name), bitfield_storage)
+            (true, parse_quote!(#name), bitfield_storage, is_overlap)
         } else {
             Err(lh.error())?
         };
@@ -151,7 +161,7 @@ fn parse(input: syn::parse::ParseStream<'_>) -> Result<Self> {
             } else {
                 Err(lh.error())?
             };
-            Some((storage, args))
+            Some((storage, args, overlap))
         } else {
             let _: Token![;] = input.parse()?;
             None
@@ -230,13 +240,13 @@ pub(crate) fn register(def: RegDef) -> Result<TokenStream> {
             }
         };
 
-        if let Some((storage, args)) = &bitfield {
+        if let Some((storage, args, is_overlap)) = &bitfield {
             outputs.extend(quote_spanned!(span =>
                 ::kernel::bitfield!(
                     // `#[allow(non_camel_case_types)]` is added since register names typically use
                     // `SCREAMING_CASE`.
                     #[allow(non_camel_case_types)]
-                    #(#attrs)* #vis struct #name(#storage) #args
+                    #(#attrs)* #vis struct #name(#storage, overlap=#is_overlap) #args
                 );
             ));
         }
-- 
2.56.1


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

* Re: [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register!
  2026-11-30  8:13 [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register! Boming Kong
  2026-11-30  8:13 ` [RFC PATCH 1/2] rust: bitfield: added optional overlap argument for bitfield! Boming Kong
  2026-11-30  8:13 ` [RFC PATCH 2/2] rust: io: register: implemented overlap flag inside register! Boming Kong
@ 2026-11-30 10:34 ` Miguel Ojeda
  2026-11-30 17:31   ` Boming Kong
  2026-12-02  6:23   ` Alexandre Courbot
  2 siblings, 2 replies; 6+ messages in thread
From: Miguel Ojeda @ 2026-11-30 10:34 UTC (permalink / raw)
  To: Boming Kong
  Cc: rust-for-linux, Alexandre Courbot, Yury Norov, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
	Daniel Almeida, Tamir Duberstein, Onur Özkan, driver-core

On Mon, Nov 30, 2026 at 9:14 AM Boming Kong <michaelkongboming@gmail.com> wrote:
>
> I propose adding optional overlap checking to bitfield! and enabling
> it by default in register!, while keeping it disabled by default in
> bitfield!

Hmm... Why would we keep it disabled by default for `bitfield!`?

The commit says it is because it is the current behavior, but if the
check makes sense to have by default to avoid mistakes, then it can be
changed at the same time.

Alexandre said it is a feature, but how common is overlapping expected
to be? That is what should drive the decision, I would say.

> Overlapping fields were previously discussed and confirmed to be an
> intentional feature [1]. This proposal preserves that functionality
> while allowing accidental overlaps to be detected if user request for
> overlapping check.
>
> [1] https://lkml.iu.edu/hypermail/linux/kernel/2510.0/05029.html

Please use lore.kernel.org for mailing list archive links, and add
some context of this context to the commit(s) implementing it, ideally
including Link, e.g.

Link: https://lore.kernel.org/rust-for-linux/DDBW1JYMK8Y7.37R0EJR5VFEO4@nvidia.com/

Thanks!

Cheers,
Miguel

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

* Re: [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register!
  2026-11-30 10:34 ` [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register! Miguel Ojeda
@ 2026-11-30 17:31   ` Boming Kong
  2026-12-02  6:23   ` Alexandre Courbot
  1 sibling, 0 replies; 6+ messages in thread
From: Boming Kong @ 2026-11-30 17:31 UTC (permalink / raw)
  To: Miguel Ojeda
  Cc: rust-for-linux, Alexandre Courbot, Yury Norov, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, Danilo Krummrich,
	Daniel Almeida, Tamir Duberstein, Onur Özkan, driver-core

(Resending as plain text, the list rejected my previous reply as html.
Sorry for the duplicate.)
> Hmm... Why would we keep it disabled by default for `bitfield!`?
>
> Alexandre said it is a feature, but how common is overlapping expected
> to be? That is what should drive the decision, I would say.

Hi Miguel,

Thanks for having a look.

I checked by temporarily enabling the check for all `bitfield!` and
`register!` uses and builds the tree with the Rust drivers and samples
enabled. The only place with intentionally overlapping fields is in
drivers/gpu/nova-core/mm/pagetable/ver2.rs, where:

// Page Directory Entry (PDE) for MMU v2 - 64-bit entry at levels 0-2.
...
53:8    table_frame_sys => Pfn;
/// Table frame number for video memory.
32:8    table_frame_vid => Pfn;

I also found a kunit test in rust/kernel/bitfield.rs called
test_overlapping_fields() which explicitly tests overlapping fields. I
assume it's the intended default behavior, so I kept the check off by
default to stay consistent with it. But I agree the check should be on
by default, since the majority of bitfield definition don't use
overlapping fields. I will do this in v2, and opt out the `Pde`
definition in ver2.rs and the corresponding KUnit test.

> Please use lore.kernel.org for mailing list archive links, and add
> some context of this context to the commit(s) implementing it, ideally
> including Link, e.g.
>
> Link: https://lore.kernel.org/rust-for-linux/DDBW1JYMK8Y7.37R0EJR5VFEO4@nvidia.com/

Will do, thanks.

On Mon, Nov 30, 2026 at 5:35 AM Miguel Ojeda
<miguel.ojeda.sandonis@gmail.com> wrote:
>
> On Mon, Nov 30, 2026 at 9:14 AM Boming Kong <michaelkongboming@gmail.com> wrote:
> >
> > I propose adding optional overlap checking to bitfield! and enabling
> > it by default in register!, while keeping it disabled by default in
> > bitfield!
>
> Hmm... Why would we keep it disabled by default for `bitfield!`?
>
> The commit says it is because it is the current behavior, but if the
> check makes sense to have by default to avoid mistakes, then it can be
> changed at the same time.
>
> Alexandre said it is a feature, but how common is overlapping expected
> to be? That is what should drive the decision, I would say.
>
> > Overlapping fields were previously discussed and confirmed to be an
> > intentional feature [1]. This proposal preserves that functionality
> > while allowing accidental overlaps to be detected if user request for
> > overlapping check.
> >
> > [1] https://lkml.iu.edu/hypermail/linux/kernel/2510.0/05029.html
>
> Please use lore.kernel.org for mailing list archive links, and add
> some context of this context to the commit(s) implementing it, ideally
> including Link, e.g.
>
> Link: https://lore.kernel.org/rust-for-linux/DDBW1JYMK8Y7.37R0EJR5VFEO4@nvidia.com/
>
> Thanks!
>
> Cheers,
> Miguel

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

* Re: [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register!
  2026-11-30 10:34 ` [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register! Miguel Ojeda
  2026-11-30 17:31   ` Boming Kong
@ 2026-12-02  6:23   ` Alexandre Courbot
  1 sibling, 0 replies; 6+ messages in thread
From: Alexandre Courbot @ 2026-12-02  6:23 UTC (permalink / raw)
  To: Miguel Ojeda
  Cc: Boming Kong, rust-for-linux, Yury Norov, Miguel Ojeda, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Onur Özkan, driver-core

On Mon Nov 30, 2026 at 7:34 PM JST, Miguel Ojeda wrote:
> On Mon, Nov 30, 2026 at 9:14 AM Boming Kong <michaelkongboming@gmail.com> wrote:
>>
>> I propose adding optional overlap checking to bitfield! and enabling
>> it by default in register!, while keeping it disabled by default in
>> bitfield!
>
> Hmm... Why would we keep it disabled by default for `bitfield!`?
>
> The commit says it is because it is the current behavior, but if the
> check makes sense to have by default to avoid mistakes, then it can be
> changed at the same time.
>
> Alexandre said it is a feature, but how common is overlapping expected
> to be? That is what should drive the decision, I would say.

Overlapping is clearly the exception (currently 0 overlapping register
definitions, and only 2 bitfields) so having a safety mechanism enabled
by default does make sense to me.

Ideally the escape hatch should be per-bitfield rather than for the
entire structure. Also some syntax like `#[overlapping]` would be more
idiomatic. Boming, do you think you could produce a v2 that does this,
and turn the overlap check on by default after updating the couple of
bitfields that need an exception?

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

end of thread, other threads:[~2026-12-02  6:23 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-30  8:13 [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register! Boming Kong
2026-11-30  8:13 ` [RFC PATCH 1/2] rust: bitfield: added optional overlap argument for bitfield! Boming Kong
2026-11-30  8:13 ` [RFC PATCH 2/2] rust: io: register: implemented overlap flag inside register! Boming Kong
2026-11-30 10:34 ` [RFC PATCH 0/2] rust: Add compile-time overlap checking for bitfield! and register! Miguel Ojeda
2026-11-30 17:31   ` Boming Kong
2026-12-02  6:23   ` Alexandre Courbot

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