Skip to contentSkip to conversation

rust: Add compile-time overlap checking for bitfield! and register!

RFC PATCH In review Boming Kong 5 participants 10 messages Nov 30 – Dec 2

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

cover rust: Add compile-time overlap checking for bitfield! and register!

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(-)
Signature · 1 line
2.56.1
#1 lore raw

RFC PATCH 1/2 rust: bitfield: added optional overlap argument for bitfield!

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

---
 rust/kernel/bitfield.rs | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)
rust/kernel/bitfield.rs +23 -3
index 8d7d781753..9d9852a7fe 100644
@@ -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)]
Signature · 1 line
2.56.1
#2 lore raw

RFC PATCH 2/2 rust: io: register: implemented overlap flag inside register!

In reply to Boming Kong

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.

---
 rust/macros/io/register.rs | 24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)
rust/macros/io/register.rs +17 -7
index 420c3ad052..4422095787 100644
@@ -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
                 );
             ));
         }
Signature · 1 line
2.56.1
#3 lore raw
In reply to Boming Kong
Quoted 4 lines · Boming Kong

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.

Quoted 6 lines

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.

Thanks!

Cheers,
Miguel

#4 lore raw

(Resending as plain text, the list rejected my previous reply as html. Sorry for the duplicate.)

Quoted 4 lines

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.

Quoted 5 lines

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.

Will do, thanks.

Quoted 33 lines · Miguel Ojeda
Quoted 4 lines · Boming Kong

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.

Quoted 6 lines

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.

Thanks!

Cheers,
Miguel

#5 lore raw
In reply to Miguel Ojeda
Quoted 6 lines · Miguel Ojeda
Quoted 4 lines · Boming Kong

I propose adding optional overlap checking to bitfield! and enabling it by default in register!, while keeping it disabled by default in bitfield!

Quoted 8 lines

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?

#6 lore raw
Quoted 3 lines

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?

Hi Alexandre,

Sure, I can do that.

The syntax off top of my head would looks like this:

#[overlapping]
53:8 table_frame_sys => Pfn;
#[overlapping]
32:8 table_frame_vid => Pfn;

where table_frame_sys and table_frame_vid would escape checks.

Quoted 26 lines · Alexandre Courbot
Quoted 6 lines · Miguel Ojeda
Quoted 4 lines · Boming Kong

I propose adding optional overlap checking to bitfield! and enabling it by default in register!, while keeping it disabled by default in bitfield!

Quoted 8 lines

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?

#7 lore raw
Quoted 8 lines · Boming Kong
Quoted 3 lines

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?

Hi Alexandre,

Sure, I can do that.

Quoted 8 lines

The syntax off top of my head would looks like this:

#[overlapping]
53:8 table_frame_sys => Pfn;
#[overlapping]
32:8 table_frame_vid => Pfn;

where table_frame_sys and table_frame_vid would escape checks.

That's the idea yes, although maybe only the second field needs to be tagged in that case.

I'm not sure if declarative macros allow that syntax easily, but if they do then it would be perfect.

Thanks!

reviewer
#8 lore raw
Quoted 16 lines · Alexandre Courbot
Quoted 15 lines · Boming Kong
Quoted 3 lines

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?

Hi Alexandre,

Sure, I can do that.

The syntax off top of my head would looks like this:

#[overlapping]
53:8 table_frame_sys => Pfn;
#[overlapping]
32:8 table_frame_vid => Pfn;

Quoted 4 lines
Quoted 1 line

where table_frame_sys and table_frame_vid would escape checks.

That's the idea yes, although maybe only the second field needs to be tagged in that case.

I'd prefer the order to stay unimportant. So perhaps we can define this as "#[overlapping]" fields are not checked instead of "second field that overlaps need to be marked as #[overlapping]".

So in this case, you'd want to annotate the larger-sized one, i.e.

    #[overlapping]
    53:8 table_frame_sys => Pfn;
    32:8 table_frame_vid => Pfn;

So if a field overlaps with two other fields, you only need to mark the single field (in the devfn case of PCI_DEVID, if we were to introduce devfn, only the devfn one is marked, regardless placement).

Best,
Gary

#9 lore raw
Quoted 26 lines · Gary Guo
Quoted 16 lines · Alexandre Courbot
Quoted 15 lines · Boming Kong
Quoted 3 lines

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?

Hi Alexandre,

Sure, I can do that.

The syntax off top of my head would looks like this:

#[overlapping]
53:8 table_frame_sys => Pfn;
#[overlapping]
32:8 table_frame_vid => Pfn;

Quoted 4 lines
Quoted 1 line

where table_frame_sys and table_frame_vid would escape checks.

That's the idea yes, although maybe only the second field needs to be tagged in that case.

I'd prefer the order to stay unimportant. So perhaps we can define this as "#[overlapping]" fields are not checked instead of "second field that overlaps need to be marked as #[overlapping]".

Quoted 5 lines

So in this case, you'd want to annotate the larger-sized one, i.e.

    #[overlapping]
    53:8 table_frame_sys => Pfn;
    32:8 table_frame_vid => Pfn;

It's not overlapping, it's embedding, and it should not be restricted or require any special annotation because it's a common practice.

The true overlapping is something like:

    53:8 table_frame_sys => Pfn;
    32:0 table_frame_vid => Pfn;

I agree that overlapping is weird to some extent. Let's maybe restrict it unless user explicitly mentions fields that do overlap:

#[overlaps: foo, bar, baz]

Thanks,
Yury