rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/
@ 2025-09-30 14:45 Joel Fernandes
  2025-09-30 14:45 ` [PATCH v5 1/9] nova-core: bitfield: Move bitfield-specific code from register! into new macro Joel Fernandes
                   ` (10 more replies)
  0 siblings, 11 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 14:45 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Joel Fernandes,
	Timur Tabi, joel, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau

Hello!

These patches extract and enhance the bitfield support in the register macro in
nova to define Rust structures with bitfields. It then moves out the bitfield
support into the kenrel crate and further enhances it. This is extremely useful
as it allows clean Rust structure definitions without requiring explicit masks
and shifts.

See [1] example code using it.

[1] https://git.kernel.org/pub/scm/linux/kernel/git/jfern/linux.git/patch/?id=76797b31facae8f1a1be139412c78568df1da9f3

v4 of the patches are at:
https://lore.kernel.org/all/20250920182232.2095101-1-joelagnelf@nvidia.com/

v3 of the patches are at:
https://lore.kernel.org/all/20250909212039.227221-1-joelagnelf@nvidia.com/

v2 of the patches are at:
https://lore.kernel.org/all/20250903215428.1296517-1-joelagnelf@nvidia.com/

v1 of the patches are at:
https://lore.kernel.org/all/20250824135954.2243774-1-joelagnelf@nvidia.com/

v4->v5:
* Added 2 hardening patches to catch the misuse of the API.
* Limited access to the inner value of the struct.
* Fixed kunit tests
* Addressed feedback from lots of folks (Miguel, Alexandre, Yury, Danilo).
* Added Alex tags to most patches.

v3->v4:
* Rebased on -next.
* Added more test cases.
* Added support for fields larger than the struct
  (ex, using 'as u32' for a u8 struct.)

v2->v3:
* Renamed bitstruct to bitfield.
* Various suggestions to improve code (Alex, Yury, Miguel).
* Added reviewed-by tags from Elle Rhumsaa.
* Added KUNIT tests including tests for overlap.
* Added F: maintainers file entry for new files under BITOPS.

v1->v2:
* Use build_assert in bitstruct
* Split move and enhance patches for easier review
* Move out of Nova into kernel crate for other drivers like Tyr which will use.
* Miscellaneous cosmetic improvements.

Joel Fernandes (9):
  nova-core: bitfield: Move bitfield-specific code from register! into
    new macro
  nova-core: bitfield: Add support for different storage widths
  nova-core: bitfield: Add support for custom visiblity
  rust: Move register and bitfield macros out of Nova
  rust: bitfield: Add a new() constructor and raw() accessor
  rust: bitfield: Add KUNIT tests for bitfield
  rust: bitfield: Use 'as' operator for setter type conversion
  rust: bitfield: Add hardening for out of bounds access
  rust: bitfield: Add hardening for undefined bits

 MAINTAINERS                                   |   7 +
 drivers/gpu/nova-core/falcon.rs               |   2 +-
 drivers/gpu/nova-core/falcon/gsp.rs           |   4 +-
 drivers/gpu/nova-core/falcon/sec2.rs          |   2 +-
 drivers/gpu/nova-core/regs.rs                 |   6 +-
 rust/kernel/bitfield.rs                       | 804 ++++++++++++++++++
 rust/kernel/io.rs                             |   1 +
 .../macros.rs => rust/kernel/io/register.rs   | 317 +------
 rust/kernel/lib.rs                            |   1 +
 security/Kconfig.hardening                    |   9 +
 10 files changed, 870 insertions(+), 283 deletions(-)
 create mode 100644 rust/kernel/bitfield.rs
 rename drivers/gpu/nova-core/regs/macros.rs => rust/kernel/io/register.rs (72%)

-- 
2.34.1


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

* [PATCH v5 1/9] nova-core: bitfield: Move bitfield-specific code from register! into new macro
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
@ 2025-09-30 14:45 ` Joel Fernandes
  2025-09-30 14:45 ` [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths Joel Fernandes
                   ` (9 subsequent siblings)
  10 siblings, 0 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 14:45 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Joel Fernandes,
	Timur Tabi, joel, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau

The bitfield-specific into new macro. This will be used to define
structs with bitfields, similar to C language.

Reviewed-by: Elle Rhumsaa <elle@weathered-steel.dev>
Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
---
 drivers/gpu/nova-core/bitfield.rs    | 315 +++++++++++++++++++++++++++
 drivers/gpu/nova-core/nova_core.rs   |   3 +
 drivers/gpu/nova-core/regs/macros.rs | 259 +---------------------
 3 files changed, 328 insertions(+), 249 deletions(-)
 create mode 100644 drivers/gpu/nova-core/bitfield.rs

diff --git a/drivers/gpu/nova-core/bitfield.rs b/drivers/gpu/nova-core/bitfield.rs
new file mode 100644
index 000000000000..b1e1c438b8a8
--- /dev/null
+++ b/drivers/gpu/nova-core/bitfield.rs
@@ -0,0 +1,315 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Bitfield library for Rust structures
+//!
+//! Support for defining bitfields in Rust structures. Also used by the [`register!`] macro.
+//!
+//! # Syntax
+//!
+//! ```rust
+//! use nova_core::bitfield;
+//!
+//! #[derive(Debug, Clone, Copy, Default)]
+//! enum Mode {
+//!     #[default]
+//!     Low = 0,
+//!     High = 1,
+//!     Auto = 2,
+//! }
+//!
+//! impl TryFrom<u8> for Mode {
+//!     type Error = u8;
+//!     fn try_from(value: u8) -> Result<Self, Self::Error> {
+//!         match value {
+//!             0 => Ok(Mode::Low),
+//!             1 => Ok(Mode::High),
+//!             2 => Ok(Mode::Auto),
+//!             _ => Err(value),
+//!         }
+//!     }
+//! }
+//!
+//! impl From<Mode> for u32 {
+//!     fn from(mode: Mode) -> u32 {
+//!         mode as u32
+//!     }
+//! }
+//!
+//! #[derive(Debug, Clone, Copy, Default)]
+//! enum State {
+//!     #[default]
+//!     Inactive = 0,
+//!     Active = 1,
+//! }
+//!
+//! impl From<bool> for State {
+//!     fn from(value: bool) -> Self {
+//!         if value { State::Active } else { State::Inactive }
+//!     }
+//! }
+//!
+//! impl From<State> for u32 {
+//!     fn from(state: State) -> u32 {
+//!         state as u32
+//!     }
+//! }
+//!
+//! bitfield! {
+//!     struct ControlReg {
+//!         3:0 mode as u8 ?=> Mode;
+//!         7:7 state as bool => State;
+//!     }
+//! }
+//! ```
+//!
+//! This generates a struct with:
+//! - Field accessors: `mode()`, `state()`, etc.
+//! - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern).
+//! - Debug and Default implementations.
+//!
+//! Fields are defined as follows:
+//!
+//! - `as <type>` simply returns the field value casted to <type>, typically `u32`, `u16`, `u8` or
+//!   `bool`. Note that `bool` fields must have a range of 1 bit.
+//! - `as <type> => <into_type>` calls `<into_type>`'s `From::<<type>>` implementation and returns
+//!   the result.
+//! - `as <type> ?=> <try_into_type>` calls `<try_into_type>`'s `TryFrom::<<type>>` implementation
+//!   and returns the result. This is useful with fields for which not all values are valid.
+//!
+macro_rules! bitfield {
+    // Main entry point - defines the bitfield struct with fields
+    (struct $name:ident $(, $comment:literal)? { $($fields:tt)* }) => {
+        bitfield!(@core $name $(, $comment)? { $($fields)* });
+    };
+
+    // All rules below are helpers.
+
+    // Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`,
+    // `Default`, `BitOr`, and conversion to the value type) and field accessor methods.
+    (@core $name:ident $(, $comment:literal)? { $($fields:tt)* }) => {
+        $(
+        #[doc=$comment]
+        )?
+        #[repr(transparent)]
+        #[derive(Clone, Copy)]
+        pub(crate) struct $name(u32);
+
+        impl ::core::ops::BitOr for $name {
+            type Output = Self;
+
+            fn bitor(self, rhs: Self) -> Self::Output {
+                Self(self.0 | rhs.0)
+            }
+        }
+
+        impl ::core::convert::From<$name> for u32 {
+            fn from(val: $name) -> u32 {
+                val.0
+            }
+        }
+
+        bitfield!(@fields_dispatcher $name { $($fields)* });
+    };
+
+    // Captures the fields and passes them to all the implementers that require field information.
+    //
+    // Used to simplify the matching rules for implementers, so they don't need to match the entire
+    // complex fields rule even though they only make use of part of it.
+    (@fields_dispatcher $name:ident {
+        $($hi:tt:$lo:tt $field:ident as $type:tt
+            $(?=> $try_into_type:ty)?
+            $(=> $into_type:ty)?
+            $(, $comment:literal)?
+        ;
+        )*
+    }
+    ) => {
+        bitfield!(@field_accessors $name {
+            $(
+                $hi:$lo $field as $type
+                $(?=> $try_into_type)?
+                $(=> $into_type)?
+                $(, $comment)?
+            ;
+            )*
+        });
+        bitfield!(@debug $name { $($field;)* });
+        bitfield!(@default $name { $($field;)* });
+    };
+
+    // Defines all the field getter/setter methods for `$name`.
+    (
+        @field_accessors $name:ident {
+        $($hi:tt:$lo:tt $field:ident as $type:tt
+            $(?=> $try_into_type:ty)?
+            $(=> $into_type:ty)?
+            $(, $comment:literal)?
+        ;
+        )*
+        }
+    ) => {
+        $(
+            bitfield!(@check_field_bounds $hi:$lo $field as $type);
+        )*
+
+        #[allow(dead_code)]
+        impl $name {
+            $(
+            bitfield!(@field_accessor $name $hi:$lo $field as $type
+                $(?=> $try_into_type)?
+                $(=> $into_type)?
+                $(, $comment)?
+                ;
+            );
+            )*
+        }
+    };
+
+    // Boolean fields must have `$hi == $lo`.
+    (@check_field_bounds $hi:tt:$lo:tt $field:ident as bool) => {
+        #[allow(clippy::eq_op)]
+        const _: () = {
+            ::kernel::build_assert!(
+                $hi == $lo,
+                concat!("boolean field `", stringify!($field), "` covers more than one bit")
+            );
+        };
+    };
+
+    // Non-boolean fields must have `$hi >= $lo`.
+    (@check_field_bounds $hi:tt:$lo:tt $field:ident as $type:tt) => {
+        #[allow(clippy::eq_op)]
+        const _: () = {
+            ::kernel::build_assert!(
+                $hi >= $lo,
+                concat!("field `", stringify!($field), "`'s MSB is smaller than its LSB")
+            );
+        };
+    };
+
+    // Catches fields defined as `bool` and convert them into a boolean value.
+    (
+        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool => $into_type:ty
+            $(, $comment:literal)?;
+    ) => {
+        bitfield!(
+            @leaf_accessor $name $hi:$lo $field
+            { |f| <$into_type>::from(if f != 0 { true } else { false }) }
+            $into_type => $into_type $(, $comment)?;
+        );
+    };
+
+    // Shortcut for fields defined as `bool` without the `=>` syntax.
+    (
+        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?;
+    ) => {
+        bitfield!(@field_accessor $name $hi:$lo $field as bool => bool $(, $comment)?;);
+    };
+
+    // Catches the `?=>` syntax for non-boolean fields.
+    (
+        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty
+            $(, $comment:literal)?;
+    ) => {
+        bitfield!(@leaf_accessor $name $hi:$lo $field
+            { |f| <$try_into_type>::try_from(f as $type) } $try_into_type =>
+            ::core::result::Result<
+                $try_into_type,
+                <$try_into_type as ::core::convert::TryFrom<$type>>::Error
+            >
+            $(, $comment)?;);
+    };
+
+    // Catches the `=>` syntax for non-boolean fields.
+    (
+        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty
+            $(, $comment:literal)?;
+    ) => {
+        bitfield!(@leaf_accessor $name $hi:$lo $field
+            { |f| <$into_type>::from(f as $type) } $into_type => $into_type $(, $comment)?;);
+    };
+
+    // Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax.
+    (
+        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt
+            $(, $comment:literal)?;
+    ) => {
+        bitfield!(@field_accessor $name $hi:$lo $field as $type => $type $(, $comment)?;);
+    };
+
+    // Generates the accessor methods for a single field.
+    (
+        @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident
+            { $process:expr } $to_type:ty => $res_type:ty $(, $comment:literal)?;
+    ) => {
+        ::kernel::macros::paste!(
+        const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi;
+        const [<$field:upper _MASK>]: u32 = ((((1 << $hi) - 1) << 1) + 1) - ((1 << $lo) - 1);
+        const [<$field:upper _SHIFT>]: u32 = Self::[<$field:upper _MASK>].trailing_zeros();
+        );
+
+        $(
+        #[doc="Returns the value of this field:"]
+        #[doc=$comment]
+        )?
+        #[inline(always)]
+        pub(crate) fn $field(self) -> $res_type {
+            ::kernel::macros::paste!(
+            const MASK: u32 = $name::[<$field:upper _MASK>];
+            const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
+            );
+            let field = ((self.0 & MASK) >> SHIFT);
+
+            $process(field)
+        }
+
+        ::kernel::macros::paste!(
+        $(
+        #[doc="Sets the value of this field:"]
+        #[doc=$comment]
+        )?
+        #[inline(always)]
+        pub(crate) fn [<set_ $field>](mut self, value: $to_type) -> Self {
+            const MASK: u32 = $name::[<$field:upper _MASK>];
+            const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
+            let value = (u32::from(value) << SHIFT) & MASK;
+            self.0 = (self.0 & !MASK) | value;
+
+            self
+        }
+        );
+    };
+
+    // Generates the `Debug` implementation for `$name`.
+    (@debug $name:ident { $($field:ident;)* }) => {
+        impl ::core::fmt::Debug for $name {
+            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
+                f.debug_struct(stringify!($name))
+                    .field("<raw>", &format_args!("{:#x}", &self.0))
+                $(
+                    .field(stringify!($field), &self.$field())
+                )*
+                    .finish()
+            }
+        }
+    };
+
+    // Generates the `Default` implementation for `$name`.
+    (@default $name:ident { $($field:ident;)* }) => {
+        /// Returns a value for the bitfield where all fields are set to their default value.
+        impl ::core::default::Default for $name {
+            fn default() -> Self {
+                #[allow(unused_mut)]
+                let mut value = Self(Default::default());
+
+                ::kernel::macros::paste!(
+                $(
+                value.[<set_ $field>](Default::default());
+                )*
+                );
+
+                value
+            }
+        }
+    };
+}
diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
index fffcaee2249f..112277c7921e 100644
--- a/drivers/gpu/nova-core/nova_core.rs
+++ b/drivers/gpu/nova-core/nova_core.rs
@@ -2,6 +2,9 @@
 
 //! Nova Core GPU Driver
 
+#[macro_use]
+mod bitfield;
+
 mod dma;
 mod driver;
 mod falcon;
diff --git a/drivers/gpu/nova-core/regs/macros.rs b/drivers/gpu/nova-core/regs/macros.rs
index 754c14ee7f40..945d15a2c529 100644
--- a/drivers/gpu/nova-core/regs/macros.rs
+++ b/drivers/gpu/nova-core/regs/macros.rs
@@ -8,7 +8,8 @@
 //!
 //! The `register!` macro in this module provides an intuitive and readable syntax for defining a
 //! dedicated type for each register. Each such type comes with its own field accessors that can
-//! return an error if a field's value is invalid.
+//! return an error if a field's value is invalid. Please look at the [`bitfield`] macro for the
+//! complete syntax of fields definitions.
 
 /// Trait providing a base address to be added to the offset of a relative register to obtain
 /// its actual offset.
@@ -54,15 +55,6 @@ pub(crate) trait RegisterBase<T> {
 /// BOOT_0::alter(&bar, |r| r.set_major_revision(3).set_minor_revision(10));
 /// ```
 ///
-/// Fields are defined as follows:
-///
-/// - `as <type>` simply returns the field value casted to <type>, typically `u32`, `u16`, `u8` or
-///   `bool`. Note that `bool` fields must have a range of 1 bit.
-/// - `as <type> => <into_type>` calls `<into_type>`'s `From::<<type>>` implementation and returns
-///   the result.
-/// - `as <type> ?=> <try_into_type>` calls `<try_into_type>`'s `TryFrom::<<type>>` implementation
-///   and returns the result. This is useful with fields for which not all values are valid.
-///
 /// The documentation strings are optional. If present, they will be added to the type's
 /// definition, or the field getter and setter methods they are attached to.
 ///
@@ -284,25 +276,25 @@ pub(crate) trait RegisterBase<T> {
 macro_rules! register {
     // Creates a register at a fixed offset of the MMIO space.
     ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)* } ) => {
-        register!(@core $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $offset);
     };
 
     // Creates an alias register of fixed offset register `alias` with its own fields.
     ($name:ident => $alias:ident $(, $comment:literal)? { $($fields:tt)* } ) => {
-        register!(@core $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $alias::OFFSET);
     };
 
     // Creates a register at a relative offset from a base address provider.
     ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $($fields:tt)* } ) => {
-        register!(@core $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $offset ]);
     };
 
     // Creates an alias register of relative offset register `alias` with its own fields.
     ($name:ident => $base:ty [ $alias:ident ] $(, $comment:literal)? { $($fields:tt)* }) => {
-        register!(@core $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $alias::OFFSET ]);
     };
 
@@ -313,7 +305,7 @@ macro_rules! register {
         }
     ) => {
         static_assert!(::core::mem::size_of::<u32>() <= $stride);
-        register!(@core $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name $(, $comment)? { $($fields)* } );
         register!(@io_array $name @ $offset [ $size ; $stride ]);
     };
 
@@ -334,7 +326,7 @@ macro_rules! register {
             $(, $comment:literal)? { $($fields:tt)* }
     ) => {
         static_assert!(::core::mem::size_of::<u32>() <= $stride);
-        register!(@core $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name $(, $comment)? { $($fields)* } );
         register!(@io_relative_array $name @ $base [ $offset [ $size ; $stride ] ]);
     };
 
@@ -356,7 +348,7 @@ macro_rules! register {
         }
     ) => {
         static_assert!($idx < $alias::SIZE);
-        register!(@core $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $alias::OFFSET + $idx * $alias::STRIDE ] );
     };
 
@@ -365,241 +357,10 @@ macro_rules! register {
     // to avoid it being interpreted in place of the relative register array alias rule.
     ($name:ident => $alias:ident [ $idx:expr ] $(, $comment:literal)? { $($fields:tt)* }) => {
         static_assert!($idx < $alias::SIZE);
-        register!(@core $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE );
     };
 
-    // All rules below are helpers.
-
-    // Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`,
-    // `Default`, `BitOr`, and conversion to the value type) and field accessor methods.
-    (@core $name:ident $(, $comment:literal)? { $($fields:tt)* }) => {
-        $(
-        #[doc=$comment]
-        )?
-        #[repr(transparent)]
-        #[derive(Clone, Copy)]
-        pub(crate) struct $name(u32);
-
-        impl ::core::ops::BitOr for $name {
-            type Output = Self;
-
-            fn bitor(self, rhs: Self) -> Self::Output {
-                Self(self.0 | rhs.0)
-            }
-        }
-
-        impl ::core::convert::From<$name> for u32 {
-            fn from(reg: $name) -> u32 {
-                reg.0
-            }
-        }
-
-        register!(@fields_dispatcher $name { $($fields)* });
-    };
-
-    // Captures the fields and passes them to all the implementers that require field information.
-    //
-    // Used to simplify the matching rules for implementers, so they don't need to match the entire
-    // complex fields rule even though they only make use of part of it.
-    (@fields_dispatcher $name:ident {
-        $($hi:tt:$lo:tt $field:ident as $type:tt
-            $(?=> $try_into_type:ty)?
-            $(=> $into_type:ty)?
-            $(, $comment:literal)?
-        ;
-        )*
-    }
-    ) => {
-        register!(@field_accessors $name {
-            $(
-                $hi:$lo $field as $type
-                $(?=> $try_into_type)?
-                $(=> $into_type)?
-                $(, $comment)?
-            ;
-            )*
-        });
-        register!(@debug $name { $($field;)* });
-        register!(@default $name { $($field;)* });
-    };
-
-    // Defines all the field getter/methods methods for `$name`.
-    (
-        @field_accessors $name:ident {
-        $($hi:tt:$lo:tt $field:ident as $type:tt
-            $(?=> $try_into_type:ty)?
-            $(=> $into_type:ty)?
-            $(, $comment:literal)?
-        ;
-        )*
-        }
-    ) => {
-        $(
-            register!(@check_field_bounds $hi:$lo $field as $type);
-        )*
-
-        #[allow(dead_code)]
-        impl $name {
-            $(
-            register!(@field_accessor $name $hi:$lo $field as $type
-                $(?=> $try_into_type)?
-                $(=> $into_type)?
-                $(, $comment)?
-                ;
-            );
-            )*
-        }
-    };
-
-    // Boolean fields must have `$hi == $lo`.
-    (@check_field_bounds $hi:tt:$lo:tt $field:ident as bool) => {
-        #[allow(clippy::eq_op)]
-        const _: () = {
-            ::kernel::build_assert!(
-                $hi == $lo,
-                concat!("boolean field `", stringify!($field), "` covers more than one bit")
-            );
-        };
-    };
-
-    // Non-boolean fields must have `$hi >= $lo`.
-    (@check_field_bounds $hi:tt:$lo:tt $field:ident as $type:tt) => {
-        #[allow(clippy::eq_op)]
-        const _: () = {
-            ::kernel::build_assert!(
-                $hi >= $lo,
-                concat!("field `", stringify!($field), "`'s MSB is smaller than its LSB")
-            );
-        };
-    };
-
-    // Catches fields defined as `bool` and convert them into a boolean value.
-    (
-        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool => $into_type:ty
-            $(, $comment:literal)?;
-    ) => {
-        register!(
-            @leaf_accessor $name $hi:$lo $field
-            { |f| <$into_type>::from(if f != 0 { true } else { false }) }
-            $into_type => $into_type $(, $comment)?;
-        );
-    };
-
-    // Shortcut for fields defined as `bool` without the `=>` syntax.
-    (
-        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?;
-    ) => {
-        register!(@field_accessor $name $hi:$lo $field as bool => bool $(, $comment)?;);
-    };
-
-    // Catches the `?=>` syntax for non-boolean fields.
-    (
-        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty
-            $(, $comment:literal)?;
-    ) => {
-        register!(@leaf_accessor $name $hi:$lo $field
-            { |f| <$try_into_type>::try_from(f as $type) } $try_into_type =>
-            ::core::result::Result<
-                $try_into_type,
-                <$try_into_type as ::core::convert::TryFrom<$type>>::Error
-            >
-            $(, $comment)?;);
-    };
-
-    // Catches the `=>` syntax for non-boolean fields.
-    (
-        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty
-            $(, $comment:literal)?;
-    ) => {
-        register!(@leaf_accessor $name $hi:$lo $field
-            { |f| <$into_type>::from(f as $type) } $into_type => $into_type $(, $comment)?;);
-    };
-
-    // Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax.
-    (
-        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt
-            $(, $comment:literal)?;
-    ) => {
-        register!(@field_accessor $name $hi:$lo $field as $type => $type $(, $comment)?;);
-    };
-
-    // Generates the accessor methods for a single field.
-    (
-        @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident
-            { $process:expr } $to_type:ty => $res_type:ty $(, $comment:literal)?;
-    ) => {
-        ::kernel::macros::paste!(
-        const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi;
-        const [<$field:upper _MASK>]: u32 = ((((1 << $hi) - 1) << 1) + 1) - ((1 << $lo) - 1);
-        const [<$field:upper _SHIFT>]: u32 = Self::[<$field:upper _MASK>].trailing_zeros();
-        );
-
-        $(
-        #[doc="Returns the value of this field:"]
-        #[doc=$comment]
-        )?
-        #[inline(always)]
-        pub(crate) fn $field(self) -> $res_type {
-            ::kernel::macros::paste!(
-            const MASK: u32 = $name::[<$field:upper _MASK>];
-            const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
-            );
-            let field = ((self.0 & MASK) >> SHIFT);
-
-            $process(field)
-        }
-
-        ::kernel::macros::paste!(
-        $(
-        #[doc="Sets the value of this field:"]
-        #[doc=$comment]
-        )?
-        #[inline(always)]
-        pub(crate) fn [<set_ $field>](mut self, value: $to_type) -> Self {
-            const MASK: u32 = $name::[<$field:upper _MASK>];
-            const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
-            let value = (u32::from(value) << SHIFT) & MASK;
-            self.0 = (self.0 & !MASK) | value;
-
-            self
-        }
-        );
-    };
-
-    // Generates the `Debug` implementation for `$name`.
-    (@debug $name:ident { $($field:ident;)* }) => {
-        impl ::core::fmt::Debug for $name {
-            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
-                f.debug_struct(stringify!($name))
-                    .field("<raw>", &format_args!("{:#x}", &self.0))
-                $(
-                    .field(stringify!($field), &self.$field())
-                )*
-                    .finish()
-            }
-        }
-    };
-
-    // Generates the `Default` implementation for `$name`.
-    (@default $name:ident { $($field:ident;)* }) => {
-        /// Returns a value for the register where all fields are set to their default value.
-        impl ::core::default::Default for $name {
-            fn default() -> Self {
-                #[allow(unused_mut)]
-                let mut value = Self(Default::default());
-
-                ::kernel::macros::paste!(
-                $(
-                value.[<set_ $field>](Default::default());
-                )*
-                );
-
-                value
-            }
-        }
-    };
-
     // Generates the IO accessors for a fixed offset register.
     (@io_fixed $name:ident @ $offset:expr) => {
         #[allow(dead_code)]
-- 
2.34.1


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

* [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
  2025-09-30 14:45 ` [PATCH v5 1/9] nova-core: bitfield: Move bitfield-specific code from register! into new macro Joel Fernandes
@ 2025-09-30 14:45 ` Joel Fernandes
  2025-09-30 17:18   ` Joel Fernandes
  2025-10-02  1:17   ` Alexandre Courbot
  2025-09-30 14:45 ` [PATCH v5 3/9] nova-core: bitfield: Add support for custom visiblity Joel Fernandes
                   ` (8 subsequent siblings)
  10 siblings, 2 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 14:45 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Joel Fernandes,
	Timur Tabi, joel, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau

Previously, bitfields were hardcoded to use u32 as the underlying
storage type.  Add support for different storage types (u8, u16, u32,
u64) to the bitfield macro.

New syntax is: struct Name: <type ex., u32> { ... }

Reviewed-by: Elle Rhumsaa <elle@weathered-steel.dev>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
---
 drivers/gpu/nova-core/bitfield.rs    | 210 ++++++++++++++-------------
 drivers/gpu/nova-core/regs/macros.rs |  16 +-
 2 files changed, 119 insertions(+), 107 deletions(-)

diff --git a/drivers/gpu/nova-core/bitfield.rs b/drivers/gpu/nova-core/bitfield.rs
index b1e1c438b8a8..75de1c0fcb3b 100644
--- a/drivers/gpu/nova-core/bitfield.rs
+++ b/drivers/gpu/nova-core/bitfield.rs
@@ -3,96 +3,99 @@
 //! Bitfield library for Rust structures
 //!
 //! Support for defining bitfields in Rust structures. Also used by the [`register!`] macro.
-//!
-//! # Syntax
-//!
-//! ```rust
-//! use nova_core::bitfield;
-//!
-//! #[derive(Debug, Clone, Copy, Default)]
-//! enum Mode {
-//!     #[default]
-//!     Low = 0,
-//!     High = 1,
-//!     Auto = 2,
-//! }
-//!
-//! impl TryFrom<u8> for Mode {
-//!     type Error = u8;
-//!     fn try_from(value: u8) -> Result<Self, Self::Error> {
-//!         match value {
-//!             0 => Ok(Mode::Low),
-//!             1 => Ok(Mode::High),
-//!             2 => Ok(Mode::Auto),
-//!             _ => Err(value),
-//!         }
-//!     }
-//! }
-//!
-//! impl From<Mode> for u32 {
-//!     fn from(mode: Mode) -> u32 {
-//!         mode as u32
-//!     }
-//! }
-//!
-//! #[derive(Debug, Clone, Copy, Default)]
-//! enum State {
-//!     #[default]
-//!     Inactive = 0,
-//!     Active = 1,
-//! }
-//!
-//! impl From<bool> for State {
-//!     fn from(value: bool) -> Self {
-//!         if value { State::Active } else { State::Inactive }
-//!     }
-//! }
-//!
-//! impl From<State> for u32 {
-//!     fn from(state: State) -> u32 {
-//!         state as u32
-//!     }
-//! }
-//!
-//! bitfield! {
-//!     struct ControlReg {
-//!         3:0 mode as u8 ?=> Mode;
-//!         7:7 state as bool => State;
-//!     }
-//! }
-//! ```
-//!
-//! This generates a struct with:
-//! - Field accessors: `mode()`, `state()`, etc.
-//! - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern).
-//! - Debug and Default implementations.
-//!
-//! Fields are defined as follows:
-//!
-//! - `as <type>` simply returns the field value casted to <type>, typically `u32`, `u16`, `u8` or
-//!   `bool`. Note that `bool` fields must have a range of 1 bit.
-//! - `as <type> => <into_type>` calls `<into_type>`'s `From::<<type>>` implementation and returns
-//!   the result.
-//! - `as <type> ?=> <try_into_type>` calls `<try_into_type>`'s `TryFrom::<<type>>` implementation
-//!   and returns the result. This is useful with fields for which not all values are valid.
-//!
+
+/// Defines a struct with accessors to access bits within an inner unsigned integer.
+///
+/// # Syntax
+///
+/// ```rust
+/// use nova_core::bitfield;
+///
+/// #[derive(Debug, Clone, Copy, Default)]
+/// enum Mode {
+///     #[default]
+///     Low = 0,
+///     High = 1,
+///     Auto = 2,
+/// }
+///
+/// impl TryFrom<u8> for Mode {
+///     type Error = u8;
+///     fn try_from(value: u8) -> Result<Self, Self::Error> {
+///         match value {
+///             0 => Ok(Mode::Low),
+///             1 => Ok(Mode::High),
+///             2 => Ok(Mode::Auto),
+///             _ => Err(value),
+///         }
+///     }
+/// }
+///
+/// impl From<Mode> for u32 {
+///     fn from(mode: Mode) -> u32 {
+///         mode as u32
+///     }
+/// }
+///
+/// #[derive(Debug, Clone, Copy, Default)]
+/// enum State {
+///     #[default]
+///     Inactive = 0,
+///     Active = 1,
+/// }
+///
+/// impl From<bool> for State {
+///     fn from(value: bool) -> Self {
+///         if value { State::Active } else { State::Inactive }
+///     }
+/// }
+///
+/// impl From<State> for u32 {
+///     fn from(state: State) -> u32 {
+///         state as u32
+///     }
+/// }
+///
+/// bitfield! {
+///     struct ControlReg(u32) {
+///         3:0 mode as u8 ?=> Mode;
+///         7:7 state as bool => State;
+///     }
+/// }
+/// ```
+///
+/// This generates a struct with:
+/// - Field accessors: `mode()`, `state()`, etc.
+/// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern).
+///   Note that the compiler will error out if the size of the setter's arg exceeds the
+///   struct's storage size.
+/// - Debug and Default implementations.
+///
+/// Fields are defined as follows:
+///
+/// - `as <type>` simply returns the field value casted to <type>, typically `u32`, `u16`, `u8` or
+///   `bool`. Note that `bool` fields must have a range of 1 bit.
+/// - `as <type> => <into_type>` calls `<into_type>`'s `From::<<type>>` implementation and returns
+///   the result.
+/// - `as <type> ?=> <try_into_type>` calls `<try_into_type>`'s `TryFrom::<<type>>` implementation
+///   and returns the result. This is useful with fields for which not all values are valid.
 macro_rules! bitfield {
     // Main entry point - defines the bitfield struct with fields
-    (struct $name:ident $(, $comment:literal)? { $($fields:tt)* }) => {
-        bitfield!(@core $name $(, $comment)? { $($fields)* });
+    (struct $name:ident($storage:ty) $(, $comment:literal)? { $($fields:tt)* }) => {
+        bitfield!(@core $name $storage $(, $comment)? { $($fields)* });
     };
 
     // All rules below are helpers.
 
     // Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`,
     // `Default`, `BitOr`, and conversion to the value type) and field accessor methods.
-    (@core $name:ident $(, $comment:literal)? { $($fields:tt)* }) => {
+    (@core $name:ident $storage:ty $(, $comment:literal)? { $($fields:tt)* }) => {
         $(
         #[doc=$comment]
         )?
         #[repr(transparent)]
         #[derive(Clone, Copy)]
-        pub(crate) struct $name(u32);
+        pub(crate) struct $name($storage);
 
         impl ::core::ops::BitOr for $name {
             type Output = Self;
@@ -102,20 +105,20 @@ fn bitor(self, rhs: Self) -> Self::Output {
             }
         }
 
-        impl ::core::convert::From<$name> for u32 {
-            fn from(val: $name) -> u32 {
+        impl ::core::convert::From<$name> for $storage {
+            fn from(val: $name) -> $storage {
                 val.0
             }
         }
 
-        bitfield!(@fields_dispatcher $name { $($fields)* });
+        bitfield!(@fields_dispatcher $name $storage { $($fields)* });
     };
 
     // Captures the fields and passes them to all the implementers that require field information.
     //
     // Used to simplify the matching rules for implementers, so they don't need to match the entire
     // complex fields rule even though they only make use of part of it.
-    (@fields_dispatcher $name:ident {
+    (@fields_dispatcher $name:ident $storage:ty {
         $($hi:tt:$lo:tt $field:ident as $type:tt
             $(?=> $try_into_type:ty)?
             $(=> $into_type:ty)?
@@ -124,7 +127,7 @@ fn from(val: $name) -> u32 {
         )*
     }
     ) => {
-        bitfield!(@field_accessors $name {
+        bitfield!(@field_accessors $name $storage {
             $(
                 $hi:$lo $field as $type
                 $(?=> $try_into_type)?
@@ -139,7 +142,7 @@ fn from(val: $name) -> u32 {
 
     // Defines all the field getter/setter methods for `$name`.
     (
-        @field_accessors $name:ident {
+        @field_accessors $name:ident $storage:ty {
         $($hi:tt:$lo:tt $field:ident as $type:tt
             $(?=> $try_into_type:ty)?
             $(=> $into_type:ty)?
@@ -155,7 +158,7 @@ fn from(val: $name) -> u32 {
         #[allow(dead_code)]
         impl $name {
             $(
-            bitfield!(@field_accessor $name $hi:$lo $field as $type
+            bitfield!(@field_accessor $name $storage, $hi:$lo $field as $type
                 $(?=> $try_into_type)?
                 $(=> $into_type)?
                 $(, $comment)?
@@ -189,11 +192,11 @@ impl $name {
 
     // Catches fields defined as `bool` and convert them into a boolean value.
     (
-        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool => $into_type:ty
+        @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool => $into_type:ty
             $(, $comment:literal)?;
     ) => {
         bitfield!(
-            @leaf_accessor $name $hi:$lo $field
+            @leaf_accessor $name $storage, $hi:$lo $field
             { |f| <$into_type>::from(if f != 0 { true } else { false }) }
             $into_type => $into_type $(, $comment)?;
         );
@@ -201,17 +204,17 @@ impl $name {
 
     // Shortcut for fields defined as `bool` without the `=>` syntax.
     (
-        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?;
+        @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?;
     ) => {
-        bitfield!(@field_accessor $name $hi:$lo $field as bool => bool $(, $comment)?;);
+        bitfield!(@field_accessor $name $storage, $hi:$lo $field as bool => bool $(, $comment)?;);
     };
 
     // Catches the `?=>` syntax for non-boolean fields.
     (
-        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty
+        @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty
             $(, $comment:literal)?;
     ) => {
-        bitfield!(@leaf_accessor $name $hi:$lo $field
+        bitfield!(@leaf_accessor $name $storage, $hi:$lo $field
             { |f| <$try_into_type>::try_from(f as $type) } $try_into_type =>
             ::core::result::Result<
                 $try_into_type,
@@ -222,29 +225,38 @@ impl $name {
 
     // Catches the `=>` syntax for non-boolean fields.
     (
-        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty
+        @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty
             $(, $comment:literal)?;
     ) => {
-        bitfield!(@leaf_accessor $name $hi:$lo $field
+        bitfield!(@leaf_accessor $name $storage, $hi:$lo $field
             { |f| <$into_type>::from(f as $type) } $into_type => $into_type $(, $comment)?;);
     };
 
     // Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax.
     (
-        @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt
+        @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt
             $(, $comment:literal)?;
     ) => {
-        bitfield!(@field_accessor $name $hi:$lo $field as $type => $type $(, $comment)?;);
+        bitfield!(@field_accessor $name $storage, $hi:$lo $field as $type => $type $(, $comment)?;);
     };
 
     // Generates the accessor methods for a single field.
     (
-        @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident
+        @leaf_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident
             { $process:expr } $to_type:ty => $res_type:ty $(, $comment:literal)?;
     ) => {
         ::kernel::macros::paste!(
         const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi;
-        const [<$field:upper _MASK>]: u32 = ((((1 << $hi) - 1) << 1) + 1) - ((1 << $lo) - 1);
+        const [<$field:upper _MASK>]: $storage = {
+            // Generate mask for shifting
+            match ::core::mem::size_of::<$storage>() {
+                1 => ::kernel::bits::genmask_u8($lo..=$hi) as $storage,
+                2 => ::kernel::bits::genmask_u16($lo..=$hi) as $storage,
+                4 => ::kernel::bits::genmask_u32($lo..=$hi) as $storage,
+                8 => ::kernel::bits::genmask_u64($lo..=$hi) as $storage,
+                _ => ::kernel::build_error!("Unsupported storage type size")
+            }
+        };
         const [<$field:upper _SHIFT>]: u32 = Self::[<$field:upper _MASK>].trailing_zeros();
         );
 
@@ -255,7 +267,7 @@ impl $name {
         #[inline(always)]
         pub(crate) fn $field(self) -> $res_type {
             ::kernel::macros::paste!(
-            const MASK: u32 = $name::[<$field:upper _MASK>];
+            const MASK: $storage = $name::[<$field:upper _MASK>];
             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
             );
             let field = ((self.0 & MASK) >> SHIFT);
@@ -270,9 +282,9 @@ pub(crate) fn $field(self) -> $res_type {
         )?
         #[inline(always)]
         pub(crate) fn [<set_ $field>](mut self, value: $to_type) -> Self {
-            const MASK: u32 = $name::[<$field:upper _MASK>];
+            const MASK: $storage = $name::[<$field:upper _MASK>];
             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
-            let value = (u32::from(value) << SHIFT) & MASK;
+            let value = (<$storage>::from(value) << SHIFT) & MASK;
             self.0 = (self.0 & !MASK) | value;
 
             self
diff --git a/drivers/gpu/nova-core/regs/macros.rs b/drivers/gpu/nova-core/regs/macros.rs
index 945d15a2c529..ffd7d5cb73bb 100644
--- a/drivers/gpu/nova-core/regs/macros.rs
+++ b/drivers/gpu/nova-core/regs/macros.rs
@@ -276,25 +276,25 @@ pub(crate) trait RegisterBase<T> {
 macro_rules! register {
     // Creates a register at a fixed offset of the MMIO space.
     ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)* } ) => {
-        bitfield!(struct $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $offset);
     };
 
     // Creates an alias register of fixed offset register `alias` with its own fields.
     ($name:ident => $alias:ident $(, $comment:literal)? { $($fields:tt)* } ) => {
-        bitfield!(struct $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $alias::OFFSET);
     };
 
     // Creates a register at a relative offset from a base address provider.
     ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $($fields:tt)* } ) => {
-        bitfield!(struct $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $offset ]);
     };
 
     // Creates an alias register of relative offset register `alias` with its own fields.
     ($name:ident => $base:ty [ $alias:ident ] $(, $comment:literal)? { $($fields:tt)* }) => {
-        bitfield!(struct $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $alias::OFFSET ]);
     };
 
@@ -305,7 +305,7 @@ macro_rules! register {
         }
     ) => {
         static_assert!(::core::mem::size_of::<u32>() <= $stride);
-        bitfield!(struct $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_array $name @ $offset [ $size ; $stride ]);
     };
 
@@ -326,7 +326,7 @@ macro_rules! register {
             $(, $comment:literal)? { $($fields:tt)* }
     ) => {
         static_assert!(::core::mem::size_of::<u32>() <= $stride);
-        bitfield!(struct $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative_array $name @ $base [ $offset [ $size ; $stride ] ]);
     };
 
@@ -348,7 +348,7 @@ macro_rules! register {
         }
     ) => {
         static_assert!($idx < $alias::SIZE);
-        bitfield!(struct $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $alias::OFFSET + $idx * $alias::STRIDE ] );
     };
 
@@ -357,7 +357,7 @@ macro_rules! register {
     // to avoid it being interpreted in place of the relative register array alias rule.
     ($name:ident => $alias:ident [ $idx:expr ] $(, $comment:literal)? { $($fields:tt)* }) => {
         static_assert!($idx < $alias::SIZE);
-        bitfield!(struct $name $(, $comment)? { $($fields)* } );
+        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE );
     };
 
-- 
2.34.1


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

* [PATCH v5 3/9] nova-core: bitfield: Add support for custom visiblity
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
  2025-09-30 14:45 ` [PATCH v5 1/9] nova-core: bitfield: Move bitfield-specific code from register! into new macro Joel Fernandes
  2025-09-30 14:45 ` [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths Joel Fernandes
@ 2025-09-30 14:45 ` Joel Fernandes
  2025-09-30 14:45 ` [PATCH v5 4/9] rust: Move register and bitfield macros out of Nova Joel Fernandes
                   ` (7 subsequent siblings)
  10 siblings, 0 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 14:45 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Joel Fernandes,
	Timur Tabi, joel, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau

Add support for custom visiblity to allow for users to control visibility
of the structure and helpers.

Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Reviewed-by: Elle Rhumsaa <elle@weathered-steel.dev>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
---
 drivers/gpu/nova-core/bitfield.rs    | 49 +++++++++++++++-------------
 drivers/gpu/nova-core/regs/macros.rs | 16 ++++-----
 2 files changed, 34 insertions(+), 31 deletions(-)

diff --git a/drivers/gpu/nova-core/bitfield.rs b/drivers/gpu/nova-core/bitfield.rs
index 75de1c0fcb3b..cbedbb0078f6 100644
--- a/drivers/gpu/nova-core/bitfield.rs
+++ b/drivers/gpu/nova-core/bitfield.rs
@@ -57,7 +57,7 @@
 /// }
 ///
 /// bitfield! {
-///     struct ControlReg(u32) {
+///     pub struct ControlReg(u32) {
 ///         3:0 mode as u8 ?=> Mode;
 ///         7:7 state as bool => State;
 ///     }
@@ -71,6 +71,9 @@
 ///   struct's storage size.
 /// - Debug and Default implementations.
 ///
+/// Note: Field accessors and setters inherit the same visibility as the struct itself.
+/// In the example above, both `mode()` and `set_mode()` methods will be `pub`.
+///
 /// Fields are defined as follows:
 ///
 /// - `as <type>` simply returns the field value casted to <type>, typically `u32`, `u16`, `u8` or
@@ -81,21 +84,21 @@
 ///   and returns the result. This is useful with fields for which not all values are valid.
 macro_rules! bitfield {
     // Main entry point - defines the bitfield struct with fields
-    (struct $name:ident($storage:ty) $(, $comment:literal)? { $($fields:tt)* }) => {
-        bitfield!(@core $name $storage $(, $comment)? { $($fields)* });
+    ($vis:vis struct $name:ident($storage:ty) $(, $comment:literal)? { $($fields:tt)* }) => {
+        bitfield!(@core $vis $name $storage $(, $comment)? { $($fields)* });
     };
 
     // All rules below are helpers.
 
     // Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`,
     // `Default`, `BitOr`, and conversion to the value type) and field accessor methods.
-    (@core $name:ident $storage:ty $(, $comment:literal)? { $($fields:tt)* }) => {
+    (@core $vis:vis $name:ident $storage:ty $(, $comment:literal)? { $($fields:tt)* }) => {
         $(
         #[doc=$comment]
         )?
         #[repr(transparent)]
         #[derive(Clone, Copy)]
-        pub(crate) struct $name($storage);
+        $vis struct $name($storage);
 
         impl ::core::ops::BitOr for $name {
             type Output = Self;
@@ -111,14 +114,14 @@ fn from(val: $name) -> $storage {
             }
         }
 
-        bitfield!(@fields_dispatcher $name $storage { $($fields)* });
+        bitfield!(@fields_dispatcher $vis $name $storage { $($fields)* });
     };
 
     // Captures the fields and passes them to all the implementers that require field information.
     //
     // Used to simplify the matching rules for implementers, so they don't need to match the entire
     // complex fields rule even though they only make use of part of it.
-    (@fields_dispatcher $name:ident $storage:ty {
+    (@fields_dispatcher $vis:vis $name:ident $storage:ty {
         $($hi:tt:$lo:tt $field:ident as $type:tt
             $(?=> $try_into_type:ty)?
             $(=> $into_type:ty)?
@@ -127,7 +130,7 @@ fn from(val: $name) -> $storage {
         )*
     }
     ) => {
-        bitfield!(@field_accessors $name $storage {
+        bitfield!(@field_accessors $vis $name $storage {
             $(
                 $hi:$lo $field as $type
                 $(?=> $try_into_type)?
@@ -142,7 +145,7 @@ fn from(val: $name) -> $storage {
 
     // Defines all the field getter/setter methods for `$name`.
     (
-        @field_accessors $name:ident $storage:ty {
+        @field_accessors $vis:vis $name:ident $storage:ty {
         $($hi:tt:$lo:tt $field:ident as $type:tt
             $(?=> $try_into_type:ty)?
             $(=> $into_type:ty)?
@@ -158,7 +161,7 @@ fn from(val: $name) -> $storage {
         #[allow(dead_code)]
         impl $name {
             $(
-            bitfield!(@field_accessor $name $storage, $hi:$lo $field as $type
+            bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as $type
                 $(?=> $try_into_type)?
                 $(=> $into_type)?
                 $(, $comment)?
@@ -192,11 +195,11 @@ impl $name {
 
     // Catches fields defined as `bool` and convert them into a boolean value.
     (
-        @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool => $into_type:ty
+        @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool => $into_type:ty
             $(, $comment:literal)?;
     ) => {
         bitfield!(
-            @leaf_accessor $name $storage, $hi:$lo $field
+            @leaf_accessor $vis $name $storage, $hi:$lo $field
             { |f| <$into_type>::from(if f != 0 { true } else { false }) }
             $into_type => $into_type $(, $comment)?;
         );
@@ -204,17 +207,17 @@ impl $name {
 
     // Shortcut for fields defined as `bool` without the `=>` syntax.
     (
-        @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?;
+        @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?;
     ) => {
-        bitfield!(@field_accessor $name $storage, $hi:$lo $field as bool => bool $(, $comment)?;);
+        bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as bool => bool $(, $comment)?;);
     };
 
     // Catches the `?=>` syntax for non-boolean fields.
     (
-        @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty
+        @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty
             $(, $comment:literal)?;
     ) => {
-        bitfield!(@leaf_accessor $name $storage, $hi:$lo $field
+        bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field
             { |f| <$try_into_type>::try_from(f as $type) } $try_into_type =>
             ::core::result::Result<
                 $try_into_type,
@@ -225,24 +228,24 @@ impl $name {
 
     // Catches the `=>` syntax for non-boolean fields.
     (
-        @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty
+        @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty
             $(, $comment:literal)?;
     ) => {
-        bitfield!(@leaf_accessor $name $storage, $hi:$lo $field
+        bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field
             { |f| <$into_type>::from(f as $type) } $into_type => $into_type $(, $comment)?;);
     };
 
     // Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax.
     (
-        @field_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt
+        @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt
             $(, $comment:literal)?;
     ) => {
-        bitfield!(@field_accessor $name $storage, $hi:$lo $field as $type => $type $(, $comment)?;);
+        bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as $type => $type $(, $comment)?;);
     };
 
     // Generates the accessor methods for a single field.
     (
-        @leaf_accessor $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident
+        @leaf_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident
             { $process:expr } $to_type:ty => $res_type:ty $(, $comment:literal)?;
     ) => {
         ::kernel::macros::paste!(
@@ -265,7 +268,7 @@ impl $name {
         #[doc=$comment]
         )?
         #[inline(always)]
-        pub(crate) fn $field(self) -> $res_type {
+        $vis fn $field(self) -> $res_type {
             ::kernel::macros::paste!(
             const MASK: $storage = $name::[<$field:upper _MASK>];
             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
@@ -281,7 +284,7 @@ pub(crate) fn $field(self) -> $res_type {
         #[doc=$comment]
         )?
         #[inline(always)]
-        pub(crate) fn [<set_ $field>](mut self, value: $to_type) -> Self {
+        $vis fn [<set_ $field>](mut self, value: $to_type) -> Self {
             const MASK: $storage = $name::[<$field:upper _MASK>];
             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
             let value = (<$storage>::from(value) << SHIFT) & MASK;
diff --git a/drivers/gpu/nova-core/regs/macros.rs b/drivers/gpu/nova-core/regs/macros.rs
index ffd7d5cb73bb..c0a5194e8d97 100644
--- a/drivers/gpu/nova-core/regs/macros.rs
+++ b/drivers/gpu/nova-core/regs/macros.rs
@@ -276,25 +276,25 @@ pub(crate) trait RegisterBase<T> {
 macro_rules! register {
     // Creates a register at a fixed offset of the MMIO space.
     ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)* } ) => {
-        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
+        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $offset);
     };
 
     // Creates an alias register of fixed offset register `alias` with its own fields.
     ($name:ident => $alias:ident $(, $comment:literal)? { $($fields:tt)* } ) => {
-        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
+        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $alias::OFFSET);
     };
 
     // Creates a register at a relative offset from a base address provider.
     ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $($fields:tt)* } ) => {
-        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
+        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $offset ]);
     };
 
     // Creates an alias register of relative offset register `alias` with its own fields.
     ($name:ident => $base:ty [ $alias:ident ] $(, $comment:literal)? { $($fields:tt)* }) => {
-        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
+        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $alias::OFFSET ]);
     };
 
@@ -305,7 +305,7 @@ macro_rules! register {
         }
     ) => {
         static_assert!(::core::mem::size_of::<u32>() <= $stride);
-        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
+        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_array $name @ $offset [ $size ; $stride ]);
     };
 
@@ -326,7 +326,7 @@ macro_rules! register {
             $(, $comment:literal)? { $($fields:tt)* }
     ) => {
         static_assert!(::core::mem::size_of::<u32>() <= $stride);
-        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
+        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative_array $name @ $base [ $offset [ $size ; $stride ] ]);
     };
 
@@ -348,7 +348,7 @@ macro_rules! register {
         }
     ) => {
         static_assert!($idx < $alias::SIZE);
-        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
+        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $alias::OFFSET + $idx * $alias::STRIDE ] );
     };
 
@@ -357,7 +357,7 @@ macro_rules! register {
     // to avoid it being interpreted in place of the relative register array alias rule.
     ($name:ident => $alias:ident [ $idx:expr ] $(, $comment:literal)? { $($fields:tt)* }) => {
         static_assert!($idx < $alias::SIZE);
-        bitfield!(struct $name(u32) $(, $comment)? { $($fields)* } );
+        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE );
     };
 
-- 
2.34.1


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

* [PATCH v5 4/9] rust: Move register and bitfield macros out of Nova
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
                   ` (2 preceding siblings ...)
  2025-09-30 14:45 ` [PATCH v5 3/9] nova-core: bitfield: Add support for custom visiblity Joel Fernandes
@ 2025-09-30 14:45 ` Joel Fernandes
  2025-09-30 14:45 ` [PATCH v5 5/9] rust: bitfield: Add a new() constructor and raw() accessor Joel Fernandes
                   ` (6 subsequent siblings)
  10 siblings, 0 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 14:45 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Joel Fernandes,
	Timur Tabi, joel, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau

Out of broad need for the register and bitfield macros in Rust, move
them out of nova into the kernel crate. Several usecases need them (Nova
is already using these and Tyr developers said they need them).

bitfield moved into kernel crate - defines bitfields in Rust.
register moved into io module - defines hardware registers and accessors.

Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Reviewed-by: Elle Rhumsaa <elle@weathered-steel.dev>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
---
 MAINTAINERS                                   |  7 +++
 drivers/gpu/nova-core/falcon.rs               |  2 +-
 drivers/gpu/nova-core/falcon/gsp.rs           |  4 +-
 drivers/gpu/nova-core/falcon/sec2.rs          |  2 +-
 drivers/gpu/nova-core/nova_core.rs            |  3 -
 drivers/gpu/nova-core/regs.rs                 |  6 +-
 .../gpu/nova-core => rust/kernel}/bitfield.rs | 27 ++++-----
 rust/kernel/io.rs                             |  1 +
 .../macros.rs => rust/kernel/io/register.rs   | 58 ++++++++++---------
 rust/kernel/lib.rs                            |  1 +
 10 files changed, 61 insertions(+), 50 deletions(-)
 rename {drivers/gpu/nova-core => rust/kernel}/bitfield.rs (91%)
 rename drivers/gpu/nova-core/regs/macros.rs => rust/kernel/io/register.rs (93%)

diff --git a/MAINTAINERS b/MAINTAINERS
index 841b76234045..20d06cf4b512 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -4380,6 +4380,13 @@ F:	include/linux/bitops.h
 F:	lib/test_bitops.c
 F:	tools/*/bitops*
 
+BITFIELD API [RUST]
+M:	Joel Fernandes <joelagnelf@nvidia.com>
+M:	Alexandre Courbot <acourbot@nvidia.com>
+M:	Yury Norov <yury.norov@gmail.com>
+S:	Maintained
+F:	rust/kernel/bitfield.rs
+
 BITOPS API BINDINGS [RUST]
 M:	Yury Norov <yury.norov@gmail.com>
 S:	Maintained
diff --git a/drivers/gpu/nova-core/falcon.rs b/drivers/gpu/nova-core/falcon.rs
index 37e6298195e4..a15fa98c8614 100644
--- a/drivers/gpu/nova-core/falcon.rs
+++ b/drivers/gpu/nova-core/falcon.rs
@@ -6,6 +6,7 @@
 use hal::FalconHal;
 use kernel::device;
 use kernel::dma::DmaAddress;
+use kernel::io::register::RegisterBase;
 use kernel::prelude::*;
 use kernel::sync::aref::ARef;
 use kernel::time::Delta;
@@ -14,7 +15,6 @@
 use crate::driver::Bar0;
 use crate::gpu::Chipset;
 use crate::regs;
-use crate::regs::macros::RegisterBase;
 use crate::util;
 
 pub(crate) mod gsp;
diff --git a/drivers/gpu/nova-core/falcon/gsp.rs b/drivers/gpu/nova-core/falcon/gsp.rs
index f17599cb49fa..cd4960e997c8 100644
--- a/drivers/gpu/nova-core/falcon/gsp.rs
+++ b/drivers/gpu/nova-core/falcon/gsp.rs
@@ -1,9 +1,11 @@
 // SPDX-License-Identifier: GPL-2.0
 
+use kernel::io::register::RegisterBase;
+
 use crate::{
     driver::Bar0,
     falcon::{Falcon, FalconEngine, PFalcon2Base, PFalconBase},
-    regs::{self, macros::RegisterBase},
+    regs::self,
 };
 
 /// Type specifying the `Gsp` falcon engine. Cannot be instantiated.
diff --git a/drivers/gpu/nova-core/falcon/sec2.rs b/drivers/gpu/nova-core/falcon/sec2.rs
index 815786c8480d..81717868a8a8 100644
--- a/drivers/gpu/nova-core/falcon/sec2.rs
+++ b/drivers/gpu/nova-core/falcon/sec2.rs
@@ -1,7 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0
 
 use crate::falcon::{FalconEngine, PFalcon2Base, PFalconBase};
-use crate::regs::macros::RegisterBase;
+use kernel::io::register::RegisterBase;
 
 /// Type specifying the `Sec2` falcon engine. Cannot be instantiated.
 pub(crate) struct Sec2(());
diff --git a/drivers/gpu/nova-core/nova_core.rs b/drivers/gpu/nova-core/nova_core.rs
index 112277c7921e..fffcaee2249f 100644
--- a/drivers/gpu/nova-core/nova_core.rs
+++ b/drivers/gpu/nova-core/nova_core.rs
@@ -2,9 +2,6 @@
 
 //! Nova Core GPU Driver
 
-#[macro_use]
-mod bitfield;
-
 mod dma;
 mod driver;
 mod falcon;
diff --git a/drivers/gpu/nova-core/regs.rs b/drivers/gpu/nova-core/regs.rs
index 206dab2e1335..1f08e6d4045a 100644
--- a/drivers/gpu/nova-core/regs.rs
+++ b/drivers/gpu/nova-core/regs.rs
@@ -4,15 +4,13 @@
 // but are mapped to types.
 #![allow(non_camel_case_types)]
 
-#[macro_use]
-pub(crate) mod macros;
-
 use crate::falcon::{
     DmaTrfCmdSize, FalconCoreRev, FalconCoreRevSubversion, FalconFbifMemType, FalconFbifTarget,
     FalconModSelAlgo, FalconSecurityModel, PFalcon2Base, PFalconBase, PeregrineCoreSelect,
 };
 use crate::gpu::{Architecture, Chipset};
 use kernel::prelude::*;
+use kernel::register;
 
 // PMC
 
@@ -331,6 +329,7 @@ pub(crate) fn mem_scrubbing_done(self) -> bool {
 
 pub(crate) mod gm107 {
     // FUSE
+    use kernel::register;
 
     register!(NV_FUSE_STATUS_OPT_DISPLAY @ 0x00021c04 {
         0:0     display_disabled as bool;
@@ -339,6 +338,7 @@ pub(crate) mod gm107 {
 
 pub(crate) mod ga100 {
     // FUSE
+    use kernel::register;
 
     register!(NV_FUSE_STATUS_OPT_DISPLAY @ 0x00820c04 {
         0:0     display_disabled as bool;
diff --git a/drivers/gpu/nova-core/bitfield.rs b/rust/kernel/bitfield.rs
similarity index 91%
rename from drivers/gpu/nova-core/bitfield.rs
rename to rust/kernel/bitfield.rs
index cbedbb0078f6..09cd5741598c 100644
--- a/drivers/gpu/nova-core/bitfield.rs
+++ b/rust/kernel/bitfield.rs
@@ -9,7 +9,7 @@
 /// # Syntax
 ///
 /// ```rust
-/// use nova_core::bitfield;
+/// use kernel::bitfield;
 ///
 /// #[derive(Debug, Clone, Copy, Default)]
 /// enum Mode {
@@ -82,10 +82,11 @@
 ///   the result.
 /// - `as <type> ?=> <try_into_type>` calls `<try_into_type>`'s `TryFrom::<<type>>` implementation
 ///   and returns the result. This is useful with fields for which not all values are valid.
+#[macro_export]
 macro_rules! bitfield {
     // Main entry point - defines the bitfield struct with fields
     ($vis:vis struct $name:ident($storage:ty) $(, $comment:literal)? { $($fields:tt)* }) => {
-        bitfield!(@core $vis $name $storage $(, $comment)? { $($fields)* });
+        ::kernel::bitfield!(@core $vis $name $storage $(, $comment)? { $($fields)* });
     };
 
     // All rules below are helpers.
@@ -114,7 +115,7 @@ fn from(val: $name) -> $storage {
             }
         }
 
-        bitfield!(@fields_dispatcher $vis $name $storage { $($fields)* });
+        ::kernel::bitfield!(@fields_dispatcher $vis $name $storage { $($fields)* });
     };
 
     // Captures the fields and passes them to all the implementers that require field information.
@@ -130,7 +131,7 @@ fn from(val: $name) -> $storage {
         )*
     }
     ) => {
-        bitfield!(@field_accessors $vis $name $storage {
+        ::kernel::bitfield!(@field_accessors $vis $name $storage {
             $(
                 $hi:$lo $field as $type
                 $(?=> $try_into_type)?
@@ -139,8 +140,8 @@ fn from(val: $name) -> $storage {
             ;
             )*
         });
-        bitfield!(@debug $name { $($field;)* });
-        bitfield!(@default $name { $($field;)* });
+        ::kernel::bitfield!(@debug $name { $($field;)* });
+        ::kernel::bitfield!(@default $name { $($field;)* });
     };
 
     // Defines all the field getter/setter methods for `$name`.
@@ -155,13 +156,13 @@ fn from(val: $name) -> $storage {
         }
     ) => {
         $(
-            bitfield!(@check_field_bounds $hi:$lo $field as $type);
+            ::kernel::bitfield!(@check_field_bounds $hi:$lo $field as $type);
         )*
 
         #[allow(dead_code)]
         impl $name {
             $(
-            bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as $type
+            ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as $type
                 $(?=> $try_into_type)?
                 $(=> $into_type)?
                 $(, $comment)?
@@ -198,7 +199,7 @@ impl $name {
         @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool => $into_type:ty
             $(, $comment:literal)?;
     ) => {
-        bitfield!(
+        ::kernel::bitfield!(
             @leaf_accessor $vis $name $storage, $hi:$lo $field
             { |f| <$into_type>::from(if f != 0 { true } else { false }) }
             $into_type => $into_type $(, $comment)?;
@@ -209,7 +210,7 @@ impl $name {
     (
         @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?;
     ) => {
-        bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as bool => bool $(, $comment)?;);
+        ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as bool => bool $(, $comment)?;);
     };
 
     // Catches the `?=>` syntax for non-boolean fields.
@@ -217,7 +218,7 @@ impl $name {
         @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty
             $(, $comment:literal)?;
     ) => {
-        bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field
+        ::kernel::bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field
             { |f| <$try_into_type>::try_from(f as $type) } $try_into_type =>
             ::core::result::Result<
                 $try_into_type,
@@ -231,7 +232,7 @@ impl $name {
         @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty
             $(, $comment:literal)?;
     ) => {
-        bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field
+        ::kernel::bitfield!(@leaf_accessor $vis $name $storage, $hi:$lo $field
             { |f| <$into_type>::from(f as $type) } $into_type => $into_type $(, $comment)?;);
     };
 
@@ -240,7 +241,7 @@ impl $name {
         @field_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as $type:tt
             $(, $comment:literal)?;
     ) => {
-        bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as $type => $type $(, $comment)?;);
+        ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as $type => $type $(, $comment)?;);
     };
 
     // Generates the accessor methods for a single field.
diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs
index ee182b0b5452..da1384fd9ab6 100644
--- a/rust/kernel/io.rs
+++ b/rust/kernel/io.rs
@@ -9,6 +9,7 @@
 
 pub mod mem;
 pub mod poll;
+pub mod register;
 pub mod resource;
 
 pub use resource::Resource;
diff --git a/drivers/gpu/nova-core/regs/macros.rs b/rust/kernel/io/register.rs
similarity index 93%
rename from drivers/gpu/nova-core/regs/macros.rs
rename to rust/kernel/io/register.rs
index c0a5194e8d97..c24d956f122f 100644
--- a/drivers/gpu/nova-core/regs/macros.rs
+++ b/rust/kernel/io/register.rs
@@ -17,7 +17,8 @@
 /// The `T` generic argument is used to distinguish which base to use, in case a type provides
 /// several bases. It is given to the `register!` macro to restrict the use of the register to
 /// implementors of this particular variant.
-pub(crate) trait RegisterBase<T> {
+pub trait RegisterBase<T> {
+    /// The base address for the register.
     const BASE: usize;
 }
 
@@ -26,7 +27,7 @@ pub(crate) trait RegisterBase<T> {
 ///
 /// Example:
 ///
-/// ```no_run
+/// ```ignore
 /// register!(BOOT_0 @ 0x00000100, "Basic revision information about the GPU" {
 ///    3:0     minor_revision as u8, "Minor revision of the chip";
 ///    7:4     major_revision as u8, "Major revision of the chip";
@@ -39,7 +40,7 @@ pub(crate) trait RegisterBase<T> {
 /// significant bits of the register. Each field can be accessed and modified using accessor
 /// methods:
 ///
-/// ```no_run
+/// ```ignore
 /// // Read from the register's defined offset (0x100).
 /// let boot0 = BOOT_0::read(&bar);
 /// pr_info!("chip revision: {}.{}", boot0.major_revision(), boot0.minor_revision());
@@ -61,7 +62,7 @@ pub(crate) trait RegisterBase<T> {
 /// It is also possible to create a alias register by using the `=> ALIAS` syntax. This is useful
 /// for cases where a register's interpretation depends on the context:
 ///
-/// ```no_run
+/// ```ignore
 /// register!(SCRATCH @ 0x00000200, "Scratch register" {
 ///    31:0     value as u32, "Raw value";
 /// });
@@ -111,7 +112,7 @@ pub(crate) trait RegisterBase<T> {
 /// this register needs to implement `RegisterBase<Base>`. Here is the above example translated
 /// into code:
 ///
-/// ```no_run
+/// ```ignore
 /// // Type used to identify the base.
 /// pub(crate) struct CpuCtlBase;
 ///
@@ -162,7 +163,7 @@ pub(crate) trait RegisterBase<T> {
 /// compile-time or runtime bound checking. Simply define their address as `Address[Size]`, and add
 /// an `idx` parameter to their `read`, `write` and `alter` methods:
 ///
-/// ```no_run
+/// ```ignore
 /// # fn no_run() -> Result<(), Error> {
 /// # fn get_scratch_idx() -> usize {
 /// #   0x15
@@ -211,7 +212,7 @@ pub(crate) trait RegisterBase<T> {
 /// Combining the two features described in the sections above, arrays of registers accessible from
 /// a base can also be defined:
 ///
-/// ```no_run
+/// ```ignore
 /// # fn no_run() -> Result<(), Error> {
 /// # fn get_scratch_idx() -> usize {
 /// #   0x15
@@ -273,28 +274,29 @@ pub(crate) trait RegisterBase<T> {
 /// # Ok(())
 /// # }
 /// ```
+#[macro_export]
 macro_rules! register {
     // Creates a register at a fixed offset of the MMIO space.
     ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)* } ) => {
-        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
+        ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $offset);
     };
 
     // Creates an alias register of fixed offset register `alias` with its own fields.
     ($name:ident => $alias:ident $(, $comment:literal)? { $($fields:tt)* } ) => {
-        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
+        ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $alias::OFFSET);
     };
 
     // Creates a register at a relative offset from a base address provider.
     ($name:ident @ $base:ty [ $offset:literal ] $(, $comment:literal)? { $($fields:tt)* } ) => {
-        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
+        ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $offset ]);
     };
 
     // Creates an alias register of relative offset register `alias` with its own fields.
     ($name:ident => $base:ty [ $alias:ident ] $(, $comment:literal)? { $($fields:tt)* }) => {
-        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
+        ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $alias::OFFSET ]);
     };
 
@@ -305,7 +307,7 @@ macro_rules! register {
         }
     ) => {
         static_assert!(::core::mem::size_of::<u32>() <= $stride);
-        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
+        ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_array $name @ $offset [ $size ; $stride ]);
     };
 
@@ -326,7 +328,7 @@ macro_rules! register {
             $(, $comment:literal)? { $($fields:tt)* }
     ) => {
         static_assert!(::core::mem::size_of::<u32>() <= $stride);
-        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
+        ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative_array $name @ $base [ $offset [ $size ; $stride ] ]);
     };
 
@@ -348,7 +350,7 @@ macro_rules! register {
         }
     ) => {
         static_assert!($idx < $alias::SIZE);
-        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
+        ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_relative $name @ $base [ $alias::OFFSET + $idx * $alias::STRIDE ] );
     };
 
@@ -357,7 +359,7 @@ macro_rules! register {
     // to avoid it being interpreted in place of the relative register array alias rule.
     ($name:ident => $alias:ident [ $idx:expr ] $(, $comment:literal)? { $($fields:tt)* }) => {
         static_assert!($idx < $alias::SIZE);
-        bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
+        ::kernel::bitfield!(pub(crate) struct $name(u32) $(, $comment)? { $($fields)* } );
         register!(@io_fixed $name @ $alias::OFFSET + $idx * $alias::STRIDE );
     };
 
@@ -414,12 +416,12 @@ pub(crate) fn read<const SIZE: usize, T, B>(
                 base: &B,
             ) -> Self where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
-                B: crate::regs::macros::RegisterBase<$base>,
+                B: ::kernel::io::register::RegisterBase<$base>,
             {
                 const OFFSET: usize = $name::OFFSET;
 
                 let value = io.read32(
-                    <B as crate::regs::macros::RegisterBase<$base>>::BASE + OFFSET
+                    <B as ::kernel::io::register::RegisterBase<$base>>::BASE + OFFSET
                 );
 
                 Self(value)
@@ -435,13 +437,13 @@ pub(crate) fn write<const SIZE: usize, T, B>(
                 base: &B,
             ) where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
-                B: crate::regs::macros::RegisterBase<$base>,
+                B: ::kernel::io::register::RegisterBase<$base>,
             {
                 const OFFSET: usize = $name::OFFSET;
 
                 io.write32(
                     self.0,
-                    <B as crate::regs::macros::RegisterBase<$base>>::BASE + OFFSET
+                    <B as ::kernel::io::register::RegisterBase<$base>>::BASE + OFFSET
                 );
             }
 
@@ -455,7 +457,7 @@ pub(crate) fn alter<const SIZE: usize, T, B, F>(
                 f: F,
             ) where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
-                B: crate::regs::macros::RegisterBase<$base>,
+                B: ::kernel::io::register::RegisterBase<$base>,
                 F: ::core::ops::FnOnce(Self) -> Self,
             {
                 let reg = f(Self::read(io, base));
@@ -600,11 +602,11 @@ pub(crate) fn read<const SIZE: usize, T, B>(
                 idx: usize,
             ) -> Self where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
-                B: crate::regs::macros::RegisterBase<$base>,
+                B: ::kernel::io::register::RegisterBase<$base>,
             {
                 build_assert!(idx < Self::SIZE);
 
-                let offset = <B as crate::regs::macros::RegisterBase<$base>>::BASE +
+                let offset = <B as ::kernel::io::register::RegisterBase<$base>>::BASE +
                     Self::OFFSET + (idx * Self::STRIDE);
                 let value = io.read32(offset);
 
@@ -622,11 +624,11 @@ pub(crate) fn write<const SIZE: usize, T, B>(
                 idx: usize
             ) where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
-                B: crate::regs::macros::RegisterBase<$base>,
+                B: ::kernel::io::register::RegisterBase<$base>,
             {
                 build_assert!(idx < Self::SIZE);
 
-                let offset = <B as crate::regs::macros::RegisterBase<$base>>::BASE +
+                let offset = <B as ::kernel::io::register::RegisterBase<$base>>::BASE +
                     Self::OFFSET + (idx * Self::STRIDE);
 
                 io.write32(self.0, offset);
@@ -643,7 +645,7 @@ pub(crate) fn alter<const SIZE: usize, T, B, F>(
                 f: F,
             ) where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
-                B: crate::regs::macros::RegisterBase<$base>,
+                B: ::kernel::io::register::RegisterBase<$base>,
                 F: ::core::ops::FnOnce(Self) -> Self,
             {
                 let reg = f(Self::read(io, base, idx));
@@ -662,7 +664,7 @@ pub(crate) fn try_read<const SIZE: usize, T, B>(
                 idx: usize,
             ) -> ::kernel::error::Result<Self> where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
-                B: crate::regs::macros::RegisterBase<$base>,
+                B: ::kernel::io::register::RegisterBase<$base>,
             {
                 if idx < Self::SIZE {
                     Ok(Self::read(io, base, idx))
@@ -684,7 +686,7 @@ pub(crate) fn try_write<const SIZE: usize, T, B>(
                 idx: usize,
             ) -> ::kernel::error::Result where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
-                B: crate::regs::macros::RegisterBase<$base>,
+                B: ::kernel::io::register::RegisterBase<$base>,
             {
                 if idx < Self::SIZE {
                     Ok(self.write(io, base, idx))
@@ -707,7 +709,7 @@ pub(crate) fn try_alter<const SIZE: usize, T, B, F>(
                 f: F,
             ) -> ::kernel::error::Result where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
-                B: crate::regs::macros::RegisterBase<$base>,
+                B: ::kernel::io::register::RegisterBase<$base>,
                 F: ::core::ops::FnOnce(Self) -> Self,
             {
                 if idx < Self::SIZE {
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 115376c2710e..66c6219abb25 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -64,6 +64,7 @@
 #[cfg(CONFIG_AUXILIARY_BUS)]
 pub mod auxiliary;
 pub mod bitmap;
+pub mod bitfield;
 pub mod bits;
 #[cfg(CONFIG_BLOCK)]
 pub mod block;
-- 
2.34.1


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

* [PATCH v5 5/9] rust: bitfield: Add a new() constructor and raw() accessor
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
                   ` (3 preceding siblings ...)
  2025-09-30 14:45 ` [PATCH v5 4/9] rust: Move register and bitfield macros out of Nova Joel Fernandes
@ 2025-09-30 14:45 ` Joel Fernandes
  2025-09-30 14:45 ` [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield Joel Fernandes
                   ` (5 subsequent siblings)
  10 siblings, 0 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 14:45 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Joel Fernandes,
	Timur Tabi, joel, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau

In order to prevent the user from directly accessing/wrapping the inner
value of the struct, provide a new storage type to wrap the inner value.
The bitfield framework can then control access better. For instance, we
can zero out undefined bits to prevent undefined behavior of bits that
are not defined.

Further, we can somewhat prevent the user manipulating the bitfield's
inner storage directly using .0. They can still do so by using the new
bitfield storage type this patch defines, however it would not be by
accident and would have to be deliberate.

Suggested-by: Yury Norov <yury.norov@gmail.com>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
---
 rust/kernel/bitfield.rs    | 123 +++++++++++++++++++++++++++++--------
 rust/kernel/io/register.rs |  16 ++---
 2 files changed, 106 insertions(+), 33 deletions(-)

diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
index 09cd5741598c..fed19918c3b9 100644
--- a/rust/kernel/bitfield.rs
+++ b/rust/kernel/bitfield.rs
@@ -4,7 +4,33 @@
 //!
 //! Support for defining bitfields in Rust structures. Also used by the [`register!`] macro.
 
-/// Defines a struct with accessors to access bits within an inner unsigned integer.
+/// Storage wrapper for bitfield values that prevents direct construction.
+///
+/// This type wraps the underlying storage value and ensures that bitfield
+/// structs can only be constructed through their `new()` method, which
+/// properly masks undefined bits.
+#[repr(transparent)]
+#[derive(Clone, Copy)]
+pub struct BitfieldInternalStorage<T: Copy> {
+    value: T,
+}
+
+impl<T: Copy> BitfieldInternalStorage<T> {
+    /// Creates a new storage wrapper with the given value.
+    #[inline(always)]
+    pub const fn from_raw(value: T) -> Self {
+        Self { value }
+    }
+
+    /// Returns the underlying raw value.
+    #[inline(always)]
+    pub const fn into_raw(self) -> T {
+        self.value
+    }
+}
+
+/// Bitfield macro definition.
+/// Define a struct with accessors to access bits within an inner unsigned integer.
 ///
 /// # Syntax
 ///
@@ -62,9 +88,23 @@
 ///         7:7 state as bool => State;
 ///     }
 /// }
+///
+/// // Create a bitfield from a raw value - undefined bits are zeroed
+/// let reg = ControlReg::new(0xDEADBEEF);
+/// // Only bits 0-3 and 7 are preserved (as defined by the fields)
+///
+/// // Get the raw underlying value
+/// let raw_value = reg.raw();
+///
+/// // Use the builder pattern with field setters
+/// let reg2 = ControlReg::default()
+///     .set_mode(Mode::Auto)
+///     .set_state(State::Active);
 /// ```
 ///
 /// This generates a struct with:
+/// - Constructor: `new(value)` - creates a bitfield from a raw value, zeroing undefined bits
+/// - Raw accessor: `raw()` - returns the underlying raw value
 /// - Field accessors: `mode()`, `state()`, etc.
 /// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern).
 ///   Note that the compiler will error out if the size of the setter's arg exceeds the
@@ -72,7 +112,7 @@
 /// - Debug and Default implementations.
 ///
 /// Note: Field accessors and setters inherit the same visibility as the struct itself.
-/// In the example above, both `mode()` and `set_mode()` methods will be `pub`.
+/// In the example above, `new()`, `raw()`, `mode()` and `set_mode()` methods will be `pub`.
 ///
 /// Fields are defined as follows:
 ///
@@ -99,19 +139,19 @@ macro_rules! bitfield {
         )?
         #[repr(transparent)]
         #[derive(Clone, Copy)]
-        $vis struct $name($storage);
+        $vis struct $name(::kernel::bitfield::BitfieldInternalStorage<$storage>);
 
         impl ::core::ops::BitOr for $name {
             type Output = Self;
 
             fn bitor(self, rhs: Self) -> Self::Output {
-                Self(self.0 | rhs.0)
+                Self::new(self.raw() | rhs.raw())
             }
         }
 
         impl ::core::convert::From<$name> for $storage {
             fn from(val: $name) -> $storage {
-                val.0
+                val.raw()
             }
         }
 
@@ -161,6 +201,53 @@ fn from(val: $name) -> $storage {
 
         #[allow(dead_code)]
         impl $name {
+            // Generate field constants to be used later
+            $(
+            ::kernel::macros::paste!(
+                const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi;
+                const [<$field:upper _MASK>]: $storage = {
+                    // Generate mask for shifting
+                    match ::core::mem::size_of::<$storage>() {
+                        1 => ::kernel::bits::genmask_u8($lo..=$hi) as $storage,
+                        2 => ::kernel::bits::genmask_u16($lo..=$hi) as $storage,
+                        4 => ::kernel::bits::genmask_u32($lo..=$hi) as $storage,
+                        8 => ::kernel::bits::genmask_u64($lo..=$hi) as $storage,
+                        _ => ::kernel::build_error!("Unsupported storage type size")
+                    }
+                };
+                const [<$field:upper _SHIFT>]: u32 = Self::[<$field:upper _MASK>].trailing_zeros();
+            );
+            )*
+
+            /// Creates a new bitfield instance from a raw value.
+            ///
+            /// This constructor zeros out all bits that are not defined by any field,
+            /// ensuring only valid field bits are preserved. This is to prevent UB
+            /// when raw() is used to retrieve undefined bits.
+            #[inline(always)]
+            $vis fn new(value: $storage) -> Self {
+                // Calculate mask for all defined fields
+                let mut mask: $storage = 0;
+                $(
+                    ::kernel::macros::paste!(
+                        mask |= Self::[<$field:upper _MASK>];
+                    );
+                )*
+                // Zero out undefined bits and wrap in BitfieldInternalStorage
+                Self(::kernel::bitfield::BitfieldInternalStorage::from_raw(value & mask))
+            }
+
+            /// Returns the raw underlying value of the bitfield.
+            ///
+            /// This provides direct access to the storage value, useful for
+            /// debugging or when you need to work with the raw value.
+            /// Bits not defined are masked at construction time.
+            #[inline(always)]
+            $vis fn raw(&self) -> $storage {
+                self.0.into_raw()
+            }
+
+            // Generate field accessors
             $(
             ::kernel::bitfield!(@field_accessor $vis $name $storage, $hi:$lo $field as $type
                 $(?=> $try_into_type)?
@@ -249,21 +336,6 @@ impl $name {
         @leaf_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident
             { $process:expr } $to_type:ty => $res_type:ty $(, $comment:literal)?;
     ) => {
-        ::kernel::macros::paste!(
-        const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi;
-        const [<$field:upper _MASK>]: $storage = {
-            // Generate mask for shifting
-            match ::core::mem::size_of::<$storage>() {
-                1 => ::kernel::bits::genmask_u8($lo..=$hi) as $storage,
-                2 => ::kernel::bits::genmask_u16($lo..=$hi) as $storage,
-                4 => ::kernel::bits::genmask_u32($lo..=$hi) as $storage,
-                8 => ::kernel::bits::genmask_u64($lo..=$hi) as $storage,
-                _ => ::kernel::build_error!("Unsupported storage type size")
-            }
-        };
-        const [<$field:upper _SHIFT>]: u32 = Self::[<$field:upper _MASK>].trailing_zeros();
-        );
-
         $(
         #[doc="Returns the value of this field:"]
         #[doc=$comment]
@@ -274,7 +346,7 @@ impl $name {
             const MASK: $storage = $name::[<$field:upper _MASK>];
             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
             );
-            let field = ((self.0 & MASK) >> SHIFT);
+            let field = ((self.raw() & MASK) >> SHIFT);
 
             $process(field)
         }
@@ -288,8 +360,9 @@ impl $name {
         $vis fn [<set_ $field>](mut self, value: $to_type) -> Self {
             const MASK: $storage = $name::[<$field:upper _MASK>];
             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
-            let value = (<$storage>::from(value) << SHIFT) & MASK;
-            self.0 = (self.0 & !MASK) | value;
+            let val = (<$storage>::from(value) << SHIFT) & MASK;
+            let new_val = (self.raw() & !MASK) | val;
+            self.0 = ::kernel::bitfield::BitfieldInternalStorage::from_raw(new_val);
 
             self
         }
@@ -301,7 +374,7 @@ impl $name {
         impl ::core::fmt::Debug for $name {
             fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                 f.debug_struct(stringify!($name))
-                    .field("<raw>", &format_args!("{:#x}", &self.0))
+                    .field("<raw>", &format_args!("{:#x}", &self.raw()))
                 $(
                     .field(stringify!($field), &self.$field())
                 )*
@@ -316,7 +389,7 @@ fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
         impl ::core::default::Default for $name {
             fn default() -> Self {
                 #[allow(unused_mut)]
-                let mut value = Self(Default::default());
+                let mut value = Self::new(Default::default());
 
                 ::kernel::macros::paste!(
                 $(
diff --git a/rust/kernel/io/register.rs b/rust/kernel/io/register.rs
index c24d956f122f..45c6ad1bfb9e 100644
--- a/rust/kernel/io/register.rs
+++ b/rust/kernel/io/register.rs
@@ -374,7 +374,7 @@ impl $name {
             pub(crate) fn read<const SIZE: usize, T>(io: &T) -> Self where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
             {
-                Self(io.read32($offset))
+                Self::new(io.read32($offset))
             }
 
             /// Write the value contained in `self` to the register address in `io`.
@@ -382,7 +382,7 @@ pub(crate) fn read<const SIZE: usize, T>(io: &T) -> Self where
             pub(crate) fn write<const SIZE: usize, T>(self, io: &T) where
                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
             {
-                io.write32(self.0, $offset)
+                io.write32(self.raw(), $offset)
             }
 
             /// Read the register from its address in `io` and run `f` on its value to obtain a new
@@ -424,7 +424,7 @@ pub(crate) fn read<const SIZE: usize, T, B>(
                     <B as ::kernel::io::register::RegisterBase<$base>>::BASE + OFFSET
                 );
 
-                Self(value)
+                Self::new(value)
             }
 
             /// Write the value contained in `self` to `io`, using the base address provided by
@@ -442,7 +442,7 @@ pub(crate) fn write<const SIZE: usize, T, B>(
                 const OFFSET: usize = $name::OFFSET;
 
                 io.write32(
-                    self.0,
+                    self.raw(),
                     <B as ::kernel::io::register::RegisterBase<$base>>::BASE + OFFSET
                 );
             }
@@ -487,7 +487,7 @@ pub(crate) fn read<const SIZE: usize, T>(
                 let offset = Self::OFFSET + (idx * Self::STRIDE);
                 let value = io.read32(offset);
 
-                Self(value)
+                Self::new(value)
             }
 
             /// Write the value contained in `self` to the array register with index `idx` in `io`.
@@ -503,7 +503,7 @@ pub(crate) fn write<const SIZE: usize, T>(
 
                 let offset = Self::OFFSET + (idx * Self::STRIDE);
 
-                io.write32(self.0, offset);
+                io.write32(self.raw(), offset);
             }
 
             /// Read the array register at index `idx` in `io` and run `f` on its value to obtain a
@@ -610,7 +610,7 @@ pub(crate) fn read<const SIZE: usize, T, B>(
                     Self::OFFSET + (idx * Self::STRIDE);
                 let value = io.read32(offset);
 
-                Self(value)
+                Self::new(value)
             }
 
             /// Write the value contained in `self` to `io`, using the base address provided by
@@ -631,7 +631,7 @@ pub(crate) fn write<const SIZE: usize, T, B>(
                 let offset = <B as ::kernel::io::register::RegisterBase<$base>>::BASE +
                     Self::OFFSET + (idx * Self::STRIDE);
 
-                io.write32(self.0, offset);
+                io.write32(self.raw(), offset);
             }
 
             /// Read the array register at index `idx` from `io`, using the base address provided
-- 
2.34.1


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

* [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
                   ` (4 preceding siblings ...)
  2025-09-30 14:45 ` [PATCH v5 5/9] rust: bitfield: Add a new() constructor and raw() accessor Joel Fernandes
@ 2025-09-30 14:45 ` Joel Fernandes
  2025-10-02  1:41   ` Alexandre Courbot
  2025-09-30 14:45 ` [PATCH v5 7/9] rust: bitfield: Use 'as' operator for setter type conversion Joel Fernandes
                   ` (4 subsequent siblings)
  10 siblings, 1 reply; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 14:45 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Joel Fernandes,
	Timur Tabi, joel, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau

Add KUNIT tests to make sure the macro is working correctly.

Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
---
 rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 321 insertions(+)

diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
index fed19918c3b9..9a20bcd2eb60 100644
--- a/rust/kernel/bitfield.rs
+++ b/rust/kernel/bitfield.rs
@@ -402,3 +402,324 @@ fn default() -> Self {
         }
     };
 }
+
+#[::kernel::macros::kunit_tests(kernel_bitfield)]
+mod tests {
+    use core::convert::TryFrom;
+
+    // Enum types for testing => and ?=> conversions
+    #[derive(Debug, Clone, Copy, PartialEq)]
+    enum MemoryType {
+        Unmapped = 0,
+        Normal = 1,
+        Device = 2,
+        Reserved = 3,
+    }
+
+    impl Default for MemoryType {
+        fn default() -> Self {
+            MemoryType::Unmapped
+        }
+    }
+
+    impl TryFrom<u8> for MemoryType {
+        type Error = u8;
+        fn try_from(value: u8) -> Result<Self, Self::Error> {
+            match value {
+                0 => Ok(MemoryType::Unmapped),
+                1 => Ok(MemoryType::Normal),
+                2 => Ok(MemoryType::Device),
+                3 => Ok(MemoryType::Reserved),
+                _ => Err(value),
+            }
+        }
+    }
+
+    impl From<MemoryType> for u64 {
+        fn from(mt: MemoryType) -> u64 {
+            mt as u64
+        }
+    }
+
+    #[derive(Debug, Clone, Copy, PartialEq)]
+    enum Priority {
+        Low = 0,
+        Medium = 1,
+        High = 2,
+        Critical = 3,
+    }
+
+    impl Default for Priority {
+        fn default() -> Self {
+            Priority::Low
+        }
+    }
+
+    impl From<u8> for Priority {
+        fn from(value: u8) -> Self {
+            match value & 0x3 {
+                0 => Priority::Low,
+                1 => Priority::Medium,
+                2 => Priority::High,
+                _ => Priority::Critical,
+            }
+        }
+    }
+
+    impl From<Priority> for u16 {
+        fn from(p: Priority) -> u16 {
+            p as u16
+        }
+    }
+
+    bitfield! {
+        struct TestPageTableEntry(u64) {
+            0:0       present     as bool;
+            1:1       writable    as bool;
+            11:9      available   as u8;
+            13:12     mem_type    as u8 ?=> MemoryType;
+            17:14     extended_type as u8 ?=> MemoryType;  // For testing failures
+            51:12     pfn         as u64;
+            51:12     pfn_overlap as u64;
+            61:52     available2  as u16;
+        }
+    }
+
+    bitfield! {
+        struct TestControlRegister(u16) {
+            0:0       enable      as bool;
+            3:1       mode        as u8;
+            5:4       priority    as u8 => Priority;
+            7:4       priority_nibble as u8;
+            15:8      channel     as u8;
+        }
+    }
+
+    bitfield! {
+        struct TestStatusRegister(u8) {
+            0:0       ready       as bool;
+            1:1       error       as bool;
+            3:2       state       as u8;
+            7:4       reserved    as u8;
+            7:0       full_byte   as u8;  // For entire register
+        }
+    }
+
+    #[test]
+    fn test_single_bits() {
+        let mut pte = TestPageTableEntry::default();
+
+        assert!(!pte.present());
+        assert!(!pte.writable());
+
+        pte = pte.set_present(true);
+        assert!(pte.present());
+
+        pte = pte.set_writable(true);
+        assert!(pte.writable());
+
+        pte = pte.set_writable(false);
+        assert!(!pte.writable());
+
+        assert_eq!(pte.available(), 0);
+        pte = pte.set_available(0x5);
+        assert_eq!(pte.available(), 0x5);
+    }
+
+    #[test]
+    fn test_range_fields() {
+        let mut pte = TestPageTableEntry::default();
+
+        pte = pte.set_pfn(0x123456);
+        assert_eq!(pte.pfn(), 0x123456);
+        // Test overlapping field reads same value
+        assert_eq!(pte.pfn_overlap(), 0x123456);
+
+        pte = pte.set_available(0x7);
+        assert_eq!(pte.available(), 0x7);
+
+        pte = pte.set_available2(0x3FF);
+        assert_eq!(pte.available2(), 0x3FF);
+
+        // Test TryFrom with ?=> for MemoryType
+        pte = pte.set_mem_type(MemoryType::Device);
+        assert_eq!(pte.mem_type(), Ok(MemoryType::Device));
+
+        pte = pte.set_mem_type(MemoryType::Normal);
+        assert_eq!(pte.mem_type(), Ok(MemoryType::Normal));
+
+        // Test all valid values for mem_type
+        pte = pte.set_mem_type(MemoryType::Reserved); // Valid value: 3
+        assert_eq!(pte.mem_type(), Ok(MemoryType::Reserved));
+
+        // Test failure case using extended_type field which has 4 bits (0-15)
+        // MemoryType only handles 0-3, so values 4-15 should return Err
+        let mut raw = pte.raw();
+        // Set bits 17:14 to 7 (invalid for MemoryType)
+        raw = (raw & !::kernel::bits::genmask_u64(14..=17)) | (0x7 << 14);
+        let invalid_pte = TestPageTableEntry::new(raw);
+        // Should return Err with the invalid value
+        assert_eq!(invalid_pte.extended_type(), Err(0x7));
+
+        // Test a valid value after testing invalid to ensure both cases work
+        // Set bits 17:14 to 2 (valid: Device)
+        raw = (raw & !::kernel::bits::genmask_u64(14..=17)) | (0x2 << 14);
+        let valid_pte = TestPageTableEntry::new(raw);
+        assert_eq!(valid_pte.extended_type(), Ok(MemoryType::Device));
+
+        let max_pfn = ::kernel::bits::genmask_u64(0..=39);
+        pte = pte.set_pfn(max_pfn);
+        assert_eq!(pte.pfn(), max_pfn);
+        assert_eq!(pte.pfn_overlap(), max_pfn);
+    }
+
+    #[test]
+    fn test_builder_pattern() {
+        let pte = TestPageTableEntry::default()
+            .set_present(true)
+            .set_writable(true)
+            .set_available(0x7)
+            .set_pfn(0xABCDEF)
+            .set_mem_type(MemoryType::Reserved)
+            .set_available2(0x3FF);
+
+        assert!(pte.present());
+        assert!(pte.writable());
+        assert_eq!(pte.available(), 0x7);
+        assert_eq!(pte.pfn(), 0xABCDEF);
+        assert_eq!(pte.pfn_overlap(), 0xABCDEF);
+        assert_eq!(pte.mem_type(), Ok(MemoryType::Reserved));
+        assert_eq!(pte.available2(), 0x3FF);
+    }
+
+    #[test]
+    fn test_raw_operations() {
+        let raw_value = 0x3FF0000003123E03u64;
+
+        let pte = TestPageTableEntry::new(raw_value);
+        assert_eq!(pte.raw(), raw_value);
+
+        assert!(pte.present());
+        assert!(pte.writable());
+        assert_eq!(pte.available(), 0x7);
+        assert_eq!(pte.pfn(), 0x3123);
+        assert_eq!(pte.pfn_overlap(), 0x3123);
+        assert_eq!(pte.mem_type(), Ok(MemoryType::Reserved));
+        assert_eq!(pte.available2(), 0x3FF);
+
+        // Test using direct constructor syntax TestStruct(value)
+        let pte2 = TestPageTableEntry::new(raw_value);
+        assert_eq!(pte2.raw(), raw_value);
+    }
+
+    #[test]
+    fn test_u16_bitfield() {
+        let mut ctrl = TestControlRegister::default();
+
+        assert!(!ctrl.enable());
+        assert_eq!(ctrl.mode(), 0);
+        assert_eq!(ctrl.priority(), Priority::Low);
+        assert_eq!(ctrl.priority_nibble(), 0);
+        assert_eq!(ctrl.channel(), 0);
+
+        ctrl = ctrl.set_enable(true);
+        assert!(ctrl.enable());
+
+        ctrl = ctrl.set_mode(0x5);
+        assert_eq!(ctrl.mode(), 0x5);
+
+        // Test From conversion with =>
+        ctrl = ctrl.set_priority(Priority::High);
+        assert_eq!(ctrl.priority(), Priority::High);
+        assert_eq!(ctrl.priority_nibble(), 0x2); // High = 2 in bits 5:4
+
+        ctrl = ctrl.set_channel(0xAB);
+        assert_eq!(ctrl.channel(), 0xAB);
+
+        // Test overlapping fields
+        ctrl = ctrl.set_priority_nibble(0xF);
+        assert_eq!(ctrl.priority_nibble(), 0xF);
+        assert_eq!(ctrl.priority(), Priority::Critical); // bits 5:4 = 0x3
+
+        let ctrl2 = TestControlRegister::default()
+            .set_enable(true)
+            .set_mode(0x3)
+            .set_priority(Priority::Medium)
+            .set_channel(0x42);
+
+        assert!(ctrl2.enable());
+        assert_eq!(ctrl2.mode(), 0x3);
+        assert_eq!(ctrl2.priority(), Priority::Medium);
+        assert_eq!(ctrl2.channel(), 0x42);
+
+        let raw_value: u16 = 0x4217;
+        let ctrl3 = TestControlRegister::new(raw_value);
+        assert_eq!(ctrl3.raw(), raw_value);
+        assert!(ctrl3.enable());
+        assert_eq!(ctrl3.priority(), Priority::Medium);
+        assert_eq!(ctrl3.priority_nibble(), 0x1);
+        assert_eq!(ctrl3.channel(), 0x42);
+    }
+
+    #[test]
+    fn test_u8_bitfield() {
+        let mut status = TestStatusRegister::default();
+
+        assert!(!status.ready());
+        assert!(!status.error());
+        assert_eq!(status.state(), 0);
+        assert_eq!(status.reserved(), 0);
+        assert_eq!(status.full_byte(), 0);
+
+        status = status.set_ready(true);
+        assert!(status.ready());
+        assert_eq!(status.full_byte(), 0x01);
+
+        status = status.set_error(true);
+        assert!(status.error());
+        assert_eq!(status.full_byte(), 0x03);
+
+        status = status.set_state(0x3);
+        assert_eq!(status.state(), 0x3);
+        assert_eq!(status.full_byte(), 0x0F);
+
+        status = status.set_reserved(0xA);
+        assert_eq!(status.reserved(), 0xA);
+        assert_eq!(status.full_byte(), 0xAF);
+
+        // Test overlapping field
+        status = status.set_full_byte(0x55);
+        assert_eq!(status.full_byte(), 0x55);
+        assert!(status.ready());
+        assert!(!status.error());
+        assert_eq!(status.state(), 0x1);
+        assert_eq!(status.reserved(), 0x5);
+
+        let status2 = TestStatusRegister::default()
+            .set_ready(true)
+            .set_state(0x2)
+            .set_reserved(0x5);
+
+        assert!(status2.ready());
+        assert!(!status2.error());
+        assert_eq!(status2.state(), 0x2);
+        assert_eq!(status2.reserved(), 0x5);
+        assert_eq!(status2.full_byte(), 0x59);
+
+        let raw_value: u8 = 0x59;
+        let status3 = TestStatusRegister::new(raw_value);
+        assert_eq!(status3.raw(), raw_value);
+        assert!(status3.ready());
+        assert!(!status3.error());
+        assert_eq!(status3.state(), 0x2);
+        assert_eq!(status3.reserved(), 0x5);
+        assert_eq!(status3.full_byte(), 0x59);
+
+        let status4 = TestStatusRegister::new(0xFF);
+        assert!(status4.ready());
+        assert!(status4.error());
+        assert_eq!(status4.state(), 0x3);
+        assert_eq!(status4.reserved(), 0xF);
+        assert_eq!(status4.full_byte(), 0xFF);
+    }
+}
-- 
2.34.1


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

* [PATCH v5 7/9] rust: bitfield: Use 'as' operator for setter type conversion
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
                   ` (5 preceding siblings ...)
  2025-09-30 14:45 ` [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield Joel Fernandes
@ 2025-09-30 14:45 ` Joel Fernandes
  2025-09-30 14:45 ` [PATCH v5 8/9] rust: bitfield: Add hardening for out of bounds access Joel Fernandes
                   ` (3 subsequent siblings)
  10 siblings, 0 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 14:45 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Joel Fernandes,
	Timur Tabi, joel, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau

The bitfield macro's setter accesors currently uses the From trait for
type conversion, which is overly restrictive and prevents use cases such
as narrowing conversions (e.g., u8 struct storage size does not work
with 'as u32' for the field size).

Replace 'from' with 'as' in the setter implementation to support this.

An example of such a bitfield struct is:

    bitfield! {
        struct TestWideFields: u8 {
            3:0       nibble      as u32;
            7:4       high_nibble as u32;
            7:0       full        as u64;
        }
    }

Note that there is already no requirement to have the total size of all
the 'as <type>' fields to be <= the struct's storage width. For example,
it is already possible to have a u8 sized struct, with two 'as u8'
fields.  So the struct's width is already independent of the total width
of the 'as uXX' instances.

Link: https://lore.kernel.org/all/aMIqGBoNaJ7rUrYQ@yury/
Suggested-by: Yury Norov <yury.norov@gmail.com>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
---
 rust/kernel/bitfield.rs | 37 ++++++++++++++++++++++++++++++++++---
 1 file changed, 34 insertions(+), 3 deletions(-)

diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
index 9a20bcd2eb60..a74e6d45ecd3 100644
--- a/rust/kernel/bitfield.rs
+++ b/rust/kernel/bitfield.rs
@@ -107,8 +107,6 @@ pub const fn into_raw(self) -> T {
 /// - Raw accessor: `raw()` - returns the underlying raw value
 /// - Field accessors: `mode()`, `state()`, etc.
 /// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern).
-///   Note that the compiler will error out if the size of the setter's arg exceeds the
-///   struct's storage size.
 /// - Debug and Default implementations.
 ///
 /// Note: Field accessors and setters inherit the same visibility as the struct itself.
@@ -360,7 +358,9 @@ impl $name {
         $vis fn [<set_ $field>](mut self, value: $to_type) -> Self {
             const MASK: $storage = $name::[<$field:upper _MASK>];
             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
-            let val = (<$storage>::from(value) << SHIFT) & MASK;
+            // Here we are potentially narrowing value from a wider bit value
+            // to a narrower bit value. So we have to use `as` instead of `::from()`.
+            let val = ((value as $storage) << SHIFT) & MASK;
             let new_val = (self.raw() & !MASK) | val;
             self.0 = ::kernel::bitfield::BitfieldInternalStorage::from_raw(new_val);
 
@@ -505,6 +505,15 @@ struct TestStatusRegister(u8) {
         }
     }
 
+    // For testing wide field types on narrow storage
+    bitfield! {
+        struct TestWideFields(u8) {
+            3:0       nibble      as u32;
+            7:4       high_nibble as u32;
+            7:0       full        as u64;
+        }
+    }
+
     #[test]
     fn test_single_bits() {
         let mut pte = TestPageTableEntry::default();
@@ -722,4 +731,26 @@ fn test_u8_bitfield() {
         assert_eq!(status4.reserved(), 0xF);
         assert_eq!(status4.full_byte(), 0xFF);
     }
+
+    #[test]
+    fn test_wide_field_types() {
+        let mut wf = TestWideFields::default();
+
+        wf = wf.set_nibble(0x0000000F_u32);
+        assert_eq!(wf.nibble(), 0x0000000F_u32);
+
+        wf = wf.set_high_nibble(0x00000007_u32);
+        assert_eq!(wf.high_nibble(), 0x00000007_u32);
+
+        wf = wf.set_full(0xBE_u64);
+        assert_eq!(wf.full(), 0xBE_u64);
+        assert_eq!(wf.raw(), 0xBE_u8);
+
+        wf = TestWideFields::default()
+            .set_nibble(0x5_u32)
+            .set_high_nibble(0xA_u32);
+        assert_eq!(wf.raw(), 0xA5_u8);
+        assert_eq!(wf.nibble(), 0x5_u32);
+        assert_eq!(wf.high_nibble(), 0xA_u32);
+    }
 }
-- 
2.34.1


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

* [PATCH v5 8/9] rust: bitfield: Add hardening for out of bounds access
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
                   ` (6 preceding siblings ...)
  2025-09-30 14:45 ` [PATCH v5 7/9] rust: bitfield: Use 'as' operator for setter type conversion Joel Fernandes
@ 2025-09-30 14:45 ` Joel Fernandes
  2025-09-30 18:03   ` Yury Norov
  2025-09-30 14:45 ` [PATCH v5 9/9] rust: bitfield: Add hardening for undefined bits Joel Fernandes
                   ` (2 subsequent siblings)
  10 siblings, 1 reply; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 14:45 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Joel Fernandes,
	Timur Tabi, joel, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau

Similar to bitmap.rs, add hardening to print errors or assert if the
setter API is used to write out-of-bound values.

Suggested-by: Yury Norov <yury.norov@gmail.com>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
---
 rust/kernel/bitfield.rs    | 32 +++++++++++++++++++++++++++++++-
 security/Kconfig.hardening |  9 +++++++++
 2 files changed, 40 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
index a74e6d45ecd3..655f940479f1 100644
--- a/rust/kernel/bitfield.rs
+++ b/rust/kernel/bitfield.rs
@@ -29,6 +29,20 @@ pub const fn into_raw(self) -> T {
     }
 }
 
+/// Assertion macro for bitfield
+#[macro_export]
+macro_rules! bitfield_assert {
+    ($cond:expr, $($arg:tt)+) => {
+        #[cfg(CONFIG_RUST_BITFIELD_HARDENED)]
+        ::core::assert!($cond, $($arg)*);
+
+        #[cfg(not(CONFIG_RUST_BITFIELD_HARDENED))]
+        if !($cond) {
+            $crate::pr_err!($($arg)+);
+        }
+    }
+}
+
 /// Bitfield macro definition.
 /// Define a struct with accessors to access bits within an inner unsigned integer.
 ///
@@ -358,9 +372,25 @@ impl $name {
         $vis fn [<set_ $field>](mut self, value: $to_type) -> Self {
             const MASK: $storage = $name::[<$field:upper _MASK>];
             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
+            const BITS: u32 = ($hi - $lo + 1) as u32;
+            const MAX_VALUE: $storage =
+                if BITS >= (::core::mem::size_of::<$storage>() * 8) as u32 {
+                    !0
+                } else {
+                    (1 << BITS) - 1
+                };
+
+            // Check for overflow - value should fit within the field's bits.
             // Here we are potentially narrowing value from a wider bit value
             // to a narrower bit value. So we have to use `as` instead of `::from()`.
-            let val = ((value as $storage) << SHIFT) & MASK;
+            let raw_field_value = value as $storage;
+
+            $crate::bitfield_assert!(
+                raw_field_value <= MAX_VALUE,
+                "value {} exceeds {} for a {} bit field", raw_field_value, MAX_VALUE, BITS
+            );
+
+            let val = (raw_field_value << SHIFT) & MASK;
             let new_val = (self.raw() & !MASK) | val;
             self.0 = ::kernel::bitfield::BitfieldInternalStorage::from_raw(new_val);
 
diff --git a/security/Kconfig.hardening b/security/Kconfig.hardening
index 86f8768c63d4..e9fc6dcbd6c3 100644
--- a/security/Kconfig.hardening
+++ b/security/Kconfig.hardening
@@ -265,6 +265,15 @@ config RUST_BITMAP_HARDENED
 
 	  If unsure, say N.
 
+config RUST_BITFIELD_HARDENED
+	bool "Check integrity of bitfield Rust API"
+	depends on RUST
+	help
+	  Enables additional assertions in the Rust Bitfield API to catch
+	  values that exceed the bitfield bounds.
+
+	  If unsure, say N.
+
 config BUG_ON_DATA_CORRUPTION
 	bool "Trigger a BUG when data corruption is detected"
 	select LIST_HARDENED
-- 
2.34.1


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

* [PATCH v5 9/9] rust: bitfield: Add hardening for undefined bits
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
                   ` (7 preceding siblings ...)
  2025-09-30 14:45 ` [PATCH v5 8/9] rust: bitfield: Add hardening for out of bounds access Joel Fernandes
@ 2025-09-30 14:45 ` Joel Fernandes
  2025-09-30 15:08 ` [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Danilo Krummrich
  2025-10-02  1:24 ` Alexandre Courbot
  10 siblings, 0 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 14:45 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Joel Fernandes,
	Timur Tabi, joel, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau

When creating a new bitfield, it is possible that the value contains
bits set. Such usage can be the result of an error in the usage of the
bitfield. Print an error in regular configs, and assert in a hardened config
(CONFIG_RUST_BITFIELD_HARDENED). If the design is deliberate, the user may
silence these errors or assertions by defining the bitfield as reserved.

Suggested-by: Yury Norov <yury.norov@gmail.com>
Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
---
 rust/kernel/bitfield.rs | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
index 655f940479f1..606494bf4245 100644
--- a/rust/kernel/bitfield.rs
+++ b/rust/kernel/bitfield.rs
@@ -117,7 +117,9 @@ macro_rules! bitfield_assert {
 /// ```
 ///
 /// This generates a struct with:
-/// - Constructor: `new(value)` - creates a bitfield from a raw value, zeroing undefined bits
+/// - Constructor: `new(value)` - creates a bitfield from a raw value, zeroing undefined bits.
+///   If any of the bits passed are set, but not defined as a bitfield, an error is printed.
+///   To silence these errors, either define all fields or initialize the bit positions to 0.
 /// - Raw accessor: `raw()` - returns the underlying raw value
 /// - Field accessors: `mode()`, `state()`, etc.
 /// - Field setters: `set_mode()`, `set_state()`, etc. (supports chaining with builder pattern).
@@ -236,6 +238,10 @@ impl $name {
             /// This constructor zeros out all bits that are not defined by any field,
             /// ensuring only valid field bits are preserved. This is to prevent UB
             /// when raw() is used to retrieve undefined bits.
+            ///
+            /// If any of the bits passed are set, but not defined as a bitfield,
+            /// an error is printed. To silence these errors, either define all fields
+            /// or initialize the respective bit positions to 0.
             #[inline(always)]
             $vis fn new(value: $storage) -> Self {
                 // Calculate mask for all defined fields
@@ -245,6 +251,18 @@ impl $name {
                         mask |= Self::[<$field:upper _MASK>];
                     );
                 )*
+
+                // Check if any undefined bits are set
+                $crate::bitfield_assert!(
+                    (value & !mask) == 0,
+                    concat!(
+                        "Value 0x{:x} has bits set outside of defined field ranges ",
+                        "(mask: 0x{:x}). To avoid this assertion, either define all ",
+                        "fields or initialize unused bits to 0."
+                    ),
+                    value, mask
+                );
+
                 // Zero out undefined bits and wrap in BitfieldInternalStorage
                 Self(::kernel::bitfield::BitfieldInternalStorage::from_raw(value & mask))
             }
-- 
2.34.1


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

* Re: [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
                   ` (8 preceding siblings ...)
  2025-09-30 14:45 ` [PATCH v5 9/9] rust: bitfield: Add hardening for undefined bits Joel Fernandes
@ 2025-09-30 15:08 ` Danilo Krummrich
  2025-10-02  1:24 ` Alexandre Courbot
  10 siblings, 0 replies; 27+ messages in thread
From: Danilo Krummrich @ 2025-09-30 15:08 UTC (permalink / raw)
  To: Joel Fernandes
  Cc: linux-kernel, rust-for-linux, dri-devel, acourbot,
	Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Yury Norov, Daniel Almeida, Andrea Righi, nouveau

On Tue Sep 30, 2025 at 4:45 PM CEST, Joel Fernandes wrote:
>  MAINTAINERS                                   |   7 +
>  drivers/gpu/nova-core/falcon.rs               |   2 +-
>  drivers/gpu/nova-core/falcon/gsp.rs           |   4 +-
>  drivers/gpu/nova-core/falcon/sec2.rs          |   2 +-
>  drivers/gpu/nova-core/regs.rs                 |   6 +-
>  rust/kernel/bitfield.rs                       | 804 ++++++++++++++++++
>  rust/kernel/io.rs                             |   1 +
>  .../macros.rs => rust/kernel/io/register.rs   | 317 +------
>  rust/kernel/lib.rs                            |   1 +
>  security/Kconfig.hardening                    |   9 +
>  10 files changed, 870 insertions(+), 283 deletions(-)
>  create mode 100644 rust/kernel/bitfield.rs
>  rename drivers/gpu/nova-core/regs/macros.rs => rust/kernel/io/register.rs (72%)

I think we have at least three or four potential target trees for this:
driver-core (I/O), drm-rust (Nova), bitmap / Rust.

(I don't know which tree the bitmap stuff would go through, I did not find a
tree entry in the MAINTAINERS file.)

Unless someone thinks otherwise, I'd take it through the drm-rust tree once the
series is ready. This should cause the least conflicts and as a bonus enable Tyr
to use it right away.

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

* Re: [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths
  2025-09-30 14:45 ` [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths Joel Fernandes
@ 2025-09-30 17:18   ` Joel Fernandes
  2025-10-02  1:17   ` Alexandre Courbot
  1 sibling, 0 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 17:18 UTC (permalink / raw)
  To: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Yury Norov, Daniel Almeida, Andrea Righi, nouveau



On 9/30/2025 10:45 AM, Joel Fernandes wrote:
> Previously, bitfields were hardcoded to use u32 as the underlying
> storage type.  Add support for different storage types (u8, u16, u32,
> u64) to the bitfield macro.
> 
> New syntax is: struct Name: <type ex., u32> { ... }

Apologies for not updating this commit message, the syntax is:

struct Name(<type ex., u32>) { ... }

thanks,

 - Joel

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

* Re: [PATCH v5 8/9] rust: bitfield: Add hardening for out of bounds access
  2025-09-30 14:45 ` [PATCH v5 8/9] rust: bitfield: Add hardening for out of bounds access Joel Fernandes
@ 2025-09-30 18:03   ` Yury Norov
  2025-09-30 22:06     ` Joel Fernandes
  0 siblings, 1 reply; 27+ messages in thread
From: Yury Norov @ 2025-09-30 18:03 UTC (permalink / raw)
  To: Joel Fernandes
  Cc: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot,
	Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Daniel Almeida, Andrea Righi, nouveau

On Tue, Sep 30, 2025 at 10:45:36AM -0400, Joel Fernandes wrote:
> Similar to bitmap.rs, add hardening to print errors or assert if the
> setter API is used to write out-of-bound values.
> 
> Suggested-by: Yury Norov <yury.norov@gmail.com>
> Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
> ---
>  rust/kernel/bitfield.rs    | 32 +++++++++++++++++++++++++++++++-
>  security/Kconfig.hardening |  9 +++++++++
>  2 files changed, 40 insertions(+), 1 deletion(-)
> 
> diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
> index a74e6d45ecd3..655f940479f1 100644
> --- a/rust/kernel/bitfield.rs
> +++ b/rust/kernel/bitfield.rs
> @@ -29,6 +29,20 @@ pub const fn into_raw(self) -> T {
>      }
>  }
>  
> +/// Assertion macro for bitfield
> +#[macro_export]
> +macro_rules! bitfield_assert {
> +    ($cond:expr, $($arg:tt)+) => {
> +        #[cfg(CONFIG_RUST_BITFIELD_HARDENED)]
> +        ::core::assert!($cond, $($arg)*);
> +
> +        #[cfg(not(CONFIG_RUST_BITFIELD_HARDENED))]
> +        if !($cond) {
> +            $crate::pr_err!($($arg)+);
> +        }
> +    }
> +}

Can you discuss performance implication? I'm OK if you decided to make
the check always on, but we need to understand the cost of it.

>  /// Bitfield macro definition.
>  /// Define a struct with accessors to access bits within an inner unsigned integer.
>  ///
> @@ -358,9 +372,25 @@ impl $name {
>          $vis fn [<set_ $field>](mut self, value: $to_type) -> Self {
>              const MASK: $storage = $name::[<$field:upper _MASK>];
>              const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
> +            const BITS: u32 = ($hi - $lo + 1) as u32;
> +            const MAX_VALUE: $storage =
> +                if BITS >= (::core::mem::size_of::<$storage>() * 8) as u32 {

If BITS > storage then it should be a compile time error. Can you
elaborate under which condition this check makes sense, and is not
covered with the "(1<<BITS) - 1" case?

> +                    !0
> +                } else {
> +                    (1 << BITS) - 1
> +                };
> +
> +            // Check for overflow - value should fit within the field's bits.
>              // Here we are potentially narrowing value from a wider bit value
>              // to a narrower bit value. So we have to use `as` instead of `::from()`.

The new comment sounds opposite to the old one: if you check for
overflow, then there's no chance to "potentially narrow the value".

This "potentially" wording simply means undefined behavior.

> -            let val = ((value as $storage) << SHIFT) & MASK;
> +            let raw_field_value = value as $storage;
> +
> +            $crate::bitfield_assert!(
> +                raw_field_value <= MAX_VALUE,
> +                "value {} exceeds {} for a {} bit field", raw_field_value, MAX_VALUE, BITS
> +            );

Can you hide all the internals in the assertion function? Like:

            $crate::bitfield_set_assert!(bitfield, field, value, "your message", ...);

We don't need assertion implementation in the main function body.

> +
> +            let val = (raw_field_value << SHIFT) & MASK;
>              let new_val = (self.raw() & !MASK) | val;
>         all the internals in the assertion     self.0 = ::kernel::bitfield::BitfieldInternalStorage::from_raw(new_val);

User wants to set an inappropriate value, and you know that because
you just have tested for it. But here you're accepting a definitely
wrong request. This doesn't look right.

On previous rounds you said you can't fail in setter because that
would break the "chain of setters" design. I understand that, but I
think that it's more important to have a clear defensive API that
returns an error when people do wrong things.

So please either find a way to return an error from the setter, or
some other mechanism to abort erroneous request and notify the user.

This "chain of setters" thing looks weird to me as I already said. So
if it messes with a clear API, just drop it.

And to that extend,

        a = a.set_field1()

looks more questionable than just

        a.set_field1()

because it implies an extra copy. If I do 

        b = a.set_field1()

would it change the content of 'a'?

Can I do just 'a.set_field1()'? There's no such an example in your
test.

Is that 'a = a.set_field()' thing really a zero-cost comparing to just
'a.set_field()'? Can you ensure it holds, say, on 32-bit machine when
'a' is a 64-bit bitfield? Would it work if we decide to support
bitfields larger than 64-bit, like C does?

Thanks,
Yury

> diff --git a/security/Kconfig.hardening b/security/Kconfig.hardening
> index 86f8768c63d4..e9fc6dcbd6c3 100644
> --- a/security/Kconfig.hardening
> +++ b/security/Kconfig.hardening
> @@ -265,6 +265,15 @@ config RUST_BITMAP_HARDENED
>  
>  	  If unsure, say N.
>  
> +config RUST_BITFIELD_HARDENED
> +	bool "Check integrity of bitfield Rust API"
> +	depends on RUST
> +	help
> +	  Enables additional assertions in the Rust Bitfield API to catch
> +	  values that exceed the bitfield bounds.
> +
> +	  If unsure, say N.
> +
>  config BUG_ON_DATA_CORRUPTION
>  	bool "Trigger a BUG when data corruption is detected"
>  	select LIST_HARDENED
> -- 
> 2.34.1

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

* Re: [PATCH v5 8/9] rust: bitfield: Add hardening for out of bounds access
  2025-09-30 18:03   ` Yury Norov
@ 2025-09-30 22:06     ` Joel Fernandes
  0 siblings, 0 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-09-30 22:06 UTC (permalink / raw)
  To: Yury Norov
  Cc: linux-kernel, rust-for-linux, dri-devel, dakr, acourbot,
	Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Daniel Almeida, Andrea Righi, nouveau

Hello, Yury,

On 9/30/2025 2:03 PM, Yury Norov wrote:
> On Tue, Sep 30, 2025 at 10:45:36AM -0400, Joel Fernandes wrote:
>> Similar to bitmap.rs, add hardening to print errors or assert if the
>> setter API is used to write out-of-bound values.
>>
>> Suggested-by: Yury Norov <yury.norov@gmail.com>
>> Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
>> ---
>>  rust/kernel/bitfield.rs    | 32 +++++++++++++++++++++++++++++++-
>>  security/Kconfig.hardening |  9 +++++++++
>>  2 files changed, 40 insertions(+), 1 deletion(-)
>>
>> diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
>> index a74e6d45ecd3..655f940479f1 100644
>> --- a/rust/kernel/bitfield.rs
>> +++ b/rust/kernel/bitfield.rs
>> @@ -29,6 +29,20 @@ pub const fn into_raw(self) -> T {
>>      }
>>  }
>>  
>> +/// Assertion macro for bitfield
>> +#[macro_export]
>> +macro_rules! bitfield_assert {
>> +    ($cond:expr, $($arg:tt)+) => {
>> +        #[cfg(CONFIG_RUST_BITFIELD_HARDENED)]
>> +        ::core::assert!($cond, $($arg)*);
>> +
>> +        #[cfg(not(CONFIG_RUST_BITFIELD_HARDENED))]
>> +        if !($cond) {
>> +            $crate::pr_err!($($arg)+);
>> +        }
>> +    }
>> +}
> 
> Can you discuss performance implication? I'm OK if you decided to make
> the check always on, but we need to understand the cost of it.

Sure, so the cost is zero if either CONFIG_RUST_BITFIELD_HARDENED is disabled or
the value being checked is a constant. That is, the compiler eliminates the dead
code. Otherwise the cost is a single shift instruction and a single conditional
jump on x86. I verified this. As such, I think it is a good idea to keep the
check on.

> 
>>  /// Bitfield macro definition.
>>  /// Define a struct with accessors to access bits within an inner unsigned integer.
>>  ///
>> @@ -358,9 +372,25 @@ impl $name {
>>          $vis fn [<set_ $field>](mut self, value: $to_type) -> Self {
>>              const MASK: $storage = $name::[<$field:upper _MASK>];
>>              const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
>> +            const BITS: u32 = ($hi - $lo + 1) as u32;
>> +            const MAX_VALUE: $storage =
>> +                if BITS >= (::core::mem::size_of::<$storage>() * 8) as u32 {
> 
> If BITS > storage then it should be a compile time error.

Yes, that case is a compile time error.

> Can you> elaborate under which condition this check makes sense, and is not
> covered with the "(1<<BITS) - 1" case?
If BITS is 64, then the else should not execute, because it would become (1 <<
64) which is UB.

I am Ok with changing the condition to: "if BITS ==
(::core::mem::size_of::<$storage>() * 8)" considering the compiler time error,
but I am also Ok with leaving it as it is.


> 
>> +                    !0
>> +                } else {
>> +                    (1 << BITS) - 1
>> +                };
>> +
>> +            // Check for overflow - value should fit within the field's bits.
>>              // Here we are potentially narrowing value from a wider bit value
>>              // to a narrower bit value. So we have to use `as` instead of `::from()`.
> 
> The new comment sounds opposite to the old one: if you check for
> overflow, then there's no chance to "potentially narrow the value".

No, this a compile-time issue. Even if there is no overflow, you cannot use
'::from()' because it will cause a compile-time error because it is narrowing
potentially a wider width (like u32) to a narrower width (like u8). It is not so
much about the value itself, as much as it is about the type of value.

> 
> This "potentially" wording simply means undefined behavior.
> 
>> -            let val = ((value as $storage) << SHIFT) & MASK;
>> +            let raw_field_value = value as $storage;
>> +
>> +            $crate::bitfield_assert!(
>> +                raw_field_value <= MAX_VALUE,
>> +                "value {} exceeds {} for a {} bit field", raw_field_value, MAX_VALUE, BITS
>> +            );
> 
> Can you hide all the internals in the assertion function? Like:
> 
>             $crate::bitfield_set_assert!(bitfield, field, value, "your message", ...);
> 
> We don't need assertion implementation in the main function body.

Why? That's more unreadable IMO. Having the condition itself in the assert,
clearly shows what the condition is in the context of the surrounding code. I
don't think we should more macros to do asserts when we already have a macro.

> 
>> +
>> +            let val = (raw_field_value << SHIFT) & MASK;
>>              let new_val = (self.raw() & !MASK) | val;
>>         all the internals in the assertion     self.0 = ::kernel::bitfield::BitfieldInternalStorage::from_raw(new_val);
> 
> User wants to set an inappropriate value, and you know that because
> you just have tested for it. But here you're accepting a definitely
> wrong request. This doesn't look right.
> 
> On previous rounds you said you can't fail in setter because that
> would break the "chain of setters" design. I understand that, but I
> think that it's more important to have a clear defensive API that
> returns an error when people do wrong things.
> 
> So please either find a way to return an error from the setter, or
> some other mechanism to abort erroneous request and notify the user.

There's no way to do that other than always panicking, or introducing a new API.
 There's also no way to do this at compile time, because 'value' may not always
be a constant.

I see your point, but I think since we already panicking at runtime in a
hardened config (or printing an error otherwise), we already have that covered
right? The user is already notified and it does not go by silently. If this is
really a problem, we can always panic (in other words, always keep it as
hardened config?).

> 
> This "chain of setters" thing looks weird to me as I already said. So
> if it messes with a clear API, just drop it.

I don't think we can/should drop that because this library is also used by the
register macro, and that uses the setter API (I just moved this code from
there). Also builder pattern is a common paradigm in Rust programs and I'd say
one of the key features of the bitfield macro so we should support it.

How else will you do something like:

        let status2 = TestStruct::default()
            .set_ready(true)
            .set_state(0x2)
            .set_reserved(0x5);

? :-)

As an aside, you can check literature on the builder pattern as well, it keeps
code super clean and readable.

> 
> And to that extend,
> 
>         a = a.set_field1()
> 
> looks more questionable than just
> 
>         a.set_field1()
> 
> because it implies an extra copy.

a.set_field1() on its own wont work, because the value returned (self) is discarded.

and,
a = a.set_field1()
a = a.set_field2()
a = a.set_field3()

doesn't really do multiple copies, the compiler optimizes things and eliminates
copies. I verified this in the asm as well.

> If I do 
> 
>         b = a.set_field1()
> 
> would it change the content of 'a'?
> 
> Can I do just 'a.set_field1()'? There's no such an example in your
> test.
> Is that 'a = a.set_field()' thing really a zero-cost comparing to just
> 'a.set_field()'?

You can't do that in the current implementation, it is a NO-OP. We can certainly
add a new API for that, initially I was planning to do add a 'with_field*()'
accessor for the builder pattern, and do the 'set_field*()' API as you mentioned.

So it would look like:

        let status2 = TestStruct::default()
            .with_ready(true)
            .with_state(0x2)
            .with_reserved(0x5);

Or one could do:
        let status2 = TestStruct::default();
        status2.set_ready(true);
        status2.set_state(0x2);
        status2.set_reserved(0x5);

Would that address your concern?

> Can you ensure it holds, say, on 32-bit machine when> 'a' is a 64-bit bitfield?

I don't think this is an issue. If the user writes a = a.set_fieldXX() multiple
times, it will be optimized as I mentioned above. I have verified (in release
builds) that the compiler does not create multiple intermediate copies.

> Would it work if we decide to support bitfields larger than 64-bit, like C does?

Certainly, the struct has the Copy trait. 'a = a.set_field()' will work for
larger than 64-bit just fine, if/when we support it. I verified that as well.

thanks,

 - Joel



> Thanks,
> Yury
> 
>> diff --git a/security/Kconfig.hardening b/security/Kconfig.hardening
>> index 86f8768c63d4..e9fc6dcbd6c3 100644
>> --- a/security/Kconfig.hardening
>> +++ b/security/Kconfig.hardening
>> @@ -265,6 +265,15 @@ config RUST_BITMAP_HARDENED
>>  
>>  	  If unsure, say N.
>>  
>> +config RUST_BITFIELD_HARDENED
>> +	bool "Check integrity of bitfield Rust API"
>> +	depends on RUST
>> +	help
>> +	  Enables additional assertions in the Rust Bitfield API to catch
>> +	  values that exceed the bitfield bounds.
>> +
>> +	  If unsure, say N.
>> +
>>  config BUG_ON_DATA_CORRUPTION
>>  	bool "Trigger a BUG when data corruption is detected"
>>  	select LIST_HARDENED
>> -- 
>> 2.34.1


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

* Re: [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths
  2025-09-30 14:45 ` [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths Joel Fernandes
  2025-09-30 17:18   ` Joel Fernandes
@ 2025-10-02  1:17   ` Alexandre Courbot
  1 sibling, 0 replies; 27+ messages in thread
From: Alexandre Courbot @ 2025-10-02  1:17 UTC (permalink / raw)
  To: Joel Fernandes, linux-kernel, rust-for-linux, dri-devel, dakr,
	acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Yury Norov, Daniel Almeida, Andrea Righi, nouveau

On Tue Sep 30, 2025 at 11:45 PM JST, Joel Fernandes wrote:
> Previously, bitfields were hardcoded to use u32 as the underlying
> storage type.  Add support for different storage types (u8, u16, u32,
> u64) to the bitfield macro.
>
> New syntax is: struct Name: <type ex., u32> { ... }

With the to the line above mentioned in your reply,

Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>

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

* Re: [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/
  2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
                   ` (9 preceding siblings ...)
  2025-09-30 15:08 ` [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Danilo Krummrich
@ 2025-10-02  1:24 ` Alexandre Courbot
  2025-10-02  1:26   ` Alexandre Courbot
  10 siblings, 1 reply; 27+ messages in thread
From: Alexandre Courbot @ 2025-10-02  1:24 UTC (permalink / raw)
  To: Joel Fernandes, linux-kernel, rust-for-linux, dri-devel, dakr,
	acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Yury Norov, Daniel Almeida, Andrea Righi, nouveau

On Tue Sep 30, 2025 at 11:45 PM JST, Joel Fernandes wrote:
> Hello!
>
> These patches extract and enhance the bitfield support in the register macro in
> nova to define Rust structures with bitfields. It then moves out the bitfield
> support into the kenrel crate and further enhances it. This is extremely useful
> as it allows clean Rust structure definitions without requiring explicit masks
> and shifts.

The extraction and move in themselves (patches 1-4 and maybe the KUNIT
one) look good to me. For the remainder, it will depend on whether the
BoundedInt idea sticks or not as it changes the design in a way that
makes most of these patches unneeded. In any case I think this can be
worked on after the split and extraction.

Patch 5 should probably be dropped as it has the potential to clear
register fields that are useful to the hardware but have no entry in the
`register!` definition, making read-update-write updates of registers
unpredictable.

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

* Re: [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/
  2025-10-02  1:24 ` Alexandre Courbot
@ 2025-10-02  1:26   ` Alexandre Courbot
  2025-10-03 15:26     ` Joel Fernandes
  0 siblings, 1 reply; 27+ messages in thread
From: Alexandre Courbot @ 2025-10-02  1:26 UTC (permalink / raw)
  To: Alexandre Courbot, Joel Fernandes, linux-kernel, rust-for-linux,
	dri-devel, dakr
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Yury Norov, Daniel Almeida, Andrea Righi, nouveau

On Thu Oct 2, 2025 at 10:24 AM JST, Alexandre Courbot wrote:
> On Tue Sep 30, 2025 at 11:45 PM JST, Joel Fernandes wrote:
>> Hello!
>>
>> These patches extract and enhance the bitfield support in the register macro in
>> nova to define Rust structures with bitfields. It then moves out the bitfield
>> support into the kenrel crate and further enhances it. This is extremely useful
>> as it allows clean Rust structure definitions without requiring explicit masks
>> and shifts.
>
> The extraction and move in themselves (patches 1-4 and maybe the KUNIT
> one) look good to me. For the remainder, it will depend on whether the
> BoundedInt idea sticks or not as it changes the design in a way that
> makes most of these patches unneeded. In any case I think this can be
> worked on after the split and extraction.
>
> Patch 5 should probably be dropped as it has the potential to clear
> register fields that are useful to the hardware but have no entry in the
> `register!` definition, making read-update-write updates of registers
> unpredictable.

Ah, I forgot: please base the next revision on top of drm-rust-next as
we are likely to apply it there.

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

* Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
  2025-09-30 14:45 ` [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield Joel Fernandes
@ 2025-10-02  1:41   ` Alexandre Courbot
  2025-10-02  2:16     ` Elle Rhumsaa
  2025-10-03 15:23     ` Joel Fernandes
  0 siblings, 2 replies; 27+ messages in thread
From: Alexandre Courbot @ 2025-10-02  1:41 UTC (permalink / raw)
  To: Joel Fernandes, linux-kernel, rust-for-linux, dri-devel, dakr,
	acourbot
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Yury Norov, Daniel Almeida, Andrea Righi, nouveau

On Tue Sep 30, 2025 at 11:45 PM JST, Joel Fernandes wrote:
> Add KUNIT tests to make sure the macro is working correctly.
>
> Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
> ---
>  rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++
>  1 file changed, 321 insertions(+)
>
> diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
> index fed19918c3b9..9a20bcd2eb60 100644
> --- a/rust/kernel/bitfield.rs
> +++ b/rust/kernel/bitfield.rs
> @@ -402,3 +402,324 @@ fn default() -> Self {
>          }
>      };
>  }
> +
> +#[::kernel::macros::kunit_tests(kernel_bitfield)]
> +mod tests {
> +    use core::convert::TryFrom;
> +
> +    // Enum types for testing => and ?=> conversions
> +    #[derive(Debug, Clone, Copy, PartialEq)]
> +    enum MemoryType {
> +        Unmapped = 0,
> +        Normal = 1,
> +        Device = 2,
> +        Reserved = 3,
> +    }
> +
> +    impl Default for MemoryType {
> +        fn default() -> Self {
> +            MemoryType::Unmapped
> +        }
> +    }

Tip: you can add `Default` to the `#[derive]` marker of `MemoryType` and
mark the variant you want as default with `#[default]` instead of
providing a full impl block:

    #[derive(Debug, Default, Clone, Copy, PartialEq)]
    enum MemoryType {
        #[default]
        Unmapped = 0,
        Normal = 1,
        Device = 2,
        Reserved = 3,
    }

> +
> +    impl TryFrom<u8> for MemoryType {
> +        type Error = u8;
> +        fn try_from(value: u8) -> Result<Self, Self::Error> {
> +            match value {
> +                0 => Ok(MemoryType::Unmapped),
> +                1 => Ok(MemoryType::Normal),
> +                2 => Ok(MemoryType::Device),
> +                3 => Ok(MemoryType::Reserved),
> +                _ => Err(value),
> +            }
> +        }
> +    }
> +
> +    impl From<MemoryType> for u64 {
> +        fn from(mt: MemoryType) -> u64 {
> +            mt as u64
> +        }
> +    }
> +
> +    #[derive(Debug, Clone, Copy, PartialEq)]
> +    enum Priority {
> +        Low = 0,
> +        Medium = 1,
> +        High = 2,
> +        Critical = 3,
> +    }
> +
> +    impl Default for Priority {
> +        fn default() -> Self {
> +            Priority::Low
> +        }
> +    }
> +
> +    impl From<u8> for Priority {
> +        fn from(value: u8) -> Self {
> +            match value & 0x3 {
> +                0 => Priority::Low,
> +                1 => Priority::Medium,
> +                2 => Priority::High,
> +                _ => Priority::Critical,
> +            }
> +        }
> +    }
> +
> +    impl From<Priority> for u16 {
> +        fn from(p: Priority) -> u16 {
> +            p as u16
> +        }
> +    }
> +
> +    bitfield! {
> +        struct TestPageTableEntry(u64) {
> +            0:0       present     as bool;
> +            1:1       writable    as bool;
> +            11:9      available   as u8;
> +            13:12     mem_type    as u8 ?=> MemoryType;
> +            17:14     extended_type as u8 ?=> MemoryType;  // For testing failures
> +            51:12     pfn         as u64;
> +            51:12     pfn_overlap as u64;
> +            61:52     available2  as u16;
> +        }
> +    }
> +
> +    bitfield! {
> +        struct TestControlRegister(u16) {
> +            0:0       enable      as bool;
> +            3:1       mode        as u8;
> +            5:4       priority    as u8 => Priority;
> +            7:4       priority_nibble as u8;
> +            15:8      channel     as u8;
> +        }
> +    }
> +
> +    bitfield! {
> +        struct TestStatusRegister(u8) {
> +            0:0       ready       as bool;
> +            1:1       error       as bool;
> +            3:2       state       as u8;
> +            7:4       reserved    as u8;
> +            7:0       full_byte   as u8;  // For entire register
> +        }
> +    }
> +
> +    #[test]
> +    fn test_single_bits() {
> +        let mut pte = TestPageTableEntry::default();
> +
> +        assert!(!pte.present());
> +        assert!(!pte.writable());
> +
> +        pte = pte.set_present(true);
> +        assert!(pte.present());
> +
> +        pte = pte.set_writable(true);
> +        assert!(pte.writable());
> +
> +        pte = pte.set_writable(false);
> +        assert!(!pte.writable());
> +
> +        assert_eq!(pte.available(), 0);
> +        pte = pte.set_available(0x5);
> +        assert_eq!(pte.available(), 0x5);

I'd suggest testing the actual raw value of the register on top of
invoking the getter. That way you also test that:

- The right field is actually written (i.e. if the offset is off by one,
  the getter will return the expected result even though the bitfield
  has the wrong value),
- No other field has been affected.

So something like:

    pte = pte.set_present(true);
    assert!(pte.present());
    assert(pte.into(), 0x1u64);

    pte = pte.set_writable(true);
    assert!(pte.writable());
    assert(pte.into(), 0x3u64);

It might look a bit gross, but it is ok since these are not doctests
that users are going to take as a reference, so we case improve test
coverage at the detriment of readability.


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

* Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
  2025-10-02  1:41   ` Alexandre Courbot
@ 2025-10-02  2:16     ` Elle Rhumsaa
  2025-10-02  2:51       ` Alexandre Courbot
  2025-10-03 15:23     ` Joel Fernandes
  1 sibling, 1 reply; 27+ messages in thread
From: Elle Rhumsaa @ 2025-10-02  2:16 UTC (permalink / raw)
  To: Alexandre Courbot, Joel Fernandes, linux-kernel, rust-for-linux,
	dri-devel, dakr
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Yury Norov, Daniel Almeida, Andrea Righi, nouveau

On 10/2/25 1:41 AM, Alexandre Courbot wrote:

> On Tue Sep 30, 2025 at 11:45 PM JST, Joel Fernandes wrote:
>> Add KUNIT tests to make sure the macro is working correctly.
>>
>> Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
>> ---
>>   rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++
>>   1 file changed, 321 insertions(+)
>>
>> diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
>> index fed19918c3b9..9a20bcd2eb60 100644
>> --- a/rust/kernel/bitfield.rs
>> +++ b/rust/kernel/bitfield.rs
>> @@ -402,3 +402,324 @@ fn default() -> Self {
>>           }
>>       };
>>   }
>> +
>> +#[::kernel::macros::kunit_tests(kernel_bitfield)]
>> +mod tests {
>> +    use core::convert::TryFrom;
>> +
>> +    // Enum types for testing => and ?=> conversions
>> +    #[derive(Debug, Clone, Copy, PartialEq)]
>> +    enum MemoryType {
>> +        Unmapped = 0,
>> +        Normal = 1,
>> +        Device = 2,
>> +        Reserved = 3,
>> +    }
>> +
>> +    impl Default for MemoryType {
>> +        fn default() -> Self {
>> +            MemoryType::Unmapped
>> +        }
>> +    }
> Tip: you can add `Default` to the `#[derive]` marker of `MemoryType` and
> mark the variant you want as default with `#[default]` instead of
> providing a full impl block:
>
>      #[derive(Debug, Default, Clone, Copy, PartialEq)]
>      enum MemoryType {
>          #[default]
>          Unmapped = 0,
>          Normal = 1,
>          Device = 2,
>          Reserved = 3,
>      }

I would alternatively recommend to provide a `MemoryType::new` impl with 
a `const` definition:

```rust
impl MemoryType {
     pub const fn new() -> Self {

         Self::Unmapped

     }
}

impl Default for MemoryType {
     fn default() -> Self {
         Self::new()
     }
}
```

This pattern allows using `MemoryType::new()` in `const` contexts, while 
also providing the `Default` impl using the same default. It's somewhat 
of a workaround until we get `const` traits.

>> +
>> +    impl TryFrom<u8> for MemoryType {
>> +        type Error = u8;
>> +        fn try_from(value: u8) -> Result<Self, Self::Error> {
>> +            match value {
>> +                0 => Ok(MemoryType::Unmapped),
>> +                1 => Ok(MemoryType::Normal),
>> +                2 => Ok(MemoryType::Device),
>> +                3 => Ok(MemoryType::Reserved),
>> +                _ => Err(value),
>> +            }
>> +        }
>> +    }
>> +
>> +    impl From<MemoryType> for u64 {
>> +        fn from(mt: MemoryType) -> u64 {
>> +            mt as u64
>> +        }
>> +    }
>> +
>> +    #[derive(Debug, Clone, Copy, PartialEq)]
>> +    enum Priority {
>> +        Low = 0,
>> +        Medium = 1,
>> +        High = 2,
>> +        Critical = 3,
>> +    }
>> +
>> +    impl Default for Priority {
>> +        fn default() -> Self {
>> +            Priority::Low
>> +        }
>> +    }
>> +
>> +    impl From<u8> for Priority {
>> +        fn from(value: u8) -> Self {
>> +            match value & 0x3 {
>> +                0 => Priority::Low,
>> +                1 => Priority::Medium,
>> +                2 => Priority::High,
>> +                _ => Priority::Critical,
>> +            }
>> +        }
>> +    }
>> +
>> +    impl From<Priority> for u16 {
>> +        fn from(p: Priority) -> u16 {
>> +            p as u16
>> +        }
>> +    }
>> +
>> +    bitfield! {
>> +        struct TestPageTableEntry(u64) {
>> +            0:0       present     as bool;
>> +            1:1       writable    as bool;
>> +            11:9      available   as u8;
>> +            13:12     mem_type    as u8 ?=> MemoryType;
>> +            17:14     extended_type as u8 ?=> MemoryType;  // For testing failures
>> +            51:12     pfn         as u64;
>> +            51:12     pfn_overlap as u64;
>> +            61:52     available2  as u16;
>> +        }
>> +    }
>> +
>> +    bitfield! {
>> +        struct TestControlRegister(u16) {
>> +            0:0       enable      as bool;
>> +            3:1       mode        as u8;
>> +            5:4       priority    as u8 => Priority;
>> +            7:4       priority_nibble as u8;
>> +            15:8      channel     as u8;
>> +        }
>> +    }
>> +
>> +    bitfield! {
>> +        struct TestStatusRegister(u8) {
>> +            0:0       ready       as bool;
>> +            1:1       error       as bool;
>> +            3:2       state       as u8;
>> +            7:4       reserved    as u8;
>> +            7:0       full_byte   as u8;  // For entire register
>> +        }
>> +    }
>> +
>> +    #[test]
>> +    fn test_single_bits() {
>> +        let mut pte = TestPageTableEntry::default();
>> +
>> +        assert!(!pte.present());
>> +        assert!(!pte.writable());
>> +
>> +        pte = pte.set_present(true);
>> +        assert!(pte.present());
>> +
>> +        pte = pte.set_writable(true);
>> +        assert!(pte.writable());
>> +
>> +        pte = pte.set_writable(false);
>> +        assert!(!pte.writable());
>> +
>> +        assert_eq!(pte.available(), 0);
>> +        pte = pte.set_available(0x5);
>> +        assert_eq!(pte.available(), 0x5);
> I'd suggest testing the actual raw value of the register on top of
> invoking the getter. That way you also test that:
>
> - The right field is actually written (i.e. if the offset is off by one,
>    the getter will return the expected result even though the bitfield
>    has the wrong value),
> - No other field has been affected.
>
> So something like:
>
>      pte = pte.set_present(true);
>      assert!(pte.present());
>      assert(pte.into(), 0x1u64);
>
>      pte = pte.set_writable(true);
>      assert!(pte.writable());
>      assert(pte.into(), 0x3u64);
>
> It might look a bit gross, but it is ok since these are not doctests
> that users are going to take as a reference, so we case improve test
> coverage at the detriment of readability.
>

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

* Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
  2025-10-02  2:16     ` Elle Rhumsaa
@ 2025-10-02  2:51       ` Alexandre Courbot
  2025-10-02  3:35         ` Elle Rhumsaa
  0 siblings, 1 reply; 27+ messages in thread
From: Alexandre Courbot @ 2025-10-02  2:51 UTC (permalink / raw)
  To: Elle Rhumsaa, Alexandre Courbot, Joel Fernandes, linux-kernel,
	rust-for-linux, dri-devel, dakr
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Yury Norov, Daniel Almeida, Andrea Righi, nouveau

On Thu Oct 2, 2025 at 11:16 AM JST, Elle Rhumsaa wrote:
> On 10/2/25 1:41 AM, Alexandre Courbot wrote:
>
>> On Tue Sep 30, 2025 at 11:45 PM JST, Joel Fernandes wrote:
>>> Add KUNIT tests to make sure the macro is working correctly.
>>>
>>> Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
>>> ---
>>>   rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++
>>>   1 file changed, 321 insertions(+)
>>>
>>> diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
>>> index fed19918c3b9..9a20bcd2eb60 100644
>>> --- a/rust/kernel/bitfield.rs
>>> +++ b/rust/kernel/bitfield.rs
>>> @@ -402,3 +402,324 @@ fn default() -> Self {
>>>           }
>>>       };
>>>   }
>>> +
>>> +#[::kernel::macros::kunit_tests(kernel_bitfield)]
>>> +mod tests {
>>> +    use core::convert::TryFrom;
>>> +
>>> +    // Enum types for testing => and ?=> conversions
>>> +    #[derive(Debug, Clone, Copy, PartialEq)]
>>> +    enum MemoryType {
>>> +        Unmapped = 0,
>>> +        Normal = 1,
>>> +        Device = 2,
>>> +        Reserved = 3,
>>> +    }
>>> +
>>> +    impl Default for MemoryType {
>>> +        fn default() -> Self {
>>> +            MemoryType::Unmapped
>>> +        }
>>> +    }
>> Tip: you can add `Default` to the `#[derive]` marker of `MemoryType` and
>> mark the variant you want as default with `#[default]` instead of
>> providing a full impl block:
>>
>>      #[derive(Debug, Default, Clone, Copy, PartialEq)]
>>      enum MemoryType {
>>          #[default]
>>          Unmapped = 0,
>>          Normal = 1,
>>          Device = 2,
>>          Reserved = 3,
>>      }
>
> I would alternatively recommend to provide a `MemoryType::new` impl with 
> a `const` definition:
>
> ```rust
> impl MemoryType {
>      pub const fn new() -> Self {
>
>          Self::Unmapped
>
>      }
> }
>
> impl Default for MemoryType {
>      fn default() -> Self {
>          Self::new()
>      }
> }
> ```
>
> This pattern allows using `MemoryType::new()` in `const` contexts, while 
> also providing the `Default` impl using the same default. It's somewhat 
> of a workaround until we get `const` traits.

That's an elegant pattern generally speaking, but I don't think we would
benefit from using it in these unit tests.

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

* Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
  2025-10-02  2:51       ` Alexandre Courbot
@ 2025-10-02  3:35         ` Elle Rhumsaa
  0 siblings, 0 replies; 27+ messages in thread
From: Elle Rhumsaa @ 2025-10-02  3:35 UTC (permalink / raw)
  To: Alexandre Courbot, Joel Fernandes, linux-kernel, rust-for-linux,
	dri-devel, dakr
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Yury Norov, Daniel Almeida, Andrea Righi, nouveau


On 10/2/25 2:51 AM, Alexandre Courbot wrote:
> On Thu Oct 2, 2025 at 11:16 AM JST, Elle Rhumsaa wrote:
>> On 10/2/25 1:41 AM, Alexandre Courbot wrote:
>>
>>> On Tue Sep 30, 2025 at 11:45 PM JST, Joel Fernandes wrote:
>>>> Add KUNIT tests to make sure the macro is working correctly.
>>>>
>>>> Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
>>>> ---
>>>>    rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++
>>>>    1 file changed, 321 insertions(+)
>>>>
>>>> diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
>>>> index fed19918c3b9..9a20bcd2eb60 100644
>>>> --- a/rust/kernel/bitfield.rs
>>>> +++ b/rust/kernel/bitfield.rs
>>>> @@ -402,3 +402,324 @@ fn default() -> Self {
>>>>            }
>>>>        };
>>>>    }
>>>> +
>>>> +#[::kernel::macros::kunit_tests(kernel_bitfield)]
>>>> +mod tests {
>>>> +    use core::convert::TryFrom;
>>>> +
>>>> +    // Enum types for testing => and ?=> conversions
>>>> +    #[derive(Debug, Clone, Copy, PartialEq)]
>>>> +    enum MemoryType {
>>>> +        Unmapped = 0,
>>>> +        Normal = 1,
>>>> +        Device = 2,
>>>> +        Reserved = 3,
>>>> +    }
>>>> +
>>>> +    impl Default for MemoryType {
>>>> +        fn default() -> Self {
>>>> +            MemoryType::Unmapped
>>>> +        }
>>>> +    }
>>> Tip: you can add `Default` to the `#[derive]` marker of `MemoryType` and
>>> mark the variant you want as default with `#[default]` instead of
>>> providing a full impl block:
>>>
>>>       #[derive(Debug, Default, Clone, Copy, PartialEq)]
>>>       enum MemoryType {
>>>           #[default]
>>>           Unmapped = 0,
>>>           Normal = 1,
>>>           Device = 2,
>>>           Reserved = 3,
>>>       }
>> I would alternatively recommend to provide a `MemoryType::new` impl with
>> a `const` definition:
>>
>> ```rust
>> impl MemoryType {
>>       pub const fn new() -> Self {
>>
>>           Self::Unmapped
>>
>>       }
>> }
>>
>> impl Default for MemoryType {
>>       fn default() -> Self {
>>           Self::new()
>>       }
>> }
>> ```
>>
>> This pattern allows using `MemoryType::new()` in `const` contexts, while
>> also providing the `Default` impl using the same default. It's somewhat
>> of a workaround until we get `const` traits.
> That's an elegant pattern generally speaking, but I don't think we would
> benefit from using it in these unit tests.

*facepalm* right, I lost the context that these data structures were 
KUNIT-specific. Please disregard.


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

* Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
  2025-10-02  1:41   ` Alexandre Courbot
  2025-10-02  2:16     ` Elle Rhumsaa
@ 2025-10-03 15:23     ` Joel Fernandes
  2025-10-04  0:38       ` Alexandre Courbot
  1 sibling, 1 reply; 27+ messages in thread
From: Joel Fernandes @ 2025-10-03 15:23 UTC (permalink / raw)
  To: Alexandre Courbot, linux-kernel, rust-for-linux, dri-devel, dakr
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Yury Norov, Daniel Almeida, Andrea Righi, nouveau



On 10/1/2025 9:41 PM, Alexandre Courbot wrote:
> On Tue Sep 30, 2025 at 11:45 PM JST, Joel Fernandes wrote:
>> Add KUNIT tests to make sure the macro is working correctly.
>>
>> Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
>> ---
>>  rust/kernel/bitfield.rs | 321 ++++++++++++++++++++++++++++++++++++++++
>>  1 file changed, 321 insertions(+)
>>
>> diff --git a/rust/kernel/bitfield.rs b/rust/kernel/bitfield.rs
>> index fed19918c3b9..9a20bcd2eb60 100644
>> --- a/rust/kernel/bitfield.rs
>> +++ b/rust/kernel/bitfield.rs
>> @@ -402,3 +402,324 @@ fn default() -> Self {
>>          }
>>      };
>>  }
>> +
>> +#[::kernel::macros::kunit_tests(kernel_bitfield)]
>> +mod tests {
>> +    use core::convert::TryFrom;
>> +
>> +    // Enum types for testing => and ?=> conversions
>> +    #[derive(Debug, Clone, Copy, PartialEq)]
>> +    enum MemoryType {
>> +        Unmapped = 0,
>> +        Normal = 1,
>> +        Device = 2,
>> +        Reserved = 3,
>> +    }
>> +
>> +    impl Default for MemoryType {
>> +        fn default() -> Self {
>> +            MemoryType::Unmapped
>> +        }
>> +    }
> 
> Tip: you can add `Default` to the `#[derive]` marker of `MemoryType` and
> mark the variant you want as default with `#[default]` instead of
> providing a full impl block:
> 
>     #[derive(Debug, Default, Clone, Copy, PartialEq)]
>     enum MemoryType {
>         #[default]
>         Unmapped = 0,
>         Normal = 1,
>         Device = 2,
>         Reserved = 3,
>     }
> 

Good point, changed to this.

>> +
>> +    impl TryFrom<u8> for MemoryType {
>> +        type Error = u8;
>> +        fn try_from(value: u8) -> Result<Self, Self::Error> {
>> +            match value {
>> +                0 => Ok(MemoryType::Unmapped),
>> +                1 => Ok(MemoryType::Normal),
>> +                2 => Ok(MemoryType::Device),
>> +                3 => Ok(MemoryType::Reserved),
>> +                _ => Err(value),
>> +            }
>> +        }
>> +    }
>> +
>> +    impl From<MemoryType> for u64 {
>> +        fn from(mt: MemoryType) -> u64 {
>> +            mt as u64
>> +        }
>> +    }
>> +
>> +    #[derive(Debug, Clone, Copy, PartialEq)]
>> +    enum Priority {
>> +        Low = 0,
>> +        Medium = 1,
>> +        High = 2,
>> +        Critical = 3,
>> +    }
>> +
>> +    impl Default for Priority {
>> +        fn default() -> Self {
>> +            Priority::Low
>> +        }
>> +    }
>> +
>> +    impl From<u8> for Priority {
>> +        fn from(value: u8) -> Self {
>> +            match value & 0x3 {
>> +                0 => Priority::Low,
>> +                1 => Priority::Medium,
>> +                2 => Priority::High,
>> +                _ => Priority::Critical,
>> +            }
>> +        }
>> +    }
>> +
>> +    impl From<Priority> for u16 {
>> +        fn from(p: Priority) -> u16 {
>> +            p as u16
>> +        }
>> +    }
>> +
>> +    bitfield! {
>> +        struct TestPageTableEntry(u64) {
>> +            0:0       present     as bool;
>> +            1:1       writable    as bool;
>> +            11:9      available   as u8;
>> +            13:12     mem_type    as u8 ?=> MemoryType;
>> +            17:14     extended_type as u8 ?=> MemoryType;  // For testing failures
>> +            51:12     pfn         as u64;
>> +            51:12     pfn_overlap as u64;
>> +            61:52     available2  as u16;
>> +        }
>> +    }
>> +
>> +    bitfield! {
>> +        struct TestControlRegister(u16) {
>> +            0:0       enable      as bool;
>> +            3:1       mode        as u8;
>> +            5:4       priority    as u8 => Priority;
>> +            7:4       priority_nibble as u8;
>> +            15:8      channel     as u8;
>> +        }
>> +    }
>> +
>> +    bitfield! {
>> +        struct TestStatusRegister(u8) {
>> +            0:0       ready       as bool;
>> +            1:1       error       as bool;
>> +            3:2       state       as u8;
>> +            7:4       reserved    as u8;
>> +            7:0       full_byte   as u8;  // For entire register
>> +        }
>> +    }
>> +
>> +    #[test]
>> +    fn test_single_bits() {
>> +        let mut pte = TestPageTableEntry::default();
>> +
>> +        assert!(!pte.present());
>> +        assert!(!pte.writable());
>> +
>> +        pte = pte.set_present(true);
>> +        assert!(pte.present());
>> +
>> +        pte = pte.set_writable(true);
>> +        assert!(pte.writable());
>> +
>> +        pte = pte.set_writable(false);
>> +        assert!(!pte.writable());
>> +
>> +        assert_eq!(pte.available(), 0);
>> +        pte = pte.set_available(0x5);
>> +        assert_eq!(pte.available(), 0x5);
> 
> I'd suggest testing the actual raw value of the register on top of
> invoking the getter. That way you also test that:

Sure, I am actually doing a raw check in a few other tests, but I could do so in
this one as well.

> 
> - The right field is actually written (i.e. if the offset is off by one,
>   the getter will return the expected result even though the bitfield
>   has the wrong value),
> - No other field has been affected.
> 
> So something like:
> 
>     pte = pte.set_present(true);
>     assert!(pte.present());
>     assert(pte.into(), 0x1u64);
> 
>     pte = pte.set_writable(true);
>     assert!(pte.writable());
>     assert(pte.into(), 0x3u64);
> 
> It might look a bit gross, but it is ok since these are not doctests
> that users are going to take as a reference, so we case improve test
> coverage at the detriment of readability.
> 

Ack. I will add these.

Thanks for the review! (I am assuming with these changes you're Ok with me
carrying your Reviewed-by tag on this patch as well, but please let me know if
there is a concern.)

 - Joel



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

* Re: [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/
  2025-10-02  1:26   ` Alexandre Courbot
@ 2025-10-03 15:26     ` Joel Fernandes
  0 siblings, 0 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-10-03 15:26 UTC (permalink / raw)
  To: Alexandre Courbot, linux-kernel, rust-for-linux, dri-devel, dakr
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Yury Norov, Daniel Almeida, Andrea Righi, nouveau

On 10/1/2025 9:26 PM, Alexandre Courbot wrote:
> On Thu Oct 2, 2025 at 10:24 AM JST, Alexandre Courbot wrote:
>> On Tue Sep 30, 2025 at 11:45 PM JST, Joel Fernandes wrote:
>>> Hello!
>>>
>>> These patches extract and enhance the bitfield support in the register macro in
>>> nova to define Rust structures with bitfields. It then moves out the bitfield
>>> support into the kenrel crate and further enhances it. This is extremely useful
>>> as it allows clean Rust structure definitions without requiring explicit masks
>>> and shifts.
>>
>> The extraction and move in themselves (patches 1-4 and maybe the KUNIT
>> one) look good to me. For the remainder, it will depend on whether the
>> BoundedInt idea sticks or not as it changes the design in a way that
>> makes most of these patches unneeded. In any case I think this can be
>> worked on after the split and extraction.

Sure.

>>
>> Patch 5 should probably be dropped as it has the potential to clear
>> register fields that are useful to the hardware but have no entry in the
>> `register!` definition, making read-update-write updates of registers
>> unpredictable.
> 
> Ah, I forgot: please base the next revision on top of drm-rust-next as
> we are likely to apply it there.

Done, I rebased on top of drm-rust-next, commit: 299eb32863e5 ("gpu: nova-core:
Add base files for r570.144 firmware bindings")

I will send the v6 out shortly with just the patches to be included.

Thanks.

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

* Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
  2025-10-03 15:23     ` Joel Fernandes
@ 2025-10-04  0:38       ` Alexandre Courbot
  2025-10-04 16:14         ` Joel Fernandes
  0 siblings, 1 reply; 27+ messages in thread
From: Alexandre Courbot @ 2025-10-04  0:38 UTC (permalink / raw)
  To: Joel Fernandes, Alexandre Courbot, linux-kernel, rust-for-linux,
	dri-devel, dakr
  Cc: Alistair Popple, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, David Airlie, Simona Vetter, Maarten Lankhorst,
	Maxime Ripard, Thomas Zimmermann, John Hubbard, Timur Tabi, joel,
	Elle Rhumsaa, Yury Norov, Daniel Almeida, Andrea Righi, nouveau

On Sat Oct 4, 2025 at 12:23 AM JST, Joel Fernandes wrote:
>> - The right field is actually written (i.e. if the offset is off by one,
>>   the getter will return the expected result even though the bitfield
>>   has the wrong value),
>> - No other field has been affected.
>> 
>> So something like:
>> 
>>     pte = pte.set_present(true);
>>     assert!(pte.present());
>>     assert(pte.into(), 0x1u64);
>> 
>>     pte = pte.set_writable(true);
>>     assert!(pte.writable());
>>     assert(pte.into(), 0x3u64);
>> 
>> It might look a bit gross, but it is ok since these are not doctests
>> that users are going to take as a reference, so we case improve test
>> coverage at the detriment of readability.
>> 
>
> Ack. I will add these.
>
> Thanks for the review! (I am assuming with these changes you're Ok with me
> carrying your Reviewed-by tag on this patch as well, but please let me know if
> there is a concern.)

Please do not add tags that haven't been explicitly given. If we start
assuming one another's stance about patches, the trust we can have in
these tags is significantly reduced.

Doing so also doesn't achieve anything in terms of efficiency; if I am
ok with v3 I can give my Reviewed-by on it, and the tag can be picked up
along with the patch when it is applied.

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

* Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
  2025-10-04  0:38       ` Alexandre Courbot
@ 2025-10-04 16:14         ` Joel Fernandes
  2025-10-06 16:40           ` Miguel Ojeda
  0 siblings, 1 reply; 27+ messages in thread
From: Joel Fernandes @ 2025-10-04 16:14 UTC (permalink / raw)
  To: Alexandre Courbot
  Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org,
	dri-devel@lists.freedesktop.org, dakr@kernel.org, Alistair Popple,
	Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh@protonmail.com, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, David Airlie, Simona Vetter,
	Maarten Lankhorst, Maxime Ripard, Thomas Zimmermann, John Hubbard,
	Timur Tabi, joel@joelfernandes.org, Elle Rhumsaa, Yury Norov,
	Daniel Almeida, Andrea Righi, nouveau@lists.freedesktop.org,
	Alexandre Courbot



> On Oct 3, 2025, at 8:38 PM, Alexandre Courbot <acourbot@nvidia.com> wrote:
> 
> On Sat Oct 4, 2025 at 12:23 AM JST, Joel Fernandes wrote:
>>> - The right field is actually written (i.e. if the offset is off by one,
>>>  the getter will return the expected result even though the bitfield
>>>  has the wrong value),
>>> - No other field has been affected.
>>> 
>>> So something like:
>>> 
>>>    pte = pte.set_present(true);
>>>    assert!(pte.present());
>>>    assert(pte.into(), 0x1u64);
>>> 
>>>    pte = pte.set_writable(true);
>>>    assert!(pte.writable());
>>>    assert(pte.into(), 0x3u64);
>>> 
>>> It might look a bit gross, but it is ok since these are not doctests
>>> that users are going to take as a reference, so we case improve test
>>> coverage at the detriment of readability.
>>> 
>> 
>> Ack. I will add these.
>> 
>> Thanks for the review! (I am assuming with these changes you're Ok with me
>> carrying your Reviewed-by tag on this patch as well, but please let me know if
>> there is a concern.)
> 
> Please do not add tags that haven't been explicitly given. If we start
> assuming one another's stance about patches, the trust we can have in
> these tags is significantly reduced.

Oh, I thought you told me you reviewed the patch privately, but consider the tag dropped.

> 
> Doing so also doesn't achieve anything in terms of efficiency; if I am
> ok with v3 I can give my Reviewed-by on it, and the tag can be picked up
> along with the patch when it is applied.

Well, it can be efficient. It really depends. I have been contributing upstream for about 15 years if you see the git log, often when someone chats privately with me like you did and they told me they are ok with a patch, I save them the trouble and add their review tag especially after they already added their tag to all my other patches. Surprisingly though this is probably the first time anyone has been pissed off about it.  Anyway I will not add your tag henceforth unless you publicly reply (or you let me know otherwise by chat).

Anyway thank you for the review of this patch,

Joel

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

* Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
  2025-10-04 16:14         ` Joel Fernandes
@ 2025-10-06 16:40           ` Miguel Ojeda
  2025-10-06 19:50             ` Joel Fernandes
  0 siblings, 1 reply; 27+ messages in thread
From: Miguel Ojeda @ 2025-10-06 16:40 UTC (permalink / raw)
  To: Joel Fernandes
  Cc: Alexandre Courbot, linux-kernel@vger.kernel.org,
	rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org,
	dakr@kernel.org, Alistair Popple, Miguel Ojeda, Alex Gaynor,
	Boqun Feng, Gary Guo, bjorn3_gh@protonmail.com, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, David Airlie,
	Simona Vetter, Maarten Lankhorst, Maxime Ripard,
	Thomas Zimmermann, John Hubbard, Timur Tabi,
	joel@joelfernandes.org, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau@lists.freedesktop.org

On Sat, Oct 4, 2025 at 6:14 PM Joel Fernandes <joelagnelf@nvidia.com> wrote:
>
> Well, it can be efficient. It really depends. I have been contributing upstream for about 15 years if you see the git log, often when someone chats privately with me like you did and they told me they are ok with a patch, I save them the trouble and add their review tag especially after they already added their tag to all my other patches. Surprisingly though this is probably the first time anyone has been pissed off about it.  Anyway I will not add your tag henceforth unless you publicly reply (or you let me know otherwise by chat).

If they just say they are OK with a patch, that would just mean an
Acked-by, not a Reviewed-by.

In any case, the documentation states those tags cannot be added
without permission -- if someone gives you a tag privately, it is best
that you tell them to please send it in the mailing list instead. That
way there is no confusion and others (including tooling, e.g.
patchwork and b4) can see it.

Thanks!

Cheers,
Miguel

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

* Re: [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield
  2025-10-06 16:40           ` Miguel Ojeda
@ 2025-10-06 19:50             ` Joel Fernandes
  0 siblings, 0 replies; 27+ messages in thread
From: Joel Fernandes @ 2025-10-06 19:50 UTC (permalink / raw)
  To: Miguel Ojeda
  Cc: Alexandre Courbot, linux-kernel@vger.kernel.org,
	rust-for-linux@vger.kernel.org, dri-devel@lists.freedesktop.org,
	dakr@kernel.org, Alistair Popple, Miguel Ojeda, Alex Gaynor,
	Boqun Feng, Gary Guo, bjorn3_gh@protonmail.com, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, David Airlie,
	Simona Vetter, Maarten Lankhorst, Maxime Ripard,
	Thomas Zimmermann, John Hubbard, Timur Tabi,
	joel@joelfernandes.org, Elle Rhumsaa, Yury Norov, Daniel Almeida,
	Andrea Righi, nouveau@lists.freedesktop.org



On 10/6/2025 12:40 PM, Miguel Ojeda wrote:
> On Sat, Oct 4, 2025 at 6:14 PM Joel Fernandes <joelagnelf@nvidia.com> wrote:
>>
>> Well, it can be efficient. It really depends. I have been contributing upstream for about 15 years if you see the git log, often when someone chats privately with me like you did and they told me they are ok with a patch, I save them the trouble and add their review tag especially after they already added their tag to all my other patches. Surprisingly though this is probably the first time anyone has been pissed off about it.  Anyway I will not add your tag henceforth unless you publicly reply (or you let me know otherwise by chat).
> 
> If they just say they are OK with a patch, that would just mean an
> Acked-by, not a Reviewed-by.
>> In any case, the documentation states those tags cannot be added
> without permission -- if someone gives you a tag privately, it is best
> that you tell them to please send it in the mailing list instead. That
> way there is no confusion and others (including tooling, e.g.
> patchwork and b4) can see it.
Sure, certainly it goes against docs/guidelines to add a tag *without
permission*. I don't think anyone disputed that? I don't think I was advocating
adding RB tags randomly without consent at all - please don't get me wrong. :-)

And no doubts that publicly replying with RB tags is the best way.

cheers,

 - Joel


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

end of thread, other threads:[~2025-10-06 19:50 UTC | newest]

Thread overview: 27+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-09-30 14:45 [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Joel Fernandes
2025-09-30 14:45 ` [PATCH v5 1/9] nova-core: bitfield: Move bitfield-specific code from register! into new macro Joel Fernandes
2025-09-30 14:45 ` [PATCH v5 2/9] nova-core: bitfield: Add support for different storage widths Joel Fernandes
2025-09-30 17:18   ` Joel Fernandes
2025-10-02  1:17   ` Alexandre Courbot
2025-09-30 14:45 ` [PATCH v5 3/9] nova-core: bitfield: Add support for custom visiblity Joel Fernandes
2025-09-30 14:45 ` [PATCH v5 4/9] rust: Move register and bitfield macros out of Nova Joel Fernandes
2025-09-30 14:45 ` [PATCH v5 5/9] rust: bitfield: Add a new() constructor and raw() accessor Joel Fernandes
2025-09-30 14:45 ` [PATCH v5 6/9] rust: bitfield: Add KUNIT tests for bitfield Joel Fernandes
2025-10-02  1:41   ` Alexandre Courbot
2025-10-02  2:16     ` Elle Rhumsaa
2025-10-02  2:51       ` Alexandre Courbot
2025-10-02  3:35         ` Elle Rhumsaa
2025-10-03 15:23     ` Joel Fernandes
2025-10-04  0:38       ` Alexandre Courbot
2025-10-04 16:14         ` Joel Fernandes
2025-10-06 16:40           ` Miguel Ojeda
2025-10-06 19:50             ` Joel Fernandes
2025-09-30 14:45 ` [PATCH v5 7/9] rust: bitfield: Use 'as' operator for setter type conversion Joel Fernandes
2025-09-30 14:45 ` [PATCH v5 8/9] rust: bitfield: Add hardening for out of bounds access Joel Fernandes
2025-09-30 18:03   ` Yury Norov
2025-09-30 22:06     ` Joel Fernandes
2025-09-30 14:45 ` [PATCH v5 9/9] rust: bitfield: Add hardening for undefined bits Joel Fernandes
2025-09-30 15:08 ` [PATCH v5 0/9] Introduce bitfield and move register macro to rust/kernel/ Danilo Krummrich
2025-10-02  1:24 ` Alexandre Courbot
2025-10-02  1:26   ` Alexandre Courbot
2025-10-03 15:26     ` Joel Fernandes

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).