Skip to contentSkip to conversation

rust: add Bounded integer type

PATCH Applied Alexandre Courbot 4 participants 13 messages Nov 8, 2025 – Nov 19, 2025

Subsystems (5)
lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

v4 cover rust: add Bounded integer type

Minor revision adding the feedback received on v3.

Patch 3 adds a MAINTAINERS entry in case the Rust core team would like us to maintain this, but please ignore it if you prefer to take it under the core umbrella.

This series provides Bounded, 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.

For a basic usage, please see the rustdoc of the Bounded type on the second 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 last patch is just 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 last patch, but the first 2 patches 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 v4:
- Change Unsigned and Signed to be empty enums so they can never be instantiated (thanks Alice!).
- Add test at the limits of a Bounded<i8, 4> to confirm fits_within
is working as expected.
- Rebase on top of drm-rust-next for Nova patch.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Rename to Bounded to avoid confusion with C's _BitInt.
- Request all common integer features on Integer trait and remove unneeded Boundable.
- Use assert instead of build_assert in const blocks. (thanks Alice!)
- Implement Integer for u/isize and u/i128.
- Support usize/isize as Bounded types.
- Implement arithmetic and logic ops between two Bounded of the same backing type (but not necessarily same length).
- Move addition of num module to its own patch.
- Add MAINTAINERS entry for num.
- Link to v2: https://lore.kernel.org/r/[email protected]

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 (4):
rust: add num module and Integer trait
rust: num: add Bounded integer wrapping type
MAINTAINERS: add entry for the Rust num module [FOR REFERENCE] gpu: nova-core: use BitInt for bitfields

 MAINTAINERS                               |    8 +
 drivers/gpu/nova-core/bitfield.rs         |  366 +++++-----
 drivers/gpu/nova-core/falcon.rs           |  145 ++--
 drivers/gpu/nova-core/falcon/hal/ga102.rs |    5 +-
 drivers/gpu/nova-core/fb/hal/ga100.rs     |    9 +-
 drivers/gpu/nova-core/gpu.rs              |    9 +-
 drivers/gpu/nova-core/regs.rs             |  139 ++--
 rust/kernel/lib.rs                        |    1 +
 rust/kernel/num.rs                        |   79 +++
 rust/kernel/num/bounded.rs                | 1054 +++++++++++++++++++++++++++++
 10 files changed, 1507 insertions(+), 308 deletions(-)

---
base-commit: 80b3dc0a5a2e51fb2b8f3406f5ee20ad4a652316
change-id: 20251001-bounded_ints-1d0457d9ae26

Best regards,

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

PATCH v4 1/4 rust: add num module and Integer trait

Introduce the num module, which will provide numerical extensions and utilities for the kernel.

For now, introduce the Integer trait, which is implemented for all primitive integer types to provides their core properties to generic code.

---
 rust/kernel/lib.rs |  1 +
 rust/kernel/num.rs | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 77 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 +76 -0

76 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#2 lore raw

PATCH v4 2/4 rust: num: add Bounded integer wrapping type

In reply to Alexandre Courbot

Add the Bounded integer wrapper type, which restricts the number of bits allowed to represent of value.

This is useful to e.g. enforce guarantees when working with bitfields that have an arbitrary number of bits.

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

---
 rust/kernel/num.rs         |    3 +
 rust/kernel/num/bounded.rs | 1054 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1057 insertions(+)
rust/kernel/num.rs +3 -0
index c8c91cb9e682..8532b511384c 100644
@@ -4,6 +4,9 @@
 
 use core::ops;
 
+pub mod bounded;
+pub use bounded::*;
+
 /// Designates unsigned primitive types.
 pub enum Unsigned {}
 
rust/kernel/num/bounded.rs new file +1054 -0

1,054 lines not on this page · raw message

Signature · 1 line
2.51.2
author maintainer
#3 lore raw

PATCH v4 3/4 MAINTAINERS: add entry for the Rust `num` module

In reply to Alexandre Courbot

This new module provides numerical features useful for the kernel, such as the Integer trait and the Bounded integer wrapper.

---
 MAINTAINERS | 8 ++++++++
 1 file changed, 8 insertions(+)
MAINTAINERS +8 -0
index 952aed4619c2..b6294a2903c1 100644
@@ -22521,6 +22521,14 @@ T:	git https://github.com/Rust-for-Linux/linux.git alloc-next
 F:	rust/kernel/alloc.rs
 F:	rust/kernel/alloc/
 
+RUST [NUM]
+M:	Alexandre Courbot <[email protected]>
+R:	Yury Norov <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	rust/kernel/num.rs
+F:	rust/kernel/num/
+
 RUST [PIN-INIT]
 M:	Benno Lossin <[email protected]>
 L:	[email protected]
Signature · 1 line
2.51.2
#4 lore raw

Re: [PATCH v4 3/4] MAINTAINERS: add entry for the Rust `num` module

Quoted 2 lines · Alexandre Courbot

+R: Yury Norov <[email protected]>

Yury didn't Ack'd this, but I will assume it is OK since he mentioned so in v1.

Cheers,
Miguel

author maintainer
#6 lore raw

PATCH v4 4/4 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           | 145 ++++++------
 drivers/gpu/nova-core/falcon/hal/ga102.rs |   5 +-
 drivers/gpu/nova-core/fb/hal/ga100.rs     |   9 +-
 drivers/gpu/nova-core/gpu.rs              |   9 +-
 drivers/gpu/nova-core/regs.rs             | 139 ++++++------
 6 files changed, 365 insertions(+), 308 deletions(-)
drivers/gpu/nova-core/bitfield.rs +201 -165
index 16e143658c51..be4d54feb38c 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<Bounded<u32, 4>> for Mode {
+///     type Error = u32;
+///     fn try_from(value: Bounded<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 Bounded<u32, 4> {
+///     fn from(mode: Mode) -> Bounded<u32, 4> {
+///         Bounded::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<Bounded<u32, 1>> for State {
+///     fn from(value: Bounded<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 Bounded<u32, 1> {
+///     fn from(state: State) -> Bounded<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::Bounded<$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::Bounded::<$storage, { $hi + 1 - $lo }>::from_expr(field)
+        }
+
+        fn [<set_ $field _internal>](
+            mut self,
+            value: ::kernel::num::Bounded<$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::TryIntoBounded<$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::Bounded<$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::Bounded<$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::Bounded<$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::TryIntoBounded<$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::Bounded<$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 +81 -64

274 lines not on this page · raw message

drivers/gpu/nova-core/falcon/hal/ga102.rs +3 -2
index 69a7a95cac16..72afbd9101cf 100644
@@ -59,7 +59,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()
@@ -68,7 +68,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 +5 -4
index e0acc41aa7cd..acf46ad0dba1 100644
@@ -1,6 +1,9 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use kernel::prelude::*;
+use kernel::{
+    num::Bounded,
+    prelude::*, //
+};
 
 use crate::{
     driver::Bar0,
@@ -20,9 +23,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()
-        // CAST: `as u32` is used on purpose since the remaining bits are guaranteed to fit within
-        // a `u32`.
-        .set_adr_63_40((addr >> FLUSH_SYSMEM_ADDR_SHIFT_HI) as u32)
+        .set_adr_63_40(Bounded::from_expr(addr >> FLUSH_SYSMEM_ADDR_SHIFT_HI).cast())
         .write(bar);
     regs::NV_PFB_NISO_FLUSH_SYSMEM_ADDR::default()
         // CAST: `as u32` is used on purpose since we want to strip the upper bits that have been
drivers/gpu/nova-core/gpu.rs +5 -4
index 802e71e4f97d..faa1ab58b4fe 100644
@@ -4,6 +4,7 @@
     device,
     devres::Devres,
     fmt,
+    num::Bounded,
     pci,
     prelude::*,
     sync::Arc, //
@@ -143,15 +144,15 @@ fn try_from(value: u8) -> Result<Self> {
 }
 
 pub(crate) struct Revision {
-    major: u8,
-    minor: u8,
+    major: Bounded<u8, 4>,
+    minor: Bounded<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
author maintainer
#7 lore raw
In reply to Alexandre Courbot
Quoted 25 lines · Alexandre Courbot

Minor revision adding the feedback received on v3.

Patch 3 adds a MAINTAINERS entry in case the Rust core team would like us to maintain this, but please ignore it if you prefer to take it under the core umbrella.

This series provides Bounded, 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.

For a basic usage, please see the rustdoc of the Bounded type on the second 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 last patch is just 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.

Quoted 7 lines

This series applies on top of drm-rust-next for the needs of the last patch, but the first 2 patches 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

Hi Rust core team,

With -rc6 approaching, may I enquire on the appetite to merge this for 6.19? This is the last hard dependency for moving the bitfield/register macros out of Nova, so we need it if we want to tackle this for the next cycle.

Please let me know if there is more I can do to bring this to shape! :)

Acked-by
#8 lore raw
Quoted 9 lines · Alexandre Courbot

Hi Rust core team,

With -rc6 approaching, may I enquire on the appetite to merge this for 6.19? This is the last hard dependency for moving the bitfield/register macros out of Nova, so we need it if we want to tackle this for the next cycle.

Please let me know if there is more I can do to bring this to shape! :)

Let's get some testing in linux-next :)

Thanks!

Cheers,
Miguel

author maintainer
#9 lore raw
Quoted 9 lines · Miguel Ojeda
Quoted 8 lines · Alexandre Courbot

Hi Rust core team,

With -rc6 approaching, may I enquire on the appetite to merge this for 6.19? This is the last hard dependency for moving the bitfield/register macros out of Nova, so we need it if we want to tackle this for the next cycle.

Quoted 5 lines
Quoted 1 line

Please let me know if there is more I can do to bring this to shape! :)

Let's get some testing in linux-next :)

Thanks! What is the path from this to linux-next? IIUC we wanted to merge this series (minus patch 4) through the Rust (not drm-rust) tree.

#10 lore raw
Quoted 3 lines · Alexandre Courbot

Thanks! What is the path from this to linux-next? IIUC we wanted to merge this series (minus patch 4) through the Rust (not drm-rust) tree.

Sounds fine, I can take them. Thanks!

Cheers,
Miguel

maintainer Reviewed-by on the v4 series
#11 lore raw
In reply to Alexandre Courbot
Quoted 25 lines · Alexandre Courbot

Minor revision adding the feedback received on v3.

Patch 3 adds a MAINTAINERS entry in case the Rust core team would like us to maintain this, but please ignore it if you prefer to take it under the core umbrella.

This series provides Bounded, 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.

For a basic usage, please see the rustdoc of the Bounded type on the second 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 last patch is just 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.

Quoted 7 lines

This series applies on top of drm-rust-next for the needs of the last patch, but the first 2 patches 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

Applied
#12 lore raw
In reply to Alexandre Courbot
Quoted 26 lines · Alexandre Courbot

Minor revision adding the feedback received on v3.

Patch 3 adds a MAINTAINERS entry in case the Rust core team would like us to maintain this, but please ignore it if you prefer to take it under the core umbrella.

This series provides Bounded, 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.

For a basic usage, please see the rustdoc of the Bounded type on the second 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 last patch is just 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.

Quoted 7 lines

This series applies on top of drm-rust-next for the needs of the last patch, but the first 2 patches 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

Applied to rust-next -- thanks everyone!

[ Added intra-doc link. Fixed a few other nits. - Miguel ]

Cheers,
Miguel