NVIDIA GPU driver infrastructure
 help / color / mirror / Atom feed
* [PATCH v2] rust: bitfield: implement compile-time bitfield! overlap check
@ 2026-12-04  3:48 Boming Kong
  2026-12-04  4:04 ` sashiko-bot
  0 siblings, 1 reply; 2+ messages in thread
From: Boming Kong @ 2026-12-04  3:48 UTC (permalink / raw)
  To: rust-for-linux
  Cc: ojeda, acourbot, gary, Boming Kong, Danilo Krummrich, Alice Ryhl,
	David Airlie, Simona Vetter, Yury Norov, Boqun Feng,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Trevor Gross, Daniel Almeida, Tamir Duberstein, Onur Özkan,
	Greg Kroah-Hartman, Jakub Kicinski, Alex Deucher, Andrew Morton,
	Jens Axboe, nova-gpu, dri-devel

This commit implemented compile-time bitfield! overlapping check to avoid
unintended overlaps between fields within a bitfield! and cause subtle
driver bug.

This commit also introduce per-field #[allow_overlap] for user to
opt-out overlap checks.

Updated nova-core's MMU ver2.rs PDE and PTE definition to adapt this new
function.

As register! builds upon bitfield!, it inherits overlap checking without
requiring changes to it's own implementation

Previous discussion: https://lore.kernel.org/rust-for-linux/20261130081359.158313-1-michaelkongboming@gmail.com/

Signed-off-by: Boming Kong <michaelkongboming@gmail.com>
---

Changes in v2:
- Enable overlap checking by default.
- Introduce per-field #[allow_overlap]
- Update affected nova-core mmu v2 definitions and existing tests.
- Drop the separate register! patch, as register! now inherits
  overlap checking from bitfield!.

Note: overlapping fields without #[allow_overlap] would fail to compile
as intended, but KUnit cannot reveal this case so I verified it
manually. Is this acceptable or are there any preferred ways to test
this scenario?

 drivers/gpu/nova-core/mm/pagetable/ver2.rs |  2 ++
 rust/kernel/bitfield.rs                    | 38 ++++++++++++++++++++--
 2 files changed, 38 insertions(+), 2 deletions(-)

diff --git a/drivers/gpu/nova-core/mm/pagetable/ver2.rs b/drivers/gpu/nova-core/mm/pagetable/ver2.rs
index d7169a0fcf..59f6f40c88 100644
--- a/drivers/gpu/nova-core/mm/pagetable/ver2.rs
+++ b/drivers/gpu/nova-core/mm/pagetable/ver2.rs
@@ -109,6 +109,7 @@ pub(in crate::mm) struct Pte(u64) {
         /// Atomic operations disabled.
         7:7     atomic_disable;
         /// Frame number for system memory.
+        #[allow_overlap]
         53:8    frame_number_sys => Pfn;
         /// Frame number for video memory.
         32:8    frame_number_vid => Pfn;
@@ -171,6 +172,7 @@ pub(in crate::mm) struct Pde(u64) {
         /// Disable Address Translation Services.
         5:5     no_ats;
         /// Table frame number for system memory.
+        #[allow_overlap]
         53:8    table_frame_sys => Pfn;
         /// Table frame number for video memory.
         32:8    table_frame_vid => Pfn;
diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
index 8d7d781753..fe67cfe9a4 100644
--- a/rust/kernel/bitfield.rs
+++ b/rust/kernel/bitfield.rs
@@ -359,7 +359,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 {
-        $($(#[doc = $doc:expr])* $hi:literal:$lo:literal $field:ident
+        $($(#[$attr:ident $(= $doc:expr)?])* $hi:literal:$lo:literal $field:ident
             $(?=> $try_into_type:ty)?
             $(=> $into_type:ty)?
         ;
@@ -371,7 +371,7 @@ impl $name {
         $(
         $crate::bitfield!(@private_field_accessors $vis $name $storage : $hi:$lo $field);
         $crate::bitfield!(
-            @public_field_accessors $(#[doc = $doc])* $vis $name $storage : $hi:$lo $field
+            @public_field_accessors $($(#[doc = $doc])?)* $vis $name $storage : $hi:$lo $field
             $(?=> $try_into_type)?
             $(=> $into_type)?
         );
@@ -379,6 +379,9 @@ impl $name {
         }
 
         $crate::bitfield!(@debug $name { $($field;)* });
+        $crate::bitfield!(@lohi_chk $name $storage {
+            $($(#[$attr $(= $doc)?])* $field;)*
+        });
     };
 
     // Private field accessors working with the exact `Bounded` type for the field.
@@ -540,6 +543,35 @@ const fn [<__with_ $field>](
         );
     };
 
+    (@allow_overlap doc = $doc:expr) => { false };
+    (@allow_overlap allow_overlap) => { true };
+
+    (@lohi_chk $name:ident $storage:ty {
+        $($(#[$attr:ident $(= $doc:expr)?])* $field:ident;)*
+    }) => {
+        ::kernel::macros::paste!(
+        const _: () = {
+            let masks: &[$storage] = &[
+                $(if false $(|| $crate::bitfield!(@allow_overlap $attr $(= $doc)?))* {
+                    0
+                } else {
+                    $name::[<$field:upper _MASK>]
+                }),*
+            ];
+            let err_msg: &[&str] = &[
+                $(concat!(stringify!($field), " overlaps a previous field")),*
+            ];
+            let mut used: $storage = 0;
+            let mut i = 0;
+            while i < masks.len() {
+                ::core::assert!(used & masks[i] == 0, "{}", err_msg[i]);
+                used |= masks[i];
+                i += 1;
+            }
+        };
+        );
+    };
+
     // `Debug` implementation.
     (@debug $name:ident { $($field:ident;)* }) => {
         impl ::kernel::fmt::Debug for $name {
@@ -637,6 +669,7 @@ struct TestU64(u64) {
         struct TestU16(u16) {
             15:8      field_15_8;
             7:4       field_7_4; // Partial overlap with `field_5_4`.
+            #[allow_overlap]
             5:4       field_5_4 => Priority;
             3:1       field_3_1;
             0:0       field_0;
@@ -645,6 +678,7 @@ struct TestU16(u16) {
 
     bitfield! {
         struct TestU8(u8) {
+            #[allow_overlap]
             7:0       field_7_0; // Full byte overlap.
             7:4       field_7_4;
             3:2       field_3_2;
-- 
2.56.1


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

* Re: [PATCH v2] rust: bitfield: implement compile-time bitfield! overlap check
  2026-12-04  3:48 [PATCH v2] rust: bitfield: implement compile-time bitfield! overlap check Boming Kong
@ 2026-12-04  4:04 ` sashiko-bot
  0 siblings, 0 replies; 2+ messages in thread
From: sashiko-bot @ 2026-12-04  4:04 UTC (permalink / raw)
  To: Boming Kong
  Cc: ojeda, Alexandre Courbot, gary, Danilo Krummrich, Alice Ryhl,
	David Airlie, Simona Vetter, Yury Norov, Boqun Feng,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Trevor Gross, Daniel Almeida, Tamir Duberstein, Onur Özkan,
	Greg Kroah-Hartman, Jakub Kicinski, Alex Deucher, Andrew Morton,
	Jens Axboe, nova-gpu, dri-devel

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Medium] rust: bitfield: allow_overlap zeroes mask and hides unrelated
  overlaps
- [Low] rust: bitfield: missing docs for overlap check and allow_overlap
- [Low] rust: bitfield: unchecked field attr doc forwarding and misnamed
  @lohi_chk
--

commit 4bf24af3cd86e778bdc829070073575d0ee69450
Author: Boming Kong <michaelkongboming@gmail.com>

rust: bitfield: implement compile-time bitfield! overlap check

This commit adds compile-time overlap checking to bitfield! (and register!
by inheritance), introduces a per-field #[allow_overlap] opt-out, and
updates nova-core MMU v2 page table definitions and bitfield tests.

> diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
> index 8d7d781753363..fe67cfe9a44ad 100644
> --- a/rust/kernel/bitfield.rs
> +++ b/rust/kernel/bitfield.rs
> @@ -359,7 +359,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 {
> -        $($(#[doc = $doc:expr])* $hi:literal:$lo:literal $field:ident
> +        $($(#[$attr:ident $(= $doc:expr)?])* $hi:literal:$lo:literal $field:ident
>              $(?=> $try_into_type:ty)?
>              $(=> $into_type:ty)?
>          ;
> @@ -371,7 +371,7 @@ impl $name {
>          $(
>          $crate::bitfield!(@private_field_accessors $vis $name $storage : $hi:$lo $field);
>          $crate::bitfield!(
> -            @public_field_accessors $(#[doc = $doc])* $vis $name $storage : $hi:$lo $field
> +            @public_field_accessors $($(#[doc = $doc])?)* $vis $name $storage : $hi:$lo $field
>              $(?=> $try_into_type)?
>              $(=> $into_type)?
>          );
> @@ -379,6 +379,9 @@ impl $name {
>          }
>  
>          $crate::bitfield!(@debug $name { $($field;)* });
> +        $crate::bitfield!(@lohi_chk $name $storage {
> +            $($(#[$attr $(= $doc)?])* $field;)*
> +        });
>      };

[Severity: Low]
Should @fields match doc = $doc:expr and allow_overlap explicitly instead
of rewriting any key-value attribute into #[doc = $doc]?  A malformed
#[allow_overlap = true] gets expanded as #[doc = true] on every public
accessor, causing spurious doc errors alongside the @allow_overlap error.

Also, @lohi_chk is a misleading name since it checks mask overlap rather
than lo/hi ordering, and both @allow_overlap and @lohi_chk omit the
descriptive comments present on the other helper arms in bitfield!.

[ ... ]

> @@ -540,6 +543,35 @@ const fn [<__with_ $field>](
>          );
>      };
>  
> +    (@allow_overlap doc = $doc:expr) => { false };
> +    (@allow_overlap allow_overlap) => { true };

[Severity: Low]
Should the bitfield! syntax documentation in rust/kernel/bitfield.rs (and
rust/kernel/io/register.rs, which inherits this behavior) be updated to
describe the default compile-time overlap check and the #[allow_overlap]
field attribute?

> +    (@lohi_chk $name:ident $storage:ty {
> +        $($(#[$attr:ident $(= $doc:expr)?])* $field:ident;)*
> +    }) => {
> +        ::kernel::macros::paste!(
> +        const _: () = {
> +            let masks: &[$storage] = &[
> +                $(if false $(|| $crate::bitfield!(@allow_overlap $attr $(= $doc)?))* {
> +                    0
> +                } else {
> +                    $name::[<$field:upper _MASK>]
> +                }),*
> +            ];
> +            let err_msg: &[&str] = &[
> +                $(concat!(stringify!($field), " overlaps a previous field")),*
> +            ];
> +            let mut used: $storage = 0;
> +            let mut i = 0;
> +            while i < masks.len() {
> +                ::core::assert!(used & masks[i] == 0, "{}", err_msg[i]);
> +                used |= masks[i];
> +                i += 1;
> +            }
> +        };
> +        );
> +    };

[Severity: Medium]
Does zeroing the mask for #[allow_overlap] fields disable overlap checks
for unrelated fields in both directions?

Because the mask becomes 0, the annotated field is never checked against
earlier fields, and none of its bits are recorded in used for later
unannotated fields.  In nova-core's Pde, table_frame_sys (53:8) carries
#[allow_overlap], so a typo colliding with no_ats (5:5) would compile.

In the same Pde, table_frame_vid (32:8) and peer_id (35:33) leave bits
53:36 unset in used, so a new unannotated field there would silently
overlap table_frame_sys.  Scoping the opt-out to intended overlapping
partners or a mutually exclusive group would keep checking the other bits.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261204034830.117532-1-michaelkongboming@gmail.com?part=1

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

end of thread, other threads:[~2026-12-04  4:04 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-04  3:48 [PATCH v2] rust: bitfield: implement compile-time bitfield! overlap check Boming Kong
2026-12-04  4:04 ` sashiko-bot

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