Rust for Linux List
 help / color / mirror / Atom feed
* [PATCH v2] rust: bitfield: implement compile-time bitfield! overlap check
@ 2026-12-04  3:48 Boming Kong
  0 siblings, 0 replies; only message 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] only message in thread

only message in thread, other threads:[~2026-12-04  3:48 UTC | newest]

Thread overview: (only message) (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

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