* [PATCH v3 1/4] rust: add num module and Integer trait
2025-11-06 7:07 [PATCH v3 0/4] rust: add Bounded integer type Alexandre Courbot
@ 2025-11-06 7:07 ` Alexandre Courbot
2025-11-06 9:46 ` Alice Ryhl
2025-11-06 7:07 ` [PATCH v3 2/4] rust: num: add Bounded integer wrapping type Alexandre Courbot
` (2 subsequent siblings)
3 siblings, 1 reply; 9+ messages in thread
From: Alexandre Courbot @ 2025-11-06 7:07 UTC (permalink / raw)
To: Alice Ryhl, Danilo Krummrich, Miguel Ojeda, Joel Fernandes,
Yury Norov, Jesung Yang, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross
Cc: linux-kernel, rust-for-linux, 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.
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
---
rust/kernel/lib.rs | 1 +
rust/kernel/num.rs | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 77 insertions(+)
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 3dd7bebe7888..235d0d8b1eff 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -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;
diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs
new file mode 100644
index 000000000000..3f85e50b8632
--- /dev/null
+++ b/rust/kernel/num.rs
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Additional numerical features for the kernel.
+
+use core::ops;
+
+/// Designates unsigned primitive types.
+pub struct Unsigned(());
+
+/// Designates signed primitive types.
+pub struct Signed(());
+
+/// Describes core properties of integer types.
+pub trait Integer:
+ Sized
+ + Copy
+ + Clone
+ + PartialEq
+ + Eq
+ + PartialOrd
+ + Ord
+ + ops::Add<Output = Self>
+ + ops::AddAssign
+ + ops::Sub<Output = Self>
+ + ops::SubAssign
+ + ops::Mul<Output = Self>
+ + ops::MulAssign
+ + ops::Div<Output = Self>
+ + ops::DivAssign
+ + ops::Rem<Output = Self>
+ + ops::RemAssign
+ + ops::BitAnd<Output = Self>
+ + ops::BitAndAssign
+ + ops::BitOr<Output = Self>
+ + ops::BitOrAssign
+ + ops::BitXor<Output = Self>
+ + ops::BitXorAssign
+ + ops::Shl<u32, Output = Self>
+ + ops::ShlAssign<u32>
+ + ops::Shr<u32, Output = Self>
+ + ops::ShrAssign<u32>
+ + ops::Not
+{
+ /// Whether this type is [`Signed`] or [`Unsigned`].
+ type Signedness;
+
+ /// Number of bits used for value representation.
+ const BITS: u32;
+}
+
+macro_rules! impl_integer {
+ ($($type:ty: $signedness:ty), *) => {
+ $(
+ impl Integer for $type {
+ type Signedness = $signedness;
+
+ const BITS: u32 = <$type>::BITS;
+ }
+ )*
+ };
+}
+
+impl_integer!(
+ u8: Unsigned,
+ u16: Unsigned,
+ u32: Unsigned,
+ u64: Unsigned,
+ u128: Unsigned,
+ usize: Unsigned,
+ i8: Signed,
+ i16: Signed,
+ i32: Signed,
+ i64: Signed,
+ i128: Signed,
+ isize: Signed
+);
--
2.51.2
^ permalink raw reply related [flat|nested] 9+ messages in thread* Re: [PATCH v3 1/4] rust: add num module and Integer trait
2025-11-06 7:07 ` [PATCH v3 1/4] rust: add num module and Integer trait Alexandre Courbot
@ 2025-11-06 9:46 ` Alice Ryhl
2025-11-06 11:05 ` Alexandre Courbot
0 siblings, 1 reply; 9+ messages in thread
From: Alice Ryhl @ 2025-11-06 9:46 UTC (permalink / raw)
To: Alexandre Courbot
Cc: Danilo Krummrich, Miguel Ojeda, Joel Fernandes, Yury Norov,
Jesung Yang, Boqun Feng, Gary Guo, Björn Roy Baron,
Benno Lossin, Andreas Hindborg, Trevor Gross, linux-kernel,
rust-for-linux
On Thu, Nov 06, 2025 at 04:07:13PM +0900, Alexandre Courbot wrote:
> 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.
>
> Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
> ---
> rust/kernel/lib.rs | 1 +
> rust/kernel/num.rs | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
> 2 files changed, 77 insertions(+)
>
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 3dd7bebe7888..235d0d8b1eff 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -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;
> diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs
> new file mode 100644
> index 000000000000..3f85e50b8632
> --- /dev/null
> +++ b/rust/kernel/num.rs
> @@ -0,0 +1,76 @@
> +// SPDX-License-Identifier: GPL-2.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
^ permalink raw reply [flat|nested] 9+ messages in thread* Re: [PATCH v3 1/4] rust: add num module and Integer trait
2025-11-06 9:46 ` Alice Ryhl
@ 2025-11-06 11:05 ` Alexandre Courbot
0 siblings, 0 replies; 9+ messages in thread
From: Alexandre Courbot @ 2025-11-06 11:05 UTC (permalink / raw)
To: Alice Ryhl, Alexandre Courbot
Cc: Danilo Krummrich, Miguel Ojeda, Joel Fernandes, Yury Norov,
Jesung Yang, Boqun Feng, Gary Guo, Björn Roy Baron,
Benno Lossin, Andreas Hindborg, Trevor Gross, linux-kernel,
rust-for-linux
On Thu Nov 6, 2025 at 6:46 PM JST, Alice Ryhl wrote:
> On Thu, Nov 06, 2025 at 04:07:13PM +0900, Alexandre Courbot wrote:
>> 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.
>>
>> Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
>> ---
>> rust/kernel/lib.rs | 1 +
>> rust/kernel/num.rs | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
>> 2 files changed, 77 insertions(+)
>>
>> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
>> index 3dd7bebe7888..235d0d8b1eff 100644
>> --- a/rust/kernel/lib.rs
>> +++ b/rust/kernel/lib.rs
>> @@ -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;
>> diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs
>> new file mode 100644
>> index 000000000000..3f85e50b8632
>> --- /dev/null
>> +++ b/rust/kernel/num.rs
>> @@ -0,0 +1,76 @@
>> +// SPDX-License-Identifier: GPL-2.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 {}
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!
^ permalink raw reply [flat|nested] 9+ messages in thread
* [PATCH v3 2/4] rust: num: add Bounded integer wrapping type
2025-11-06 7:07 [PATCH v3 0/4] rust: add Bounded integer type Alexandre Courbot
2025-11-06 7:07 ` [PATCH v3 1/4] rust: add num module and Integer trait Alexandre Courbot
@ 2025-11-06 7:07 ` Alexandre Courbot
2025-11-06 9:53 ` Alice Ryhl
2025-11-06 7:07 ` [PATCH v3 3/4] MAINTAINERS: add entry for the Rust `num` module Alexandre Courbot
2025-11-06 7:07 ` [PATCH FOR REFERENCE v3 4/4] gpu: nova-core: use BitInt for bitfields Alexandre Courbot
3 siblings, 1 reply; 9+ messages in thread
From: Alexandre Courbot @ 2025-11-06 7:07 UTC (permalink / raw)
To: Alice Ryhl, Danilo Krummrich, Miguel Ojeda, Joel Fernandes,
Yury Norov, Jesung Yang, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross
Cc: linux-kernel, rust-for-linux, 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.
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
---
rust/kernel/num.rs | 3 +
rust/kernel/num/bounded.rs | 1045 ++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 1048 insertions(+)
diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs
index 3f85e50b8632..bc9abcc3a317 100644
--- a/rust/kernel/num.rs
+++ b/rust/kernel/num.rs
@@ -4,6 +4,9 @@
use core::ops;
+pub mod bounded;
+pub use bounded::*;
+
/// Designates unsigned primitive types.
pub struct Unsigned(());
diff --git a/rust/kernel/num/bounded.rs b/rust/kernel/num/bounded.rs
new file mode 100644
index 000000000000..2e4bc4ce9af5
--- /dev/null
+++ b/rust/kernel/num/bounded.rs
@@ -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`.
+///
+/// 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
+ }};
+}
+
+/// Returns `true` if `value` can be represented with at most `N` bits in a `T`.
+fn fits_within<T: Integer>(value: T, num_bits: u32) -> bool {
+ fits_within!(value, T, num_bits)
+}
+
+/// An integer value that requires only the `N` less significant bits of the wrapped type to be
+/// encoded.
+///
+/// This limits the number of usable bits in the wrapped integer type, and thus the stored value to
+/// a narrower range, which provides guarantees that can be useful when working with in e.g.
+/// bitfields.
+///
+/// # Invariants
+///
+/// - `N` is greater than `0`.
+/// - `N` is less than or equal to `T::BITS`.
+/// - Stored values can be represented with at most `N` bits.
+///
+/// # Examples
+///
+/// The preferred way to create values is through constants and the [`Bounded::new`] family of
+/// constructors, as they trigger a build error if the type invariants cannot be withheld.
+///
+/// ```
+/// use kernel::num::Bounded;
+///
+/// // An unsigned 8-bit integer, of which only the 4 LSBs are used.
+/// // The value `15` is statically validated to fit that constraint at build time.
+/// let v = Bounded::<u8, 4>::new::<15>();
+/// assert_eq!(v.get(), 15);
+///
+/// // Same using signed values.
+/// let v = Bounded::<i8, 4>::new::<-8>();
+/// assert_eq!(v.get(), -8);
+///
+/// // This doesn't build: a `u8` is smaller than the requested 9 bits.
+/// // let _ = Bounded::<u8, 9>::new::<10>();
+///
+/// // This also doesn't build: the requested value doesn't fit within 4 signed bits.
+/// // let _ = Bounded::<i8, 4>::new::<8>();
+/// ```
+/// Values can also be validated at runtime with [`Bounded::try_new`].
+///
+/// ```
+/// use kernel::num::Bounded;
+///
+/// // This succeeds because `15` can be represented with 4 unsigned bits.
+/// assert!(Bounded::<u8, 4>::try_new(15).is_some());
+///
+/// // This fails because `16` cannot be represented with 4 unsigned bits.
+/// assert!(Bounded::<u8, 4>::try_new(16).is_none());
+/// ```
+///
+/// Non-constant expressions can be validated at build-time thanks to compiler optimizations. This
+/// should be used with caution, on simple expressions only.
+///
+/// ```
+/// use kernel::num::Bounded;
+/// # fn some_number() -> u32 { 0xffffffff }
+///
+/// // Here the compiler can infer from the mask that the type invariants are not violated, even
+/// // though the value returned by `some_number` is not statically known.
+/// let v = Bounded::<u32, 4>::from_expr(some_number() & 0xf);
+/// ```
+///
+/// Comparison and arithmetic operations are supported on [`Bounded`]s with a compatible backing
+/// type, regardless of their number of valid bits.
+///
+/// ```
+/// use kernel::num::Bounded;
+///
+/// let v1 = Bounded::<u32, 8>::new::<4>();
+/// let v2 = Bounded::<u32, 4>::new::<15>();
+///
+/// assert!(v1 != v2);
+/// assert!(v1 < v2);
+/// assert_eq!(v1 + v2, 19);
+/// assert_eq!(v2 % v1, 3);
+/// ```
+///
+/// These operations are also supported between a [`Bounded`] and its backing type.
+///
+/// ```
+/// use kernel::num::Bounded;
+///
+/// let v = Bounded::<u8, 4>::new::<15>();
+///
+/// assert!(v == 15);
+/// assert!(v > 12);
+/// assert_eq!(v + 5, 20);
+/// assert_eq!(v / 3, 5);
+/// ```
+///
+/// A change of backing types is possible using [`Bounded::cast`], and the number of valid bits can
+/// be extended or reduced with [`Bounded::extend`] and [`Bounded::try_shrink`].
+///
+/// ```
+/// use kernel::num::Bounded;
+///
+/// let v = Bounded::<u32, 12>::new::<127>();
+///
+/// // Changes backing type from `u32` to `u16`.
+/// let _: Bounded<u16, 12> = v.cast();
+///
+/// // This does not build, as `u8` is smaller than 12 bits.
+/// // let _: Bounded<u8, 12> = v.cast();
+///
+/// // We can safely extend the number of bits...
+/// let _ = v.extend::<15>();
+///
+/// // ... to the limits of the backing type. This doesn't build as a `u32` cannot contain 33 bits.
+/// // let _ = v.extend::<33>();
+///
+/// // Reducing the number of bits is validated at runtime. This works because `127` can be
+/// // represented with 8 bits.
+/// assert!(v.try_shrink::<8>().is_some());
+///
+/// // ... but not with 6, so this fails.
+/// assert!(v.try_shrink::<6>().is_none());
+/// ```
+///
+/// Infallible conversions from a primitive integer to a large-enough [`Bounded`] are supported.
+///
+/// ```
+/// use kernel::num::Bounded;
+///
+/// // This unsigned `Bounded` has 8 bits, so it can represent any `u8`.
+/// let v = Bounded::<u32, 8>::from(128u8);
+/// assert_eq!(v.get(), 128);
+///
+/// // This signed `Bounded` has 8 bits, so it can represent any `i8`.
+/// let v = Bounded::<i32, 8>::from(-128i8);
+/// assert_eq!(v.get(), -128);
+///
+/// // This doesn't build, as this 6-bit `Bounded` does not have enough capacity to represent a
+/// // `u8` (regardless of the passed value).
+/// // let _ = Bounded::<u32, 6>::from(10u8);
+///
+/// // Booleans can be converted into single-bit `Bounded`s.
+///
+/// let v = Bounded::<u64, 1>::from(false);
+/// assert_eq!(v.get(), 0);
+///
+/// let v = Bounded::<u64, 1>::from(true);
+/// assert_eq!(v.get(), 1);
+/// ```
+///
+/// Infallible conversions from a [`Bounded`] to a primitive integer are also supported, and
+/// dependent on the number of bits used for value representation, not on the backing type.
+///
+/// ```
+/// use kernel::num::Bounded;
+///
+/// // Even though its backing type is `u32`, this `Bounded` only uses 6 bits and thus can safely
+/// // be converted to a `u8`.
+/// let v = Bounded::<u32, 6>::new::<63>();
+/// assert_eq!(u8::from(v), 63);
+///
+/// // Same using signed values.
+/// let v = Bounded::<i32, 8>::new::<-128>();
+/// assert_eq!(i8::from(v), -128);
+///
+/// // This however does not build, as 10 bits won't fit into a `u8` (regardless of the actually
+/// // contained value).
+/// let _v = Bounded::<u32, 10>::new::<10>();
+/// // assert_eq!(u8::from(_v), 10);
+///
+/// // Single-bit `Bounded`s can be converted into a boolean.
+/// let v = Bounded::<u8, 1>::new::<1>();
+/// assert_eq!(bool::from(v), true);
+///
+/// let v = Bounded::<u8, 1>::new::<0>();
+/// assert_eq!(bool::from(v), false);
+/// ```
+///
+/// Fallible conversions from any primitive integer to any [`Bounded`] are also supported using the
+/// [`TryIntoBounded`] trait.
+///
+/// ```
+/// use kernel::num::{Bounded, TryIntoBounded};
+///
+/// // Succeeds because `128` fits into 8 bits.
+/// let v: Option<Bounded<u16, 8>> = 128u32.try_into_bitint();
+/// assert_eq!(v.as_deref().copied(), Some(128));
+///
+/// // Fails because `128` doesn't fits into 6 bits.
+/// let v: Option<Bounded<u16, 6>> = 128u32.try_into_bitint();
+/// assert_eq!(v, None);
+/// ```
+#[repr(transparent)]
+#[derive(Clone, Copy, Debug, Default, Hash)]
+pub struct Bounded<T: Integer, const N: u32>(T);
+
+/// Validating the value as a const expression cannot be done as a regular method, as the
+/// arithmetic operations we rely on to check the bounds are not const. Thus, implement
+/// [`Bounded::new`] using a macro.
+macro_rules! impl_const_new {
+ ($($type:ty)*) => {
+ $(
+ impl<const N: u32> Bounded<$type, N> {
+ /// Creates a [`Bounded`] for the constant `VALUE`.
+ ///
+ /// Fails at build time if `VALUE` cannot be represented with `N` bits.
+ ///
+ /// This method should be preferred to [`Self::from_expr`] whenever possible.
+ ///
+ /// # Examples
+ /// ```
+ /// use kernel::num::Bounded;
+ ///
+ #[doc = ::core::concat!(
+ "let v = Bounded::<",
+ ::core::stringify!($type),
+ ", 4>::new::<7>();")]
+ /// assert_eq!(v.get(), 7);
+ /// ```
+ pub const fn new<const VALUE: $type>() -> Self {
+ // Statically assert that `VALUE` fits within the set number of bits.
+ const {
+ assert!(fits_within!(VALUE, $type, N));
+ }
+
+ // INVARIANT: `fits_within` confirmed that `VALUE` can be represented within
+ // `N` bits.
+ Self::__new(VALUE)
+ }
+ }
+ )*
+ };
+}
+
+impl_const_new!(
+ u8 u16 u32 u64 usize
+ i8 i16 i32 i64 isize
+);
+
+impl<T, const N: u32> Bounded<T, N>
+where
+ T: Integer,
+{
+ /// Private constructor enforcing the type invariants.
+ ///
+ /// All instances of [`Bounded`] must be created through this method as it enforces most of the
+ /// type invariants.
+ ///
+ /// The caller remains responsible for checking, either statically or dynamically, that `value`
+ /// can be represented as a `T` using at most `N` bits.
+ const fn __new(value: T) -> Self {
+ // Enforce the type invariants.
+ const {
+ // `N` cannot be zero.
+ assert!(N != 0);
+ // The backing type is at least as large as `N` bits.
+ assert!(N <= T::BITS);
+ }
+
+ Self(value)
+ }
+
+ /// Attempts to turn `value` into a `Bounded` using `N` bits.
+ ///
+ /// Returns [`None`] if `value` doesn't fit within `N` bits.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use kernel::num::Bounded;
+ ///
+ /// let v = Bounded::<u8, 1>::try_new(1);
+ /// assert_eq!(v.as_deref().copied(), Some(1));
+ ///
+ /// let v = Bounded::<i8, 4>::try_new(-2);
+ /// assert_eq!(v.as_deref().copied(), Some(-2));
+ ///
+ /// // `0x1ff` doesn't fit into 8 unsigned bits.
+ /// let v = Bounded::<u32, 8>::try_new(0x1ff);
+ /// assert_eq!(v, None);
+ ///
+ /// // `8` doesn't fit into 4 signed bits.
+ /// let v = Bounded::<i8, 4>::try_new(8);
+ /// assert_eq!(v, None);
+ /// ```
+ pub fn try_new(value: T) -> Option<Self> {
+ fits_within(value, N).then(|| {
+ // INVARIANT: `fits_within` confirmed that `value` can be represented within `N` bits.
+ Self::__new(value)
+ })
+ }
+
+ /// Checks that `expr` is valid for this type at compile-time and build a new value.
+ ///
+ /// This relies on [`build_assert!`] and guaranteed optimization to perform validation at
+ /// compile-time. If `expr` cannot be proved to be within the requested bounds at compile-time,
+ /// use the fallible [`Self::try_new`] instead.
+ ///
+ /// Limit this to simple, easily provable expressions, and prefer one of the [`Self::new`]
+ /// constructors whenever possible as they statically validate the value instead of relying on
+ /// compiler optimizations.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use kernel::num::Bounded;
+ /// # fn some_number() -> u32 { 0xffffffff }
+ ///
+ /// // Some undefined number.
+ /// let v: u32 = some_number();
+ ///
+ /// // Triggers a build error as `v` cannot be asserted to fit within 4 bits...
+ /// // let _ = Bounded::<u32, 4>::from_expr(v);
+ ///
+ /// // ... but this works as the compiler can assert the range from the mask.
+ /// let _ = Bounded::<u32, 4>::from_expr(v & 0xf);
+ ///
+ /// // These expressions are simple enough to be proven correct, but since they are static the
+ /// // `new` constructor should be preferred.
+ /// assert_eq!(Bounded::<u8, 1>::from_expr(1).get(), 1);
+ /// assert_eq!(Bounded::<u16, 8>::from_expr(0xff).get(), 0xff);
+ /// ```
+ pub fn from_expr(expr: T) -> Self {
+ crate::build_assert!(
+ fits_within(expr, N),
+ "Requested value larger than maximal representable value."
+ );
+
+ // INVARIANT: `fits_within` confirmed that `expr` can be represented within `N` bits.
+ Self::__new(expr)
+ }
+
+ /// Returns the wrapped value as the backing type.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use kernel::num::Bounded;
+ ///
+ /// let v = Bounded::<u32, 4>::new::<7>();
+ /// assert_eq!(v.get(), 7u32);
+ /// ```
+ pub fn get(self) -> T {
+ *self.deref()
+ }
+
+ /// Increases the number of bits usable for `self`.
+ ///
+ /// This operation cannot fail.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use kernel::num::Bounded;
+ ///
+ /// let v = Bounded::<u32, 4>::new::<7>();
+ /// let larger_v = v.extend::<12>();
+ /// // The contained values are equal even though `larger_v` has a bigger capacity.
+ /// assert_eq!(larger_v, v);
+ /// ```
+ pub const fn extend<const M: u32>(self) -> Bounded<T, M> {
+ const {
+ assert!(
+ M >= N,
+ "Requested number of bits is less than the current representation."
+ );
+ }
+
+ // INVARIANT: the value did fit within `N` bits, so it will all the more fit within
+ // the larger `M` bits.
+ Bounded::__new(self.0)
+ }
+
+ /// Attempts to shrink the number of bits usable for `self`.
+ ///
+ /// Returns [`None`] if the value of `self` cannot be represented within `M` bits.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use kernel::num::Bounded;
+ ///
+ /// let v = Bounded::<u32, 12>::new::<7>();
+ ///
+ /// // `7` can be represented using 3 unsigned bits...
+ /// let smaller_v = v.try_shrink::<3>();
+ /// assert_eq!(smaller_v.as_deref().copied(), Some(7));
+ ///
+ /// // ... but doesn't fit within `2` bits.
+ /// assert_eq!(v.try_shrink::<2>(), None);
+ /// ```
+ pub fn try_shrink<const M: u32>(self) -> Option<Bounded<T, M>> {
+ Bounded::<T, M>::try_new(self.get())
+ }
+
+ /// Casts `self` into a [`Bounded`] backed by a different storage type, but using the same
+ /// number of valid bits.
+ ///
+ /// Both `T` and `U` must be of same signedness, and `U` must be at least as large as
+ /// `N` bits, or a build error will occur.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ /// use kernel::num::Bounded;
+ ///
+ /// let v = Bounded::<u32, 12>::new::<127>();
+ ///
+ /// let u16_v: Bounded<u16, 12> = v.cast();
+ /// assert_eq!(u16_v.get(), 127);
+ ///
+ /// // This won't build: a `u8` is smaller than the required 12 bits.
+ /// // let _: Bounded<u8, 12> = v.cast();
+ /// ```
+ pub fn cast<U>(self) -> Bounded<U, N>
+ where
+ U: TryFrom<T> + Integer,
+ T: Integer,
+ U: Integer<Signedness = T::Signedness>,
+ {
+ // SAFETY: the converted value is represented using `N` bits, `U` can contain `N` bits, and
+ // `U` and `T` have the same sign, hence this conversion cannot fail.
+ let value = unsafe { U::try_from(self.get()).unwrap_unchecked() };
+
+ // INVARIANT: although the backing type has changed, the value is still represented within
+ // `N` bits, and with the same signedness.
+ Bounded::__new(value)
+ }
+}
+
+impl<T, const N: u32> Deref for Bounded<T, N>
+where
+ T: Integer,
+{
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ // Enforce the invariant to inform the compiler of the bounds of the value.
+ if !fits_within(self.0, N) {
+ // SAFETY: Per the `Bounded` invariants, `fits_within` can never return `false` on the
+ // value of a valid instance
+ unsafe { core::hint::unreachable_unchecked() }
+ }
+
+ &self.0
+ }
+}
+
+/// Trait similar to [`TryInto`] but for [`Bounded`], to avoid conflicting implementations.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::num::{Bounded, TryIntoBounded};
+///
+/// // Succeeds because `128` fits into 8 bits.
+/// let v: Option<Bounded<u16, 8>> = 128u32.try_into_bitint();
+/// assert_eq!(v.as_deref().copied(), Some(128));
+///
+/// // Fails because `128` doesn't fits into 6 bits.
+/// let v: Option<Bounded<u16, 6>> = 128u32.try_into_bitint();
+/// assert_eq!(v, None);
+/// ```
+pub trait TryIntoBounded<T: Integer, const N: u32> {
+ /// Attempts to convert `self` into a [`Bounded`] using `N` bits.
+ ///
+ /// Returns `None` if `self` does not fit into the target type.
+ fn try_into_bitint(self) -> Option<Bounded<T, N>>;
+}
+
+/// Any integer value can be attempted to be converted into a [`Bounded`] of any size.
+impl<T, U, const N: u32> TryIntoBounded<T, N> for U
+where
+ T: Integer,
+ U: TryInto<T>,
+{
+ fn try_into_bitint(self) -> Option<Bounded<T, N>> {
+ self.try_into().ok().and_then(Bounded::try_new)
+ }
+}
+
+// Comparisons between `Bounded`s.
+
+impl<T, U, const N: u32, const M: u32> PartialEq<Bounded<U, M>> for Bounded<T, N>
+where
+ T: Integer,
+ U: Integer,
+ T: PartialEq<U>,
+{
+ fn eq(&self, other: &Bounded<U, M>) -> bool {
+ self.get() == other.get()
+ }
+}
+
+impl<T, const N: u32> Eq for Bounded<T, N> where T: Integer {}
+
+impl<T, U, const N: u32, const M: u32> PartialOrd<Bounded<U, M>> for Bounded<T, N>
+where
+ T: Integer,
+ U: Integer,
+ T: PartialOrd<U>,
+{
+ fn partial_cmp(&self, other: &Bounded<U, M>) -> Option<cmp::Ordering> {
+ self.get().partial_cmp(&other.get())
+ }
+}
+
+impl<T, const N: u32> Ord for Bounded<T, N>
+where
+ T: Integer,
+ T: Ord,
+{
+ fn cmp(&self, other: &Self) -> cmp::Ordering {
+ self.get().cmp(&other.get())
+ }
+}
+
+// Comparisons between a `Bounded` and its backing type.
+
+impl<T, const N: u32> PartialEq<T> for Bounded<T, N>
+where
+ T: Integer,
+ T: PartialEq,
+{
+ fn eq(&self, other: &T) -> bool {
+ self.get() == *other
+ }
+}
+
+impl<T, const N: u32> PartialOrd<T> for Bounded<T, N>
+where
+ T: Integer,
+ T: PartialOrd,
+{
+ fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
+ self.get().partial_cmp(other)
+ }
+}
+
+// Implementations of `core::ops` for two `Bounded` with the same backing type.
+
+impl<T, const N: u32, const M: u32> ops::Add<Bounded<T, M>> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Add<Output = T>,
+{
+ type Output = T;
+
+ fn add(self, rhs: Bounded<T, M>) -> Self::Output {
+ self.get() + rhs.get()
+ }
+}
+
+impl<T, const N: u32, const M: u32> ops::BitAnd<Bounded<T, M>> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::BitAnd<Output = T>,
+{
+ type Output = T;
+
+ fn bitand(self, rhs: Bounded<T, M>) -> Self::Output {
+ self.get() & rhs.get()
+ }
+}
+
+impl<T, const N: u32, const M: u32> ops::BitOr<Bounded<T, M>> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::BitOr<Output = T>,
+{
+ type Output = T;
+
+ fn bitor(self, rhs: Bounded<T, M>) -> Self::Output {
+ self.get() | rhs.get()
+ }
+}
+
+impl<T, const N: u32, const M: u32> ops::BitXor<Bounded<T, M>> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::BitXor<Output = T>,
+{
+ type Output = T;
+
+ fn bitxor(self, rhs: Bounded<T, M>) -> Self::Output {
+ self.get() ^ rhs.get()
+ }
+}
+
+impl<T, const N: u32, const M: u32> ops::Div<Bounded<T, M>> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Div<Output = T>,
+{
+ type Output = T;
+
+ fn div(self, rhs: Bounded<T, M>) -> Self::Output {
+ self.get() / rhs.get()
+ }
+}
+
+impl<T, const N: u32, const M: u32> ops::Mul<Bounded<T, M>> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Mul<Output = T>,
+{
+ type Output = T;
+
+ fn mul(self, rhs: Bounded<T, M>) -> Self::Output {
+ self.get() * rhs.get()
+ }
+}
+
+impl<T, const N: u32, const M: u32> ops::Rem<Bounded<T, M>> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Rem<Output = T>,
+{
+ type Output = T;
+
+ fn rem(self, rhs: Bounded<T, M>) -> Self::Output {
+ self.get() % rhs.get()
+ }
+}
+
+impl<T, const N: u32, const M: u32> ops::Sub<Bounded<T, M>> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Sub<Output = T>,
+{
+ type Output = T;
+
+ fn sub(self, rhs: Bounded<T, M>) -> Self::Output {
+ self.get() - rhs.get()
+ }
+}
+
+// Implementations of `core::ops` between a `Bounded` and its backing type.
+
+impl<T, const N: u32> ops::Add<T> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Add<Output = T>,
+{
+ type Output = T;
+
+ fn add(self, rhs: T) -> Self::Output {
+ self.get() + rhs
+ }
+}
+
+impl<T, const N: u32> ops::BitAnd<T> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::BitAnd<Output = T>,
+{
+ type Output = T;
+
+ fn bitand(self, rhs: T) -> Self::Output {
+ self.get() & rhs
+ }
+}
+
+impl<T, const N: u32> ops::BitOr<T> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::BitOr<Output = T>,
+{
+ type Output = T;
+
+ fn bitor(self, rhs: T) -> Self::Output {
+ self.get() | rhs
+ }
+}
+
+impl<T, const N: u32> ops::BitXor<T> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::BitXor<Output = T>,
+{
+ type Output = T;
+
+ fn bitxor(self, rhs: T) -> Self::Output {
+ self.get() ^ rhs
+ }
+}
+
+impl<T, const N: u32> ops::Div<T> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Div<Output = T>,
+{
+ type Output = T;
+
+ fn div(self, rhs: T) -> Self::Output {
+ self.get() / rhs
+ }
+}
+
+impl<T, const N: u32> ops::Mul<T> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Mul<Output = T>,
+{
+ type Output = T;
+
+ fn mul(self, rhs: T) -> Self::Output {
+ self.get() * rhs
+ }
+}
+
+impl<T, const N: u32> ops::Neg for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Neg<Output = T>,
+{
+ type Output = T;
+
+ fn neg(self) -> Self::Output {
+ -self.get()
+ }
+}
+
+impl<T, const N: u32> ops::Not for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Not<Output = T>,
+{
+ type Output = T;
+
+ fn not(self) -> Self::Output {
+ !self.get()
+ }
+}
+
+impl<T, const N: u32> ops::Rem<T> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Rem<Output = T>,
+{
+ type Output = T;
+
+ fn rem(self, rhs: T) -> Self::Output {
+ self.get() % rhs
+ }
+}
+
+impl<T, const N: u32> ops::Sub<T> for Bounded<T, N>
+where
+ T: Integer,
+ T: ops::Sub<Output = T>,
+{
+ type Output = T;
+
+ fn sub(self, rhs: T) -> Self::Output {
+ self.get() - rhs
+ }
+}
+
+// Proxy implementations of `core::fmt`.
+
+impl<T, const N: u32> fmt::Display for Bounded<T, N>
+where
+ T: Integer,
+ T: fmt::Display,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.get().fmt(f)
+ }
+}
+
+impl<T, const N: u32> fmt::Binary for Bounded<T, N>
+where
+ T: Integer,
+ T: fmt::Binary,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.get().fmt(f)
+ }
+}
+
+impl<T, const N: u32> fmt::LowerExp for Bounded<T, N>
+where
+ T: Integer,
+ T: fmt::LowerExp,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.get().fmt(f)
+ }
+}
+
+impl<T, const N: u32> fmt::LowerHex for Bounded<T, N>
+where
+ T: Integer,
+ T: fmt::LowerHex,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.get().fmt(f)
+ }
+}
+
+impl<T, const N: u32> fmt::Octal for Bounded<T, N>
+where
+ T: Integer,
+ T: fmt::Octal,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.get().fmt(f)
+ }
+}
+
+impl<T, const N: u32> fmt::UpperExp for Bounded<T, N>
+where
+ T: Integer,
+ T: fmt::UpperExp,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.get().fmt(f)
+ }
+}
+
+impl<T, const N: u32> fmt::UpperHex for Bounded<T, N>
+where
+ T: Integer,
+ T: fmt::UpperHex,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.get().fmt(f)
+ }
+}
+
+/// Implements `$trait` for all [`Bounded`] types represented using `$num_bits`.
+///
+/// This is used to declare size properties as traits that we can constrain against in impl blocks.
+macro_rules! impl_size_rule {
+ ($trait:ty, $($num_bits:literal)*) => {
+ $(
+ impl<T> $trait for Bounded<T, $num_bits> where T: Integer {}
+ )*
+ };
+}
+
+/// Local trait expressing the fact that a given [`Bounded`] has at least `N` bits used for value
+/// representation.
+trait AtLeastXBits<const N: usize> {}
+
+/// Implementations for infallibly converting a primitive type into a [`Bounded`] that can contain
+/// it.
+///
+/// Put into their own module for readability, and to avoid cluttering the rustdoc of the parent
+/// module.
+mod atleast_impls {
+ use super::*;
+
+ // Number of bits at least as large as 64.
+ impl_size_rule!(AtLeastXBits<64>, 64);
+
+ // Anything 64 bits or more is also larger than 32.
+ impl<T> AtLeastXBits<32> for T where T: AtLeastXBits<64> {}
+ // Other numbers of bits at least as large as 32.
+ impl_size_rule!(AtLeastXBits<32>,
+ 32 33 34 35 36 37 38 39
+ 40 41 42 43 44 45 46 47
+ 48 49 50 51 52 53 54 55
+ 56 57 58 59 60 61 62 63
+ );
+
+ // Anything 32 bits or more is also larger than 16.
+ impl<T> AtLeastXBits<16> for T where T: AtLeastXBits<32> {}
+ // Other numbers of bits at least as large as 16.
+ impl_size_rule!(AtLeastXBits<16>,
+ 16 17 18 19 20 21 22 23
+ 24 25 26 27 28 29 30 31
+ );
+
+ // Anything 16 bits or more is also larger than 8.
+ impl<T> AtLeastXBits<8> for T where T: AtLeastXBits<16> {}
+ // Other numbers of bits at least as large as 8.
+ impl_size_rule!(AtLeastXBits<8>, 8 9 10 11 12 13 14 15);
+}
+
+/// Generates `From` implementations from a primitive type into a [`Bounded`] with
+/// enough bits to store any value of that type.
+///
+/// Note: The only reason for having this macro is that if we pass `$type` as a generic
+/// parameter, we cannot use it in the const context of [`AtLeastXBits`]'s generic parameter. This
+/// can be fixed once the `generic_const_exprs` feature is usable, and this macro replaced by a
+/// regular `impl` block.
+macro_rules! impl_from_primitive {
+ ($($type:ty)*) => {
+ $(
+ #[doc = ::core::concat!(
+ "Conversion from a [`",
+ ::core::stringify!($type),
+ "`] into a [`Bounded`] of same signedness with enough bits to store it.")]
+ impl<T, const N: u32> From<$type> for Bounded<T, N>
+ where
+ $type: Integer,
+ T: Integer<Signedness = <$type as Integer>::Signedness> + From<$type>,
+ Self: AtLeastXBits<{ <$type as Integer>::BITS as usize }>,
+ {
+ fn from(value: $type) -> Self {
+ // INVARIANT: The trait bound on `Self` guarantees that `N` bits is
+ // enough to hold any value of the source type.
+ Self::__new(T::from(value))
+ }
+ }
+ )*
+ }
+}
+
+impl_from_primitive!(
+ u8 u16 u32 u64 usize
+ i8 i16 i32 i64 isize
+);
+
+/// Local trait expressing the fact that a given [`Bounded`] fits into a primitive type of `N` bits,
+/// provided they have the same signedness.
+trait FitsInXBits<const N: usize> {}
+
+/// Implementations for infallibly converting a [`Bounded`] into a primitive type that can contain
+/// it.
+///
+/// Put into their own module for readability, and to avoid cluttering the rustdoc of the parent
+/// module.
+mod fits_impls {
+ use super::*;
+
+ // Number of bits that fit into a 8-bits primitive.
+ impl_size_rule!(FitsInXBits<8>, 1 2 3 4 5 6 7 8);
+
+ // Anything that fits into 8 bits also fits into 16.
+ impl<T> FitsInXBits<16> for T where T: FitsInXBits<8> {}
+ // Other number of bits that fit into a 16-bits primitive.
+ impl_size_rule!(FitsInXBits<16>, 9 10 11 12 13 14 15 16);
+
+ // Anything that fits into 16 bits also fits into 32.
+ impl<T> FitsInXBits<32> for T where T: FitsInXBits<16> {}
+ // Other number of bits that fit into a 32-bits primitive.
+ impl_size_rule!(FitsInXBits<32>,
+ 17 18 19 20 21 22 23 24
+ 25 26 27 28 29 30 31 32
+ );
+
+ // Anything that fits into 32 bits also fits into 64.
+ impl<T> FitsInXBits<64> for T where T: FitsInXBits<32> {}
+ // Other number of bits that fit into a 64-bits primitive.
+ impl_size_rule!(FitsInXBits<64>,
+ 33 34 35 36 37 38 39 40
+ 41 42 43 44 45 46 47 48
+ 49 50 51 52 53 54 55 56
+ 57 58 59 60 61 62 63 64
+ );
+}
+
+/// Generates [`From`] implementations from a [`Bounded`] into a primitive type that is
+/// guaranteed to contain it.
+///
+/// Note: The only reason for having this macro is that if we pass `$type` as a generic
+/// parameter, we cannot use it in the const context of `AtLeastXBits`'s generic parameter. This
+/// can be fixed once the `generic_const_exprs` feature is usable, and this macro replaced by a
+/// regular `impl` block.
+macro_rules! impl_into_primitive {
+ ($($type:ty)*) => {
+ $(
+ #[doc = ::core::concat!(
+ "Conversion from a [`Bounded`] with no more bits than a [`",
+ ::core::stringify!($type),
+ "`] and of same signedness into [`",
+ ::core::stringify!($type),
+ "`]")]
+ impl<T, const N: u32> From<Bounded<T, N>> for $type
+ where
+ $type: Integer + TryFrom<T>,
+ T: Integer<Signedness = <$type as Integer>::Signedness>,
+ Bounded<T, N>: FitsInXBits<{ <$type as Integer>::BITS as usize }>,
+ {
+ fn from(value: Bounded<T, N>) -> $type {
+ // SAFETY: The trait bound on `Bounded` ensures that any value it holds (which
+ // is constrained to `N` bits) can fit into the destination type, so this
+ // conversion cannot fail.
+ unsafe { <$type>::try_from(value.get()).unwrap_unchecked() }
+ }
+ }
+ )*
+ }
+}
+
+impl_into_primitive!(
+ u8 u16 u32 u64 usize
+ i8 i16 i32 i64 isize
+);
+
+// Single-bit `Bounded`s can be converted from/to a boolean.
+
+impl<T> From<Bounded<T, 1>> for bool
+where
+ T: Integer + Zeroable,
+{
+ fn from(value: Bounded<T, 1>) -> Self {
+ value.get() != Zeroable::zeroed()
+ }
+}
+
+impl<T, const N: u32> From<bool> for Bounded<T, N>
+where
+ T: Integer + From<bool>,
+{
+ fn from(value: bool) -> Self {
+ // INVARIANT: a boolean can be represented using a single bit, and thus fits within any
+ // integer type for any `N` > 0.
+ Self::__new(T::from(value))
+ }
+}
--
2.51.2
^ permalink raw reply related [flat|nested] 9+ messages in thread* Re: [PATCH v3 2/4] rust: num: add Bounded integer wrapping type
2025-11-06 7:07 ` [PATCH v3 2/4] rust: num: add Bounded integer wrapping type Alexandre Courbot
@ 2025-11-06 9:53 ` Alice Ryhl
2025-11-06 11:45 ` Alexandre Courbot
0 siblings, 1 reply; 9+ messages in thread
From: Alice Ryhl @ 2025-11-06 9:53 UTC (permalink / raw)
To: Alexandre Courbot
Cc: Danilo Krummrich, Miguel Ojeda, Joel Fernandes, Yury Norov,
Jesung Yang, Boqun Feng, Gary Guo, Björn Roy Baron,
Benno Lossin, Andreas Hindborg, Trevor Gross, linux-kernel,
rust-for-linux
On Thu, Nov 06, 2025 at 04:07:14PM +0900, Alexandre Courbot wrote:
> 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.
>
> Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
> ---
> rust/kernel/num.rs | 3 +
> rust/kernel/num/bounded.rs | 1045 ++++++++++++++++++++++++++++++++++++++++++++
> 2 files changed, 1048 insertions(+)
>
> diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs
> index 3f85e50b8632..bc9abcc3a317 100644
> --- a/rust/kernel/num.rs
> +++ b/rust/kernel/num.rs
> @@ -4,6 +4,9 @@
>
> use core::ops;
>
> +pub mod bounded;
> +pub use bounded::*;
> +
> /// Designates unsigned primitive types.
> pub struct Unsigned(());
>
> diff --git a/rust/kernel/num/bounded.rs b/rust/kernel/num/bounded.rs
> new file mode 100644
> index 000000000000..2e4bc4ce9af5
> --- /dev/null
> +++ b/rust/kernel/num/bounded.rs
> @@ -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`.
> +///
> +/// 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
^ permalink raw reply [flat|nested] 9+ messages in thread* Re: [PATCH v3 2/4] rust: num: add Bounded integer wrapping type
2025-11-06 9:53 ` Alice Ryhl
@ 2025-11-06 11:45 ` Alexandre Courbot
0 siblings, 0 replies; 9+ messages in thread
From: Alexandre Courbot @ 2025-11-06 11:45 UTC (permalink / raw)
To: Alice Ryhl, Alexandre Courbot
Cc: Danilo Krummrich, Miguel Ojeda, Joel Fernandes, Yury Norov,
Jesung Yang, Boqun Feng, Gary Guo, Björn Roy Baron,
Benno Lossin, Andreas Hindborg, Trevor Gross, linux-kernel,
rust-for-linux
On Thu Nov 6, 2025 at 6:53 PM JST, Alice Ryhl wrote:
> On Thu, Nov 06, 2025 at 04:07:14PM +0900, Alexandre Courbot wrote:
>> 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.
>>
>> Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
>> ---
>> rust/kernel/num.rs | 3 +
>> rust/kernel/num/bounded.rs | 1045 ++++++++++++++++++++++++++++++++++++++++++++
>> 2 files changed, 1048 insertions(+)
>>
>> diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs
>> index 3f85e50b8632..bc9abcc3a317 100644
>> --- a/rust/kernel/num.rs
>> +++ b/rust/kernel/num.rs
>> @@ -4,6 +4,9 @@
>>
>> use core::ops;
>>
>> +pub mod bounded;
>> +pub use bounded::*;
>> +
>> /// Designates unsigned primitive types.
>> pub struct Unsigned(());
>>
>> diff --git a/rust/kernel/num/bounded.rs b/rust/kernel/num/bounded.rs
>> new file mode 100644
>> index 000000000000..2e4bc4ce9af5
>> --- /dev/null
>> +++ b/rust/kernel/num/bounded.rs
>> @@ -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`.
>> +///
>> +/// 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?
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.
^ permalink raw reply [flat|nested] 9+ messages in thread
* [PATCH v3 3/4] MAINTAINERS: add entry for the Rust `num` module
2025-11-06 7:07 [PATCH v3 0/4] rust: add Bounded integer type Alexandre Courbot
2025-11-06 7:07 ` [PATCH v3 1/4] rust: add num module and Integer trait Alexandre Courbot
2025-11-06 7:07 ` [PATCH v3 2/4] rust: num: add Bounded integer wrapping type Alexandre Courbot
@ 2025-11-06 7:07 ` Alexandre Courbot
2025-11-06 7:07 ` [PATCH FOR REFERENCE v3 4/4] gpu: nova-core: use BitInt for bitfields Alexandre Courbot
3 siblings, 0 replies; 9+ messages in thread
From: Alexandre Courbot @ 2025-11-06 7:07 UTC (permalink / raw)
To: Alice Ryhl, Danilo Krummrich, Miguel Ojeda, Joel Fernandes,
Yury Norov, Jesung Yang, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross
Cc: linux-kernel, rust-for-linux, Alexandre Courbot
This new module provides numerical features useful for the kernel, such
as the `Integer` trait and the `Bounded` integer wrapper.
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
---
MAINTAINERS | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/MAINTAINERS b/MAINTAINERS
index 952aed4619c2..b6294a2903c1 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -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 <acourbot@nvidia.com>
+R: Yury Norov <yury.norov@gmail.com>
+L: rust-for-linux@vger.kernel.org
+S: Maintained
+F: rust/kernel/num.rs
+F: rust/kernel/num/
+
RUST [PIN-INIT]
M: Benno Lossin <lossin@kernel.org>
L: rust-for-linux@vger.kernel.org
--
2.51.2
^ permalink raw reply related [flat|nested] 9+ messages in thread
* [PATCH FOR REFERENCE v3 4/4] gpu: nova-core: use BitInt for bitfields
2025-11-06 7:07 [PATCH v3 0/4] rust: add Bounded integer type Alexandre Courbot
` (2 preceding siblings ...)
2025-11-06 7:07 ` [PATCH v3 3/4] MAINTAINERS: add entry for the Rust `num` module Alexandre Courbot
@ 2025-11-06 7:07 ` Alexandre Courbot
3 siblings, 0 replies; 9+ messages in thread
From: Alexandre Courbot @ 2025-11-06 7:07 UTC (permalink / raw)
To: Alice Ryhl, Danilo Krummrich, Miguel Ojeda, Joel Fernandes,
Yury Norov, Jesung Yang, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross
Cc: linux-kernel, rust-for-linux, 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/cover.1755235180.git.y.j3ms.n@gmail.com/
[2]
https://lore.kernel.org/rust-for-linux/20251003154748.1687160-1-joelagnelf@nvidia.com/
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
---
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(-)
diff --git a/drivers/gpu/nova-core/bitfield.rs b/drivers/gpu/nova-core/bitfield.rs
index 16e143658c51..be4d54feb38c 100644
--- a/drivers/gpu/nova-core/bitfield.rs
+++ b/drivers/gpu/nova-core/bitfield.rs
@@ -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>]());
)*
);
diff --git a/drivers/gpu/nova-core/falcon.rs b/drivers/gpu/nova-core/falcon.rs
index fb3561cc9746..ef288f5ee0c9 100644
--- a/drivers/gpu/nova-core/falcon.rs
+++ b/drivers/gpu/nova-core/falcon.rs
@@ -7,6 +7,7 @@
use kernel::device;
use kernel::dma::DmaAddress;
use kernel::io::poll::read_poll_timeout;
+use kernel::num::{self, Bounded};
use kernel::prelude::*;
use kernel::sync::aref::ARef;
use kernel::time::delay::fsleep;
@@ -23,11 +24,14 @@
pub(crate) mod sec2;
// TODO[FPRI]: Replace with `ToPrimitive`.
-macro_rules! impl_from_enum_to_u8 {
- ($enum_type:ty) => {
- impl From<$enum_type> for u8 {
+macro_rules! impl_from_enum_to_bounded {
+ ($enum_type:ty, $length:literal) => {
+ impl<T> From<$enum_type> for Bounded<T, $length>
+ where
+ T: From<u8> + num::Integer,
+ {
fn from(value: $enum_type) -> Self {
- value as u8
+ Bounded::from_expr(T::from(value as u8))
}
}
};
@@ -47,16 +51,20 @@ pub(crate) enum FalconCoreRev {
Rev6 = 6,
Rev7 = 7,
}
-impl_from_enum_to_u8!(FalconCoreRev);
+impl_from_enum_to_bounded!(FalconCoreRev, 4);
// TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for FalconCoreRev {
+impl<T> TryFrom<Bounded<T, 4>> for FalconCoreRev
+where
+ T: num::Integer,
+ u8: From<Bounded<T, 4>>,
+{
type Error = Error;
- fn try_from(value: u8) -> Result<Self> {
+ fn try_from(value: Bounded<T, 4>) -> Result<Self> {
use FalconCoreRev::*;
- let rev = match value {
+ let rev = match u8::from(value) {
1 => Rev1,
2 => Rev2,
3 => Rev3,
@@ -82,24 +90,26 @@ pub(crate) enum FalconCoreRevSubversion {
Subversion2 = 2,
Subversion3 = 3,
}
-impl_from_enum_to_u8!(FalconCoreRevSubversion);
+impl_from_enum_to_bounded!(FalconCoreRevSubversion, 2);
// TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for FalconCoreRevSubversion {
- type Error = Error;
-
- fn try_from(value: u8) -> Result<Self> {
+impl<T> From<Bounded<T, 2>> for FalconCoreRevSubversion
+where
+ T: num::Integer,
+ u8: From<Bounded<T, 2>>,
+{
+ fn from(value: Bounded<T, 2>) -> Self {
use FalconCoreRevSubversion::*;
- let sub_version = match value & 0b11 {
+ match u8::from(value) {
0 => Subversion0,
1 => Subversion1,
2 => Subversion2,
3 => Subversion3,
- _ => return Err(EINVAL),
- };
-
- Ok(sub_version)
+ // SAFETY: `value` comes from a 2-bit `Bounded`, and we just checked all possible
+ // values.
+ _ => unsafe { core::hint::unreachable_unchecked() },
+ }
}
}
@@ -126,16 +136,20 @@ pub(crate) enum FalconSecurityModel {
/// Also known as High-Secure, Privilege Level 3 or PL3.
Heavy = 3,
}
-impl_from_enum_to_u8!(FalconSecurityModel);
+impl_from_enum_to_bounded!(FalconSecurityModel, 2);
// TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for FalconSecurityModel {
+impl<T> TryFrom<Bounded<T, 2>> for FalconSecurityModel
+where
+ T: num::Integer,
+ u8: From<Bounded<T, 2>>,
+{
type Error = Error;
- fn try_from(value: u8) -> Result<Self> {
+ fn try_from(value: Bounded<T, 2>) -> Result<Self> {
use FalconSecurityModel::*;
- let sec_model = match value {
+ let sec_model = match u8::from(value) {
0 => None,
2 => Light,
3 => Heavy,
@@ -158,14 +172,18 @@ pub(crate) enum FalconModSelAlgo {
#[default]
Rsa3k = 1,
}
-impl_from_enum_to_u8!(FalconModSelAlgo);
+impl_from_enum_to_bounded!(FalconModSelAlgo, 8);
// TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for FalconModSelAlgo {
+impl<T> TryFrom<Bounded<T, 8>> for FalconModSelAlgo
+where
+ T: num::Integer,
+ u8: From<Bounded<T, 8>>,
+{
type Error = Error;
- fn try_from(value: u8) -> Result<Self> {
- match value {
+ fn try_from(value: Bounded<T, 8>) -> Result<Self> {
+ match u8::from(value) {
1 => Ok(FalconModSelAlgo::Rsa3k),
_ => Err(EINVAL),
}
@@ -180,14 +198,18 @@ pub(crate) enum DmaTrfCmdSize {
#[default]
Size256B = 0x6,
}
-impl_from_enum_to_u8!(DmaTrfCmdSize);
+impl_from_enum_to_bounded!(DmaTrfCmdSize, 3);
// TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for DmaTrfCmdSize {
+impl<T> TryFrom<Bounded<T, 3>> for DmaTrfCmdSize
+where
+ T: num::Integer,
+ u8: From<Bounded<T, 3>>,
+{
type Error = Error;
- fn try_from(value: u8) -> Result<Self> {
- match value {
+ fn try_from(value: Bounded<T, 3>) -> Result<Self> {
+ match u8::from(value) {
0x6 => Ok(Self::Size256B),
_ => Err(EINVAL),
}
@@ -203,25 +225,20 @@ pub(crate) enum PeregrineCoreSelect {
/// RISC-V core is active.
Riscv = 1,
}
+impl_from_enum_to_bounded!(PeregrineCoreSelect, 1);
-impl From<bool> for PeregrineCoreSelect {
- fn from(value: bool) -> Self {
- match value {
+impl<T> From<Bounded<T, 1>> for PeregrineCoreSelect
+where
+ T: num::Integer + Zeroable,
+{
+ fn from(value: Bounded<T, 1>) -> Self {
+ match bool::from(value) {
false => PeregrineCoreSelect::Falcon,
true => PeregrineCoreSelect::Riscv,
}
}
}
-impl From<PeregrineCoreSelect> for bool {
- fn from(value: PeregrineCoreSelect) -> Self {
- match value {
- PeregrineCoreSelect::Falcon => false,
- PeregrineCoreSelect::Riscv => true,
- }
- }
-}
-
/// Different types of memory present in a falcon core.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FalconMem {
@@ -245,14 +262,18 @@ pub(crate) enum FalconFbifTarget {
/// Non-coherent system memory (System DRAM).
NoncoherentSysmem = 2,
}
-impl_from_enum_to_u8!(FalconFbifTarget);
+impl_from_enum_to_bounded!(FalconFbifTarget, 2);
// TODO[FPRI]: replace with `FromPrimitive`.
-impl TryFrom<u8> for FalconFbifTarget {
+impl<T> TryFrom<Bounded<T, 2>> for FalconFbifTarget
+where
+ T: num::Integer,
+ u8: From<Bounded<T, 2>>,
+{
type Error = Error;
- fn try_from(value: u8) -> Result<Self> {
- let res = match value {
+ fn try_from(value: Bounded<T, 2>) -> Result<Self> {
+ let res = match u8::from(value) {
0 => Self::LocalFb,
1 => Self::CoherentSysmem,
2 => Self::NoncoherentSysmem,
@@ -272,26 +293,21 @@ pub(crate) enum FalconFbifMemType {
/// Physical memory addresses.
Physical = 1,
}
+impl_from_enum_to_bounded!(FalconFbifMemType, 1);
/// Conversion from a single-bit register field.
-impl From<bool> for FalconFbifMemType {
- fn from(value: bool) -> Self {
- match value {
+impl<T> From<Bounded<T, 1>> for FalconFbifMemType
+where
+ T: num::Integer + Zeroable,
+{
+ fn from(value: Bounded<T, 1>) -> Self {
+ match bool::from(value) {
false => Self::Virtual,
true => Self::Physical,
}
}
}
-impl From<FalconFbifMemType> for bool {
- fn from(value: FalconFbifMemType) -> Self {
- match value {
- FalconFbifMemType::Virtual => false,
- FalconFbifMemType::Physical => true,
- }
- }
-}
-
/// Type used to represent the `PFALCON` registers address base for a given falcon engine.
pub(crate) struct PFalconBase(());
@@ -414,7 +430,7 @@ pub(crate) fn reset(&self, bar: &Bar0) -> Result {
self.reset_wait_mem_scrubbing(bar)?;
regs::NV_PFALCON_FALCON_RM::default()
- .set_value(regs::NV_PMC_BOOT_0::read(bar).into())
+ .set_value(u32::from(regs::NV_PMC_BOOT_0::read(bar)))
.write(bar, &E::ID);
Ok(())
@@ -481,18 +497,18 @@ fn dma_wr<F: FalconFirmware<Target = E>>(
.set_base((dma_start >> 8) as u32)
.write(bar, &E::ID);
regs::NV_PFALCON_FALCON_DMATRFBASE1::default()
- .set_base((dma_start >> 40) as u16)
+ .try_set_base(dma_start >> 40)?
.write(bar, &E::ID);
let cmd = regs::NV_PFALCON_FALCON_DMATRFCMD::default()
.set_size(DmaTrfCmdSize::Size256B)
.set_imem(target_mem == FalconMem::Imem)
- .set_sec(if sec { 1 } else { 0 });
+ .set_sec(sec);
for pos in (0..num_transfers).map(|i| i * DMA_LEN) {
// Perform a transfer of size `DMA_LEN`.
regs::NV_PFALCON_FALCON_DMATRFMOFFS::default()
- .set_offs(load_offsets.dst_start + pos)
+ .try_set_offs(load_offsets.dst_start + pos)?
.write(bar, &E::ID);
regs::NV_PFALCON_FALCON_DMATRFFBOFFS::default()
.set_offs(src_start + pos)
diff --git a/drivers/gpu/nova-core/falcon/hal/ga102.rs b/drivers/gpu/nova-core/falcon/hal/ga102.rs
index afed353b24d2..c43e48823eff 100644
--- a/drivers/gpu/nova-core/falcon/hal/ga102.rs
+++ b/drivers/gpu/nova-core/falcon/hal/ga102.rs
@@ -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())
diff --git a/drivers/gpu/nova-core/fb/hal/ga100.rs b/drivers/gpu/nova-core/fb/hal/ga100.rs
index 871c42bf033a..8da754d84153 100644
--- a/drivers/gpu/nova-core/fb/hal/ga100.rs
+++ b/drivers/gpu/nova-core/fb/hal/ga100.rs
@@ -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)
diff --git a/drivers/gpu/nova-core/gpu.rs b/drivers/gpu/nova-core/gpu.rs
index 9d182bffe8b4..119bfb197a1e 100644
--- a/drivers/gpu/nova-core/gpu.rs
+++ b/drivers/gpu/nova-core/gpu.rs
@@ -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(),
}
}
}
diff --git a/drivers/gpu/nova-core/regs.rs b/drivers/gpu/nova-core/regs.rs
index 206dab2e1335..1542d72e4a65 100644
--- a/drivers/gpu/nova-core/regs.rs
+++ b/drivers/gpu/nova-core/regs.rs
@@ -17,18 +17,19 @@
// PMC
register!(NV_PMC_BOOT_0 @ 0x00000000, "Basic revision information about the GPU" {
- 3:0 minor_revision as u8, "Minor revision of the chip";
- 7:4 major_revision as u8, "Major revision of the chip";
- 8:8 architecture_1 as u8, "MSB of the architecture";
- 23:20 implementation as u8, "Implementation version of the architecture";
- 28:24 architecture_0 as u8, "Lower bits of the architecture";
+ 3:0 minor_revision, "Minor revision of the chip";
+ 7:4 major_revision, "Major revision of the chip";
+ 8:8 architecture_1, "MSB of the architecture";
+ 23:20 implementation, "Implementation version of the architecture";
+ 28:24 architecture_0, "Lower bits of the architecture";
});
impl NV_PMC_BOOT_0 {
/// Combines `architecture_0` and `architecture_1` to obtain the architecture of the chip.
pub(crate) fn architecture(self) -> Result<Architecture> {
Architecture::try_from(
- self.architecture_0() | (self.architecture_1() << Self::ARCHITECTURE_0_RANGE.len()),
+ u8::from(self.architecture_0())
+ | (u8::from(self.architecture_1()) << Self::ARCHITECTURE_0_RANGE.len()),
)
}
@@ -49,7 +50,7 @@ pub(crate) fn chipset(self) -> Result<Chipset> {
register!(NV_PBUS_SW_SCRATCH_0E_FRTS_ERR => NV_PBUS_SW_SCRATCH[0xe],
"scratch register 0xe used as FRTS firmware error code" {
- 31:16 frts_err_code as u16;
+ 31:16 frts_err_code;
});
// PFB
@@ -58,17 +59,17 @@ pub(crate) fn chipset(self) -> Result<Chipset> {
// GPU to perform sysmembar operations (see `fb::SysmemFlush`).
register!(NV_PFB_NISO_FLUSH_SYSMEM_ADDR @ 0x00100c10 {
- 31:0 adr_39_08 as u32;
+ 31:0 adr_39_08;
});
register!(NV_PFB_NISO_FLUSH_SYSMEM_ADDR_HI @ 0x00100c40 {
- 23:0 adr_63_40 as u32;
+ 23:0 adr_63_40;
});
register!(NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE @ 0x00100ce0 {
- 3:0 lower_scale as u8;
- 9:4 lower_mag as u8;
- 30:30 ecc_mode_enabled as bool;
+ 3:0 lower_scale;
+ 9:4 lower_mag;
+ 30:30 ecc_mode_enabled => bool;
});
impl NV_PFB_PRI_MMU_LOCAL_MEMORY_RANGE {
@@ -87,7 +88,7 @@ pub(crate) fn usable_fb_size(self) -> u64 {
}
register!(NV_PFB_PRI_MMU_WPR2_ADDR_LO@0x001fa824 {
- 31:4 lo_val as u32, "Bits 12..40 of the lower (inclusive) bound of the WPR2 region";
+ 31:4 lo_val, "Bits 12..40 of the lower (inclusive) bound of the WPR2 region";
});
impl NV_PFB_PRI_MMU_WPR2_ADDR_LO {
@@ -98,7 +99,7 @@ pub(crate) fn lower_bound(self) -> u64 {
}
register!(NV_PFB_PRI_MMU_WPR2_ADDR_HI@0x001fa828 {
- 31:4 hi_val as u32, "Bits 12..40 of the higher (exclusive) bound of the WPR2 region";
+ 31:4 hi_val, "Bits 12..40 of the higher (exclusive) bound of the WPR2 region";
});
impl NV_PFB_PRI_MMU_WPR2_ADDR_HI {
@@ -123,7 +124,7 @@ pub(crate) fn higher_bound(self) -> u64 {
// `PGC6_AON_SECURE_SCRATCH_GROUP_05` register (which it needs to read GFW_BOOT).
register!(NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_PRIV_LEVEL_MASK @ 0x00118128,
"Privilege level mask register" {
- 0:0 read_protection_level0 as bool, "Set after FWSEC lowers its protection level";
+ 0:0 read_protection_level0 => bool, "Set after FWSEC lowers its protection level";
});
// OpenRM defines this as a register array, but doesn't specify its size and only uses its first
@@ -133,7 +134,7 @@ pub(crate) fn higher_bound(self) -> u64 {
register!(
NV_PGC6_AON_SECURE_SCRATCH_GROUP_05_0_GFW_BOOT => NV_PGC6_AON_SECURE_SCRATCH_GROUP_05[0],
"Scratch group 05 register 0 used as GFW boot progress indicator" {
- 7:0 progress as u8, "Progress of GFW boot (0xff means completed)";
+ 7:0 progress, "Progress of GFW boot (0xff means completed)";
}
);
@@ -145,13 +146,13 @@ pub(crate) fn completed(self) -> bool {
}
register!(NV_PGC6_AON_SECURE_SCRATCH_GROUP_42 @ 0x001183a4 {
- 31:0 value as u32;
+ 31:0 value;
});
register!(
NV_USABLE_FB_SIZE_IN_MB => NV_PGC6_AON_SECURE_SCRATCH_GROUP_42,
"Scratch group 42 register used as framebuffer size" {
- 31:0 value as u32, "Usable framebuffer size, in megabytes";
+ 31:0 value, "Usable framebuffer size, in megabytes";
}
);
@@ -165,8 +166,8 @@ pub(crate) fn usable_fb_size(self) -> u64 {
// PDISP
register!(NV_PDISP_VGA_WORKSPACE_BASE @ 0x00625f04 {
- 3:3 status_valid as bool, "Set if the `addr` field is valid";
- 31:8 addr as u32, "VGA workspace base address divided by 0x10000";
+ 3:3 status_valid => bool, "Set if the `addr` field is valid";
+ 31:8 addr, "VGA workspace base address divided by 0x10000";
});
impl NV_PDISP_VGA_WORKSPACE_BASE {
@@ -185,40 +186,40 @@ pub(crate) fn vga_workspace_addr(self) -> Option<u64> {
pub(crate) const NV_FUSE_OPT_FPF_SIZE: usize = 16;
register!(NV_FUSE_OPT_FPF_NVDEC_UCODE1_VERSION @ 0x00824100[NV_FUSE_OPT_FPF_SIZE] {
- 15:0 data as u16;
+ 15:0 data;
});
register!(NV_FUSE_OPT_FPF_SEC2_UCODE1_VERSION @ 0x00824140[NV_FUSE_OPT_FPF_SIZE] {
- 15:0 data as u16;
+ 15:0 data;
});
register!(NV_FUSE_OPT_FPF_GSP_UCODE1_VERSION @ 0x008241c0[NV_FUSE_OPT_FPF_SIZE] {
- 15:0 data as u16;
+ 15:0 data;
});
// PFALCON
register!(NV_PFALCON_FALCON_IRQSCLR @ PFalconBase[0x00000004] {
- 4:4 halt as bool;
- 6:6 swgen0 as bool;
+ 4:4 halt => bool;
+ 6:6 swgen0 => bool;
});
register!(NV_PFALCON_FALCON_MAILBOX0 @ PFalconBase[0x00000040] {
- 31:0 value as u32;
+ 31:0 value => u32;
});
register!(NV_PFALCON_FALCON_MAILBOX1 @ PFalconBase[0x00000044] {
- 31:0 value as u32;
+ 31:0 value => u32;
});
register!(NV_PFALCON_FALCON_RM @ PFalconBase[0x00000084] {
- 31:0 value as u32;
+ 31:0 value => u32;
});
register!(NV_PFALCON_FALCON_HWCFG2 @ PFalconBase[0x000000f4] {
- 10:10 riscv as bool;
- 12:12 mem_scrubbing as bool, "Set to 0 after memory scrubbing is completed";
- 31:31 reset_ready as bool, "Signal indicating that reset is completed (GA102+)";
+ 10:10 riscv => bool;
+ 12:12 mem_scrubbing => bool, "Set to 0 after memory scrubbing is completed";
+ 31:31 reset_ready => bool, "Signal indicating that reset is completed (GA102+)";
});
impl NV_PFALCON_FALCON_HWCFG2 {
@@ -229,101 +230,101 @@ pub(crate) fn mem_scrubbing_done(self) -> bool {
}
register!(NV_PFALCON_FALCON_CPUCTL @ PFalconBase[0x00000100] {
- 1:1 startcpu as bool;
- 4:4 halted as bool;
- 6:6 alias_en as bool;
+ 1:1 startcpu => bool;
+ 4:4 halted => bool;
+ 6:6 alias_en => bool;
});
register!(NV_PFALCON_FALCON_BOOTVEC @ PFalconBase[0x00000104] {
- 31:0 value as u32;
+ 31:0 value => u32;
});
register!(NV_PFALCON_FALCON_DMACTL @ PFalconBase[0x0000010c] {
- 0:0 require_ctx as bool;
- 1:1 dmem_scrubbing as bool;
- 2:2 imem_scrubbing as bool;
- 6:3 dmaq_num as u8;
- 7:7 secure_stat as bool;
+ 0:0 require_ctx => bool;
+ 1:1 dmem_scrubbing => bool;
+ 2:2 imem_scrubbing => bool;
+ 6:3 dmaq_num;
+ 7:7 secure_stat => bool;
});
register!(NV_PFALCON_FALCON_DMATRFBASE @ PFalconBase[0x00000110] {
- 31:0 base as u32;
+ 31:0 base => u32;
});
register!(NV_PFALCON_FALCON_DMATRFMOFFS @ PFalconBase[0x00000114] {
- 23:0 offs as u32;
+ 23:0 offs;
});
register!(NV_PFALCON_FALCON_DMATRFCMD @ PFalconBase[0x00000118] {
- 0:0 full as bool;
- 1:1 idle as bool;
- 3:2 sec as u8;
- 4:4 imem as bool;
- 5:5 is_write as bool;
- 10:8 size as u8 ?=> DmaTrfCmdSize;
- 14:12 ctxdma as u8;
- 16:16 set_dmtag as u8;
+ 0:0 full => bool;
+ 1:1 idle => bool;
+ 3:2 sec;
+ 4:4 imem => bool;
+ 5:5 is_write => bool;
+ 10:8 size ?=> DmaTrfCmdSize;
+ 14:12 ctxdma;
+ 16:16 set_dmtag;
});
register!(NV_PFALCON_FALCON_DMATRFFBOFFS @ PFalconBase[0x0000011c] {
- 31:0 offs as u32;
+ 31:0 offs => u32;
});
register!(NV_PFALCON_FALCON_DMATRFBASE1 @ PFalconBase[0x00000128] {
- 8:0 base as u16;
+ 8:0 base;
});
register!(NV_PFALCON_FALCON_HWCFG1 @ PFalconBase[0x0000012c] {
- 3:0 core_rev as u8 ?=> FalconCoreRev, "Core revision";
- 5:4 security_model as u8 ?=> FalconSecurityModel, "Security model";
- 7:6 core_rev_subversion as u8 ?=> FalconCoreRevSubversion, "Core revision subversion";
+ 3:0 core_rev ?=> FalconCoreRev, "Core revision";
+ 5:4 security_model ?=> FalconSecurityModel, "Security model";
+ 7:6 core_rev_subversion => FalconCoreRevSubversion, "Core revision subversion";
});
register!(NV_PFALCON_FALCON_CPUCTL_ALIAS @ PFalconBase[0x00000130] {
- 1:1 startcpu as bool;
+ 1:1 startcpu => bool;
});
// Actually known as `NV_PSEC_FALCON_ENGINE` and `NV_PGSP_FALCON_ENGINE` depending on the falcon
// instance.
register!(NV_PFALCON_FALCON_ENGINE @ PFalconBase[0x000003c0] {
- 0:0 reset as bool;
+ 0:0 reset => bool;
});
register!(NV_PFALCON_FBIF_TRANSCFG @ PFalconBase[0x00000600[8]] {
- 1:0 target as u8 ?=> FalconFbifTarget;
- 2:2 mem_type as bool => FalconFbifMemType;
+ 1:0 target ?=> FalconFbifTarget;
+ 2:2 mem_type => FalconFbifMemType;
});
register!(NV_PFALCON_FBIF_CTL @ PFalconBase[0x00000624] {
- 7:7 allow_phys_no_ctx as bool;
+ 7:7 allow_phys_no_ctx => bool;
});
/* PFALCON2 */
register!(NV_PFALCON2_FALCON_MOD_SEL @ PFalcon2Base[0x00000180] {
- 7:0 algo as u8 ?=> FalconModSelAlgo;
+ 7:0 algo ?=> FalconModSelAlgo;
});
register!(NV_PFALCON2_FALCON_BROM_CURR_UCODE_ID @ PFalcon2Base[0x00000198] {
- 7:0 ucode_id as u8;
+ 7:0 ucode_id => u8;
});
register!(NV_PFALCON2_FALCON_BROM_ENGIDMASK @ PFalcon2Base[0x0000019c] {
- 31:0 value as u32;
+ 31:0 value => u32;
});
// OpenRM defines this as a register array, but doesn't specify its size and only uses its first
// element. Be conservative until we know the actual size or need to use more registers.
register!(NV_PFALCON2_FALCON_BROM_PARAADDR @ PFalcon2Base[0x00000210[1]] {
- 31:0 value as u32;
+ 31:0 value => u32;
});
// PRISCV
register!(NV_PRISCV_RISCV_BCR_CTRL @ PFalconBase[0x00001668] {
- 0:0 valid as bool;
- 4:4 core_select as bool => PeregrineCoreSelect;
- 8:8 br_fetch as bool;
+ 0:0 valid => bool;
+ 4:4 core_select => PeregrineCoreSelect;
+ 8:8 br_fetch => bool;
});
// The modules below provide registers that are not identical on all supported chips. They should
@@ -333,7 +334,7 @@ pub(crate) mod gm107 {
// FUSE
register!(NV_FUSE_STATUS_OPT_DISPLAY @ 0x00021c04 {
- 0:0 display_disabled as bool;
+ 0:0 display_disabled => bool;
});
}
@@ -341,6 +342,6 @@ pub(crate) mod ga100 {
// FUSE
register!(NV_FUSE_STATUS_OPT_DISPLAY @ 0x00820c04 {
- 0:0 display_disabled as bool;
+ 0:0 display_disabled => bool;
});
}
--
2.51.2
^ permalink raw reply related [flat|nested] 9+ messages in thread