Skip to contentSkip to conversation

rust: add BitInt type and use in Nova's bitfield macro

PATCH Superseded Alexandre Courbot 2 participants 6 messages Nov 2, 2025 – Nov 3, 2025

Subsystems (5)

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

v2 cover rust: add BitInt type and use in Nova's bitfield macro

Second non-RFC, with quite a few improvements - notably, the From implementations from and to primitive types have been simplified, and I guess that's the best I can do without the generic_const_exprs feature. Another improvement is that the type invariants are now enforced from a single place.

This series provides BitInt, a wrapper type for primitive integers that guarantees that only a given number of bits are used to represent values. This is particularly useful when working with bitfields, as the guarantee that a given value fits within the number of assigned bits can be enforced by the type system, saving cumbersome runtime checks, or (worse) stripping data when bits are silently dropped.

Don't worry too much about the size; a lot of it is rustdoc. :)

For a basic usage, please see the rustdoc of the BitInt type on the first patch.

The first use of this will be to represent bitfields in Nova register types to guarantee that no data is ever stripped when manipulating them. This should eventually allow the bitfield and register macros to move out of Nova and into the kernel crate.

The second patch is here to illustrate the use of this module; it is not intended to be merged this cycle as it would likely result in big merge conflicts with the drm tree.

This series applies on top of drm-rust-next for the needs of the second patch. The first patch should apply cleanly on rust-next. A branch with this series and its dependencies is available here:

https://github.com/Gnurou/linux/tree/b4/bounded_ints

---
Changes in v2:
- Move type invariants of BitInt to a centralizing private
constructor.
- Simplify From implementations to and from primitive types.
- Remove ability to convert between unsigned and signed types as it was buggy, and its utility doubtful.
- Use macro to implement Integer and avoid repeating code.
- Fix a few typos.
- More doctests, and split them into different paragraphs in the
BitInt main doccomment.
- Fix build with Rust 1.78.
- Finish implementing relevant core::ops traits.
- Link to v1: https://lore.kernel.org/r/[email protected]

Changes in v1:
- Rebase on top of drm-rust-next.
- Rename BoundedInt to BitInt (thanks Yury!).
- Add lots of documentation.
- Use shifts to validate bounds, as it works with both unsigned and
signed types contrary to the mask method.
- Support signed types (albeit with some bugs).
- Use new for the const static constructor and make it the preferred
way to build values (thanks Alice and Joel!).
- Rename LargerThanX into AtLeastX (thanks Joel!).
- Support basic arithmetic operations (+, -, etc.) against the backing
type.
- Add Deref implementation as alternative to the get method.
- Write correct Default implementation for bitfields.
- Make the new bitfield accessors inline(always).
- Update bitfield documentation to the new usage.
- Link to RFC v2: https://lore.kernel.org/r/[email protected]

Changes in RFC v2:
- Thorough implementation of BoundedInt.
- nova-core fully adapted to use BoundedInt.
- Link to RFC v1: https://lore.kernel.org/r/[email protected]

---
Alexandre Courbot (2):
rust: add BitInt integer wrapping type
[FOR REFERENCE] gpu: nova-core: use BitInt for bitfields

 drivers/gpu/nova-core/bitfield.rs         |  366 ++++++-----
 drivers/gpu/nova-core/falcon.rs           |  134 ++--
 drivers/gpu/nova-core/falcon/hal/ga102.rs |    5 +-
 drivers/gpu/nova-core/fb/hal/ga100.rs     |    3 +-
 drivers/gpu/nova-core/gpu.rs              |    9 +-
 drivers/gpu/nova-core/regs.rs             |  139 ++--
 rust/kernel/lib.rs                        |    1 +
 rust/kernel/num.rs                        |   50 ++
 rust/kernel/num/bitint.rs                 | 1001 +++++++++++++++++++++++++++++
 9 files changed, 1405 insertions(+), 303 deletions(-)

---
base-commit: 9a3c2f8a4f84960a48c056d0da88de3d09e6d622
change-id: 20251001-bounded_ints-1d0457d9ae26

Best regards,

Signature · 1 line
Alexandre Courbot <[email protected]>
author maintainer
#1 lore raw

PATCH v2 1/2 rust: add BitInt integer wrapping type

Add the BitInt type, which is an integer on which the number of bits allowed to be used is restricted, capping its maximal value below that of primitive type is wraps.

This is useful to e.g. enforce guarantees when working with bit fields.

Alongside this type, provide many From and TryFrom implementations are to reduce friction when using with regular integer types. Proxy implementations of common integer traits are also provided.

---
 rust/kernel/lib.rs        |    1 +
 rust/kernel/num.rs        |   50 +++
 rust/kernel/num/bitint.rs | 1001 +++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 1052 insertions(+)
rust/kernel/lib.rs +1 -0
index 3dd7bebe7888..235d0d8b1eff 100644
@@ -109,6 +109,7 @@
 pub mod mm;
 #[cfg(CONFIG_NET)]
 pub mod net;
+pub mod num;
 pub mod of;
 #[cfg(CONFIG_PM_OPP)]
 pub mod opp;
rust/kernel/num.rs new file +50 -0

50 lines not on this page · raw message

rust/kernel/num/bitint.rs new file +1001 -0

1,001 lines not on this page · raw message

Signature · 1 line
2.51.2
maintainer Reviewed-by on v2 1/2
#2 lore raw

Re: [PATCH v2 1/2] rust: add BitInt integer wrapping type

Quoted 11 lines · Alexandre Courbot

Add the BitInt type, which is an integer on which the number of bits allowed to be used is restricted, capping its maximal value below that of primitive type is wraps.

This is useful to e.g. enforce guarantees when working with bit fields.

Alongside this type, provide many From and TryFrom implementations are to reduce friction when using with regular integer types. Proxy implementations of common integer traits are also provided.

rust/kernel/num/bitint.rs line 266

Quoted 4 lines
rust/kernel/num/bitint.rs new file +4 -0
+                // Statically assert that `VALUE` fits within the set number of bits.
+                const {
+                    build_assert!(fits_within!(VALUE, $type, NUM_BITS));
+                }

Since it's in a const block, this can just be an assert!.

Alice

maintainer
#3 lore raw

Re: [PATCH v2 1/2] rust: add BitInt integer wrapping type

Quoted 7 lines · Alice Ryhl
Quoted 6 lines · Alexandre Courbot

Add the BitInt type, which is an integer on which the number of bits allowed to be used is restricted, capping its maximal value below that of primitive type is wraps.

This is useful to e.g. enforce guarantees when working with bit fields.

Quoted 7 lines
Quoted 5 lines

Alongside this type, provide many From and TryFrom implementations are to reduce friction when using with regular integer types. Proxy implementations of common integer traits are also provided.

Actually, I saw Yury's comments on v1 and I have some additional comments as well. See my reply there.

Alice

author maintainer
#4 lore raw

Re: [PATCH v2 1/2] rust: add BitInt integer wrapping type

Quoted 12 lines · Alice Ryhl
Quoted 11 lines · Alice Ryhl
Quoted 10 lines · Alexandre Courbot

Add the BitInt type, which is an integer on which the number of bits allowed to be used is restricted, capping its maximal value below that of primitive type is wraps.

This is useful to e.g. enforce guarantees when working with bit fields.

Alongside this type, provide many From and TryFrom implementations are to reduce friction when using with regular integer types. Proxy implementations of common integer traits are also provided.

Quoted 6 lines
Quoted 3 lines
Quoted 1 line

Actually, I saw Yury's comments on v1 and I have some additional comments as well. See my reply there.

Gotcha - ignoring your Reviewed-by tag for now.

author maintainer
#5 lore raw

PATCH v2 2/2 gpu: nova-core: use BitInt for bitfields

In reply to Alexandre Courbot

Use BitInt with the bitfield!() and register!() macros and adapt the nova-core code accordingly.

This makes it impossible to trim values when setting a register field, because either the value of the field has been inferred at compile-time to fit within the bounds of the field, or the user has been forced to check at runtime that it does indeed fit.

The use of BitInt actually simplifies register fields definitions, as they don't need an intermediate storage type (the "as ..." part of fields definitions). Instead, the internal storage type for each field is now the bounded integer of its width in bits, which can optionally be converted to another type that implements `From`` or `TryFrom`` for that bounded integer type.

This means that something like

register!(NV_PDISP_VGA_WORKSPACE_BASE @ 0x00625f04 {
3:3 status_valid as bool,
31:8 addr as u32,
});

Now becomes

  register!(NV_PDISP_VGA_WORKSPACE_BASE @ 0x00625f04 {
      3:3     status_valid => bool,
      31:8    addr,
  });

(here status_valid is infallibly converted to a bool for convenience and to remain compatible with the previous semantics)

The field setter/getters are also simplified. If a field has no target type, then its setter expects any type that implements Into to the field's bounded integer type. Due to the many From implementations for primitive types, this means that most calls can be left unchanged. If the caller passes a value that is potentially larger than the field's capacity, it must use the try_ variant of the setter, which returns an error if the value cannot be converted at runtime.

For fields that use => to convert to another type, both setter and getter are always infallible.

For fields that use ?=> to fallibly convert to another type, only the getter needs to be fallible as the setter always provide valid values by design.

Outside of the register macro, the biggest changes occur in falcon.rs, which defines many enums for fields - their conversion implementations need to be changed from the original primitive type of the field to the new corresponding bounded int type. Hopefully the TryFrom/Into derive macros [1] can take care of implementing these, but it will need to be adapted to support bounded integers... :/

But overall, I am rather happy at how simple it was to convert the whole of nova-core to this.

Note: This RFC uses nova-core's register!() macro for practical purposes, but the hope is to move this patch on top of the bitfield macro after it is split out [2].

[1]
https://lore.kernel.org/rust-for-linux/[email protected]/
[2]
https://lore.kernel.org/rust-for-linux/[email protected]/

---
 drivers/gpu/nova-core/bitfield.rs         | 366 ++++++++++++++++--------------
 drivers/gpu/nova-core/falcon.rs           | 134 ++++++-----
 drivers/gpu/nova-core/falcon/hal/ga102.rs |   5 +-
 drivers/gpu/nova-core/fb/hal/ga100.rs     |   3 +-
 drivers/gpu/nova-core/gpu.rs              |   9 +-
 drivers/gpu/nova-core/regs.rs             | 139 ++++++------
 6 files changed, 353 insertions(+), 303 deletions(-)
drivers/gpu/nova-core/bitfield.rs +201 -165
index 16e143658c51..c75d95ef1ae9 100644
@@ -19,21 +19,21 @@
 ///     Auto = 2,
 /// }
 ///
-/// impl TryFrom<u8> for Mode {
-///     type Error = u8;
-///     fn try_from(value: u8) -> Result<Self, Self::Error> {
-///         match value {
+/// impl TryFrom<BitInt<u32, 4>> for Mode {
+///     type Error = u32;
+///     fn try_from(value: BitInt<u32, 4>) -> Result<Self, Self::Error> {
+///         match *value {
 ///             0 => Ok(Mode::Low),
 ///             1 => Ok(Mode::High),
 ///             2 => Ok(Mode::Auto),
-///             _ => Err(value),
+///             value => Err(value),
 ///         }
 ///     }
 /// }
 ///
-/// impl From<Mode> for u8 {
-///     fn from(mode: Mode) -> u8 {
-///         mode as u8
+/// impl From<Mode> for BitInt<u32, 4> {
+///     fn from(mode: Mode) -> BitInt<u32, 4> {
+///         BitInt::from_expr(mode as u32)
 ///     }
 /// }
 ///
@@ -44,25 +44,29 @@
 ///     Active = 1,
 /// }
 ///
-/// impl From<bool> for State {
-///     fn from(value: bool) -> Self {
-///         if value { State::Active } else { State::Inactive }
+/// impl From<BitInt<u32, 1>> for State {
+///     fn from(value: BitInt<u32, 1>) -> Self {
+///         if bool::from(value) {
+///             State::Active
+///         } else {
+///             State::Inactive
+///         }
 ///     }
 /// }
 ///
-/// impl From<State> for bool {
-///     fn from(state: State) -> bool {
+/// impl From<State> for BitInt<u32, 1> {
+///     fn from(state: State) -> BitInt<u32, 1> {
 ///         match state {
-///             State::Inactive => false,
-///             State::Active => true,
+///             State::Inactive => false.into(),
+///             State::Active => true.into(),
 ///         }
 ///     }
 /// }
 ///
 /// bitfield! {
 ///     pub struct ControlReg(u32) {
-///         7:7 state as bool => State;
-///         3:0 mode as u8 ?=> Mode;
+///         7:7 state => State;
+///         3:0 mode ?=> Mode;
 ///     }
 /// }
 /// ```
@@ -112,12 +116,9 @@ fn from(val: $name) -> $storage {
         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.
+    // Dispatch fields depending on the syntax used.
     (@fields_dispatcher $vis:vis $name:ident $storage:ty {
-        $($hi:tt:$lo:tt $field:ident as $type:tt
+        $($hi:tt:$lo:tt $field:ident
             $(?=> $try_into_type:ty)?
             $(=> $into_type:ty)?
             $(, $comment:literal)?
@@ -125,173 +126,208 @@ fn from(val: $name) -> $storage {
         )*
     }
     ) => {
-        bitfield!(@field_accessors $vis $name $storage {
-            $(
-                $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 $vis:vis $name:ident $storage:ty {
-        $($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 $vis $name $storage, $hi:$lo $field as $type
-                $(?=> $try_into_type)?
-                $(=> $into_type)?
-                $(, $comment)?
-                ;
-            );
-            )*
+        $(
+        bitfield!(@private_field_accessors $name $storage : $hi:$lo $field);
+        bitfield!(@public_field_accessors $vis $name $storage : $hi:$lo $field
+            $(?=> $try_into_type)?
+            $(=> $into_type)?
+            $(, $comment)?
+        );
+        )*
         }
+
+        bitfield!(@debug $name { $($field;)* });
+        bitfield!(@default $name { $($field;)* });
+
     };
 
-    // 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 $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident as bool
-            => $into_type:ty $(, $comment:literal)?;
-    ) => {
-        bitfield!(
-            @leaf_accessor $vis $name $storage, $hi:$lo $field
-            { |f| <$into_type>::from(f != 0) }
-            bool $into_type => $into_type $(, $comment)?;
-        );
-    };
-
-    // Shortcut for fields defined as `bool` without the `=>` syntax.
-    (
-        @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)?;
-        );
-    };
-
-    // Catches the `?=>` syntax for non-boolean fields.
-    (
-        @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
-            { |f| <$try_into_type>::try_from(f as $type) } $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 $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
-            { |f| <$into_type>::from(f as $type) } $type $into_type => $into_type $(, $comment)?;);
-    };
-
-    // Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax.
-    (
-        @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)?;
-        );
-    };
-
-    // Generates the accessor methods for a single field.
-    (
-        @leaf_accessor $vis:vis $name:ident $storage:ty, $hi:tt:$lo:tt $field:ident
-            { $process:expr } $prim_type:tt $to_type:ty => $res_type:ty $(, $comment:literal)?;
+        @private_field_accessors $name:ident $storage:ty : $hi:tt:$lo:tt $field:ident
     ) => {
         ::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 _MASK>]: u32 = ((((1 << $hi) - 1) << 1) + 1) - ((1 << $lo) - 1);
         const [<$field:upper _SHIFT>]: u32 = $lo;
         );
 
+        ::kernel::macros::paste!(
+        fn [<$field _internal>](self) ->
+            ::kernel::num::BitInt<$storage, { $hi + 1 - $lo }> {
+            const MASK: u32 = $name::[<$field:upper _MASK>];
+            const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
+
+            let field = ((self.0 & MASK) >> SHIFT);
+
+            ::kernel::num::BitInt::<$storage, { $hi + 1 - $lo }>::from_expr(field)
+        }
+
+        fn [<set_ $field _internal>](
+            mut self,
+            value: ::kernel::num::BitInt<$storage, { $hi + 1 - $lo }>,
+        ) -> Self
+        {
+            const MASK: u32 = $name::[<$field:upper _MASK>];
+            const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
+
+            let value = (value.get() << SHIFT) & MASK;
+            self.0 = (self.0 & !MASK) | value;
+
+            self
+        }
+
+        fn [<try_set_ $field _internal>]<T>(
+            mut self,
+            value: T,
+        ) -> ::kernel::error::Result<Self>
+            where T: ::kernel::num::TryIntoBitInt<$storage, { $hi + 1 - $lo }>,
+        {
+            const MASK: u32 = $name::[<$field:upper _MASK>];
+            const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
+
+            let value = (
+                value.try_into_bitint().ok_or(::kernel::error::code::EOVERFLOW)?.get() << SHIFT
+            ) & MASK;
+
+            self.0 = (self.0 & !MASK) | value;
+
+            Ok(self)
+        }
+        );
+    };
+
+    // Generates the public accessors for fields infallibly (`=>`) converted to a type.
+    (
+        @public_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:$lo:tt $field:ident
+            => $into_type:ty $(, $comment:literal)?
+    ) => {
+        ::kernel::macros::paste!(
+
         $(
         #[doc="Returns the value of this field:"]
         #[doc=$comment]
         )?
         #[inline(always)]
-        $vis fn $field(self) -> $res_type {
-            ::kernel::macros::paste!(
-            const MASK: $storage = $name::[<$field:upper _MASK>];
-            const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
-            );
-            let field = ((self.0 & MASK) >> SHIFT);
-
-            $process(field)
+        $vis fn $field(self) -> $into_type
+        {
+            self.[<$field _internal>]().into()
         }
 
-        ::kernel::macros::paste!(
         $(
         #[doc="Sets the value of this field:"]
         #[doc=$comment]
         )?
         #[inline(always)]
-        $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($prim_type::from(value)) << SHIFT) & MASK;
-            self.0 = (self.0 & !MASK) | value;
-
-            self
+        $vis fn [<set_ $field>](self, value: $into_type) -> Self
+        {
+            self.[<set_ $field _internal>](value.into())
         }
+
+        /// Private method, for use in the [`Default`] implementation.
+        fn [<$field _default>]() -> $into_type {
+            Default::default()
+        }
+
+        );
+    };
+
+    // Generates the public accessors for fields fallibly (`?=>`) converted to a type.
+    (
+        @public_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:$lo:tt $field:ident
+            ?=> $try_into_type:ty $(, $comment:literal)?
+    ) => {
+        ::kernel::macros::paste!(
+
+        $(
+        #[doc="Returns the value of this field:"]
+        #[doc=$comment]
+        )?
+        #[inline(always)]
+        $vis fn $field(self) ->
+            Result<
+                $try_into_type,
+                <$try_into_type as ::core::convert::TryFrom<
+                    ::kernel::num::BitInt<$storage, { $hi + 1 - $lo }>
+                >>::Error
+            >
+        {
+            self.[<$field _internal>]().try_into()
+        }
+
+        $(
+        #[doc="Sets the value of this field:"]
+        #[doc=$comment]
+        )?
+        #[inline(always)]
+        $vis fn [<set_ $field>](self, value: $try_into_type) -> Self
+        {
+            self.[<set_ $field _internal>](value.into())
+        }
+
+        /// Private method, for use in the [`Default`] implementation.
+        fn [<$field _default>]() -> $try_into_type {
+            Default::default()
+        }
+
+        );
+    };
+
+    // Generates the public accessors for fields not converted to a type.
+    (
+        @public_field_accessors $vis:vis $name:ident $storage:ty : $hi:tt:$lo:tt $field:ident
+            $(, $comment:literal)?
+    ) => {
+        ::kernel::macros::paste!(
+
+        $(
+        #[doc="Returns the value of this field:"]
+        #[doc=$comment]
+        )?
+        #[inline(always)]
+        $vis fn $field(self) ->
+            ::kernel::num::BitInt<$storage, { $hi + 1 - $lo }>
+        {
+            self.[<$field _internal>]()
+        }
+
+        $(
+        #[doc="Sets the value of this field:"]
+        #[doc=$comment]
+        )?
+        #[inline(always)]
+        $vis fn [<set_ $field>]<T>(
+            self,
+            value: T,
+        ) -> Self
+            where T: Into<::kernel::num::BitInt<$storage, { $hi + 1 - $lo }>>,
+        {
+            self.[<set_ $field _internal>](value.into())
+        }
+
+        $(
+        #[doc="Attempts to set the value of this field:"]
+        #[doc=$comment]
+        )?
+        #[inline(always)]
+        $vis fn [<try_set_ $field>]<T>(
+            self,
+            value: T,
+        ) -> ::kernel::error::Result<Self>
+            where T: ::kernel::num::TryIntoBitInt<$storage, { $hi + 1 - $lo }>,
+        {
+            Ok(
+                self.[<set_ $field _internal>](
+                    value.try_into_bitint().ok_or(::kernel::error::code::EOVERFLOW)?
+                )
+            )
+        }
+
+        /// Private method, for use in the [`Default`] implementation.
+        fn [<$field _default>]() -> ::kernel::num::BitInt<$storage, { $hi + 1 - $lo }> {
+            Default::default()
+        }
+
         );
     };
 
@@ -319,7 +355,7 @@ fn default() -> Self {
 
                 ::kernel::macros::paste!(
                 $(
-                value.[<set_ $field>](Default::default());
+                value.[<set_ $field>](Self::[<$field _default>]());
                 )*
                 );
 
drivers/gpu/nova-core/falcon.rs +72 -62

263 lines not on this page · raw message

drivers/gpu/nova-core/falcon/hal/ga102.rs +3 -2
index afed353b24d2..c43e48823eff 100644
@@ -51,7 +51,7 @@ fn signature_reg_fuse_version_ga102(
 
     // `ucode_idx` is guaranteed to be in the range [0..15], making the `read` calls provable valid
     // at build-time.
-    let reg_fuse_version = if engine_id_mask & 0x0001 != 0 {
+    let reg_fuse_version: u16 = if engine_id_mask & 0x0001 != 0 {
         regs::NV_FUSE_OPT_FPF_SEC2_UCODE1_VERSION::read(bar, ucode_idx).data()
     } else if engine_id_mask & 0x0004 != 0 {
         regs::NV_FUSE_OPT_FPF_NVDEC_UCODE1_VERSION::read(bar, ucode_idx).data()
@@ -60,7 +60,8 @@ fn signature_reg_fuse_version_ga102(
     } else {
         dev_err!(dev, "unexpected engine_id_mask {:#x}", engine_id_mask);
         return Err(EINVAL);
-    };
+    }
+    .into();
 
     // TODO[NUMM]: replace with `last_set_bit` once it lands.
     Ok(u16::BITS - reg_fuse_version.leading_zeros())
drivers/gpu/nova-core/fb/hal/ga100.rs +2 -1
index 871c42bf033a..5b55ca8aaddb 100644
@@ -2,6 +2,7 @@
 
 struct Ga100;
 
+use kernel::num::BitInt;
 use kernel::prelude::*;
 
 use crate::driver::Bar0;
@@ -18,7 +19,7 @@ pub(super) fn read_sysmem_flush_page_ga100(bar: &Bar0) -> u64 {
 
 pub(super) fn write_sysmem_flush_page_ga100(bar: &Bar0, addr: u64) {
     regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI::default()
-        .set_adr_63_40((addr >> FLUSH_SYSMEM_ADDR_SHIFT_HI) as u32)
+        .set_adr_63_40(BitInt::from_expr(addr >> FLUSH_SYSMEM_ADDR_SHIFT_HI).cast())
         .write(bar);
     regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::default()
         .set_adr_39_08((addr >> FLUSH_SYSMEM_ADDR_SHIFT) as u32)
drivers/gpu/nova-core/gpu.rs +5 -4
index 9d182bffe8b4..2db3e48ea59f 100644
@@ -1,5 +1,6 @@
 // SPDX-License-Identifier: GPL-2.0
 
+use kernel::num::BitInt;
 use kernel::{device, devres::Devres, error::code::*, fmt, pci, prelude::*, sync::Arc};
 
 use crate::driver::Bar0;
@@ -130,15 +131,15 @@ fn try_from(value: u8) -> Result<Self> {
 }
 
 pub(crate) struct Revision {
-    major: u8,
-    minor: u8,
+    major: BitInt<u8, 4>,
+    minor: BitInt<u8, 4>,
 }
 
 impl Revision {
     fn from_boot0(boot0: regs::NV_PMC_BOOT_0) -> Self {
         Self {
-            major: boot0.major_revision(),
-            minor: boot0.minor_revision(),
+            major: boot0.major_revision().cast(),
+            minor: boot0.minor_revision().cast(),
         }
     }
 }
drivers/gpu/nova-core/regs.rs +70 -69

315 lines not on this page · raw message

Signature · 1 line
2.51.2