Skip to contentSkip to conversation

rust: add Bounded integer type

PATCH Superseded Alexandre Courbot 2 participants 9 messages Nov 6, 2025

Subsystems (5)

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

v3 cover rust: add Bounded integer type

New revision, where we rename BitInt to Bounded and consolidate things a bit. The Integer trait also exposes more common features of integers to generic code, which makes it more useful - to the point where we can now use it in place of the Boundable trait.

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 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           |  140 ++--
 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                        |   79 +++
 rust/kernel/num/bounded.rs                | 1045 +++++++++++++++++++++++++++++
 10 files changed, 1492 insertions(+), 303 deletions(-)

---
base-commit: ade19c5060dfa39b84a9475a4a6b05e2a8a2b3ac
change-id: 20251001-bounded_ints-1d0457d9ae26

Best regards,

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

PATCH v3 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
maintainer
#2 lore raw

Re: [PATCH v3 1/4] rust: add num module and Integer trait

Quoted 32 lines · Alexandre Courbot

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 +1 -0
new file mode 100644
index 000000000000..3f85e50b8632
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: GPL-2.0

rust/kernel/num.rs line 11

Quoted 10 lines
rust/kernel/num.rs new file +10 -0
+
+//! Additional numerical features for the kernel.
+
+use core::ops;
+
+/// Designates unsigned primitive types.
+pub struct Unsigned(());
+
+/// Designates signed primitive types.
+pub struct Signed(());

Since these types are not intended to be constructed, I would suggest using enums so that they can't be constructed:

	pub enum Unsigned {}
	pub enum Signed {}

Alice

author maintainer
#3 lore raw

Re: [PATCH v3 1/4] rust: add num module and Integer trait

Quoted 47 lines · Alice Ryhl
Quoted 32 lines · Alexandre Courbot

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 +1 -0
new file mode 100644
index 000000000000..3f85e50b8632
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: GPL-2.0

rust/kernel/num.rs line 11

Quoted 10 lines
rust/kernel/num.rs new file +10 -0
+
+//! Additional numerical features for the kernel.
+
+use core::ops;
+
+/// Designates unsigned primitive types.
+pub struct Unsigned(());
+
+/// Designates signed primitive types.
+pub struct Signed(());

Since these types are not intended to be constructed, I would suggest using enums so that they can't be constructed:

Quoted 2 lines
	pub enum Unsigned {}
	pub enum Signed {}

Ah, of course - I thought about having a private () to forbid construction outside of the module, but the empty enum prevents them from being instantiated from the module as well! Will apply, thanks!

author maintainer
#4 lore raw

PATCH v3 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 | 1045 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1048 insertions(+)
rust/kernel/num.rs +3 -0
index 3f85e50b8632..bc9abcc3a317 100644
@@ -4,6 +4,9 @@
 
 use core::ops;
 
+pub mod bounded;
+pub use bounded::*;
+
 /// Designates unsigned primitive types.
 pub struct Unsigned(());
 
rust/kernel/num/bounded.rs new file +1045 -0

1,045 lines not on this page · raw message

Signature · 1 line
2.51.2
maintainer
#5 lore raw

Re: [PATCH v3 2/4] rust: num: add Bounded integer wrapping type

Quoted 57 lines · 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 | 1045 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1048 insertions(+)
rust/kernel/num.rs +3 -0
index 3f85e50b8632..bc9abcc3a317 100644
@@ -4,6 +4,9 @@
 
 use core::ops;
 
+pub mod bounded;
+pub use bounded::*;
+
 /// Designates unsigned primitive types.
 pub struct Unsigned(());
 
rust/kernel/num/bounded.rs new file +21 -0
new file mode 100644
index 000000000000..2e4bc4ce9af5
@@ -0,0 +1,1045 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Implementation of [`Bounded`], a wrapper around integer types limiting the number of bits
+//! usable for value representation.
+
+use core::{
+    cmp,
+    fmt,
+    ops::{
+        self,
+        Deref, //
+    }, //,
+};
+
+use kernel::{
+    num::Integer,
+    prelude::*, //
+};
+
+/// Evaluates to `true` if `$value` can be represented using at most `$n` bits in a `$type`.
+///

rust/kernel/num/bounded.rs line 31

Quoted 10 lines
rust/kernel/num/bounded.rs new file +10 -0
+/// Can be used in const context.
+macro_rules! fits_within {
+    ($value:expr, $type:ty, $n:expr) => {{
+        let shift: u32 = <$type>::BITS - $n;
+
+        // `value` fits within `$n` bits if shifting it left by the number of unused bits, then
+        // right by the same number, doesn't change it.
+        //
+        // This method has the benefit of working for both unsigned and signed values.
+        ($value << shift) >> shift == $value

I'm still confused about whether this works or not for signed values.

I guess for a signed 4-bit int, the range of values is -8 to 7, so those are the values that this shift should preserve the values of. Is that what it does?

Alice

author maintainer
#6 lore raw

Re: [PATCH v3 2/4] rust: num: add Bounded integer wrapping type

Quoted 71 lines · Alice Ryhl
Quoted 57 lines · 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 | 1045 ++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1048 insertions(+)
rust/kernel/num.rs +3 -0
index 3f85e50b8632..bc9abcc3a317 100644
@@ -4,6 +4,9 @@
 
 use core::ops;
 
+pub mod bounded;
+pub use bounded::*;
+
 /// Designates unsigned primitive types.
 pub struct Unsigned(());
 
rust/kernel/num/bounded.rs new file +21 -0
new file mode 100644
index 000000000000..2e4bc4ce9af5
@@ -0,0 +1,1045 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Implementation of [`Bounded`], a wrapper around integer types limiting the number of bits
+//! usable for value representation.
+
+use core::{
+    cmp,
+    fmt,
+    ops::{
+        self,
+        Deref, //
+    }, //,
+};
+
+use kernel::{
+    num::Integer,
+    prelude::*, //
+};
+
+/// Evaluates to `true` if `$value` can be represented using at most `$n` bits in a `$type`.
+///

rust/kernel/num/bounded.rs line 31

Quoted 10 lines
rust/kernel/num/bounded.rs new file +10 -0
+/// Can be used in const context.
+macro_rules! fits_within {
+    ($value:expr, $type:ty, $n:expr) => {{
+        let shift: u32 = <$type>::BITS - $n;
+
+        // `value` fits within `$n` bits if shifting it left by the number of unused bits, then
+        // right by the same number, doesn't change it.
+        //
+        // This method has the benefit of working for both unsigned and signed values.
+        ($value << shift) >> shift == $value

I'm still confused about whether this works or not for signed values.

Quoted 3 lines

I guess for a signed 4-bit int, the range of values is -8 to 7, so those are the values that this shift should preserve the values of. Is that what it does?

Let's roll these examples, using a 4 bit integer backed by a i8.

-8i8 in binary is 1111_1000. Shift it left by 4 (i8::BITS - 4), and you get 1000_0000. Shift it back right by 4, you get 1111_1000, which is the original value. The smallest possible representation of -8 is 1000, which indeed fits in 4 bits.

Now -9i8. In binary it is 1111_0111. Shift it left by 4, you get 0111_0000. Shift back right, you get 0000_0111. The value is different, it doesn't fit - and indeed, its smallest representation is 1_0111, which requires 5 bits.

And if you go with smaller negative numbers, some 0 will eventually end up in the 4 MSBs and lost in the shift, so any value < -9 is properly detected as non-fitting.

Now for the positive limit. 7i8 is 0000_0111. Shift left by 4, 0111_0000. Shift back right, 0000_0111, original value. Smallest possible representation of 7 as a signed integer (thus including the bit sign) is 0111, so that works.

8i8 now. In binary, it's 0000_1000. Shift left by 4, 1000_0000. Shift back right, 1111_1000. Doesn't fit, because its smallest possible representation is 0_1000, 5 bits.

I have confirmed the above with a kunit test as well. Actually I will probably add these to the doctest for try_new - since all that constructor does is call fits_within, that will cover these edge cases.

author maintainer
#7 lore raw

PATCH v3 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
author maintainer
#8 lore raw

PATCH v3 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           | 140 +++++++-----
 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, 359 insertions(+), 303 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 +78 -62

269 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..8da754d84153 100644
@@ -2,6 +2,7 @@
 
 struct Ga100;
 
+use kernel::num::Bounded;
 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(Bounded::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..119bfb197a1e 100644
@@ -1,5 +1,6 @@
 // SPDX-License-Identifier: GPL-2.0
 
+use kernel::num::Bounded;
 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: 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