Skip to contentSkip to conversation

rust: introduce cv! macro for safe const conversions of integer-like types

PATCH Superseded Eliot Courtney 5 participants 15 messages Sep 2 – Oct 2

Subsystems (6)

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v3 cover rust: introduce cv! macro for safe const conversions of integer-like types

This series introduces the cv! ("const value") macro for safe compile time conversions of integer-like types. The syntax is cv!(literal or expression), or cv!(literal or expression => type) when it needs some help with type inference. The result is that many expressions can be rewritten into a compile time safe (no as) and less visually busy style, for example:

```
- const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();
+ const DMA_LEN: u32 = cv!(MEM_BLOCK_ALIGNMENT);

- .with_const_msg_type::<{ casts::u8_as_u32(MSG_TYPE_VENDOR_PCI) }>()
+ .with_const_msg_type(cv!(MSG_TYPE_VENDOR_PCI))

- data: [[u8; GSP_PAGE_SIZE]; casts::u32_as_usize(MSGQ_NUM_PAGES)],
+ data: [[u8; GSP_PAGE_SIZE]; cv!(MSGQ_NUM_PAGES)],

-pub const NSEC_PER_SEC: i64 = bindings::NSEC_PER_SEC as i64;
+pub const NSEC_PER_SEC: i64 = cv!(bindings::NSEC_PER_SEC);

-//! let b = Bounded::<u16, 5>::new::<0x18>();
+//! let b: Bounded<u16, 5> = cv!(0x18);
```

This works by defining a trait FromConst<const V: i128> with an associated constant VALUE. Then each implementor sets VALUE to a constant expression. This works around not having const traits. An alternative idea from Gary defined a FromLiteral::from_literal<V> function [1]. This version essentially moves the implementation of that function to the const block of the associated constant (since it has to be executable at compile time anyway).

This is based on ideas from Gary Guo [1], Alice Ryhl [2], and Alexandre Courbot [3].

One (potential) limitation is that const generic types or values can't be used with cv!, because it requires the const generic expressions feature. The const_as! [3] macro did not have this limitation. This is worked around by special casing conversions to language integral types in the cv! macro (essentially subsuming const_as!). This special casing can be removed when const generic expressions can be used.

Some code is taken with permission from Alex's const_as! series.

The structure of this series is as follows:

1. cv! macro
2. updates to nova-core to use cv!

For a follow up series (I've already written this, but to avoid spamming a ton while we iterate on cv!, I'd send this after):

3. updates to various other code to use cv!
4. misc updates to other code to remove usages of as

We have multiple ways of converting - T::from(), FromSafeCast/IntoSafeCast, cv!, *_as_*. This series uses them in that order of priority, based on Alex's suggestion [4].

This is based on rust-next.

[1] https://lore.kernel.org/all/[email protected]/
[2] https://lore.kernel.org/all/CAH5fLgiGcOn+HQLj4w9yDc31V54PbqNUQv8cUFRoEuFzQrAAZA@mail.gmail.com/
[3] https://lore.kernel.org/all/[email protected]/
[4] https://lore.kernel.org/all/[email protected]/

---
Changes in v3:
- Add comment about not using FromConst trait directly (Gary)
- Lower case on const assert/panics (Gary)
- match instead of unwrap() for NonZero + message (Gary)
- Add reviewed-by tags (thanks Gary!)
- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- Improve error messages (Gary)
- Remove pre-req for Alex's nova-core num->kernel series.
- Link to v1: https://patch.msgid.link/[email protected]

---
Eliot Courtney (3):
rust: num: add cv! macro to create values from constant expressions
rust: prelude: add num::cv
gpu: nova-core: use cv! for constant casts

 drivers/gpu/nova-core/falcon.rs                    |   9 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   4 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   7 +-
 drivers/gpu/nova-core/fsp.rs                       |   3 +-
 drivers/gpu/nova-core/gsp/cmdq.rs                  |   6 +-
 drivers/gpu/nova-core/gsp/fw.rs                    |  38 +++---
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   2 +-
 drivers/gpu/nova-core/num.rs                       |  55 +--------
 rust/kernel/num.rs                                 | 137 +++++++++++++++++++++
 rust/kernel/num/bounded.rs                         |  19 +++
 rust/kernel/prelude.rs                             |   1 +
 rust/kernel/ptr.rs                                 |  14 +++
 12 files changed, 199 insertions(+), 96 deletions(-)

---
base-commit: cee9395acd8043be0644b25c34bfa86623f2b935
change-id: 20260828-cv-8d4e952fc14c

Best regards,

Signature · 1 line
Eliot Courtney <[email protected]>
#1 lore raw

PATCH v3 1/3 rust: num: add cv! macro to create values from constant expressions

Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait FromConst. The value is then converted and appears in the associated constant FromConst::VALUE. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax.
For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).

---
 rust/kernel/num.rs         | 138 +++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/num/bounded.rs |  19 +++++++
 rust/kernel/ptr.rs         |  14 +++++
 3 files changed, 171 insertions(+)
rust/kernel/num.rs +138 -0
index dbe848e30efe..9435459376a4 100644
@@ -2,6 +2,7 @@
 
 //! Additional numerical features for the kernel.
 
+use crate::const_assert;
 use core::ops;
 
 pub mod bounded;
@@ -9,6 +10,143 @@
 
 pub use bounded::*;
 
+/// Creates a value from an integer constant expression, with validity checked at build time.
+///
+/// This works for any type that implements [`FromConst`], with the target type inferred from
+/// the context, or named explicitly with `cv!(value => Type)`.
+///
+/// # Examples
+///
+/// ```
+/// use core::num::NonZero;
+/// use kernel::num::Bounded;
+/// use kernel::num::cv;
+/// use kernel::ptr::Alignment;
+///
+/// let v: NonZero<usize> = cv!(8);
+/// assert_eq!(v.get(), 8);
+///
+/// // Any integer constant expression works, not only literals.
+/// let m: NonZero<usize> = cv!(usize::MAX);
+/// assert_eq!(m.get(), usize::MAX);
+///
+/// let b: Bounded<u32, 4> = cv!(15);
+/// assert_eq!(b.get(), 15);
+///
+/// let a: Alignment = cv!(4096);
+/// assert_eq!(a.as_usize(), 4096);
+///
+/// // Checked narrowing of integer constants, including in `const` items.
+/// const SMALL: u8 = cv!(200u32);
+/// assert_eq!(SMALL, 200);
+///
+/// const N: NonZero<u8> = cv!(5);
+/// assert_eq!(N.get(), 5);
+///
+/// // The target type can be given explicitly.
+/// let e = cv!(200u32 => u8);
+/// assert_eq!(e, 200);
+///
+/// // With an explicit primitive target, the expression can use generic parameters.
+/// const fn as_u64<const KEY: u16>() -> u64 {
+///     cv!(KEY => u64)
+/// }
+/// assert_eq!(as_u64::<0x40>(), 0x40);
+/// ```
+#[macro_export]
+#[doc(hidden)]
+macro_rules! cv {
+    (@cast $v:expr => $t:ty) => {
+        const {
+            #[allow(unused_comparisons, unused_assignments, clippy::as_underscore)]
+            {
+                let v = $v;
+                let r = v as $t;
+                // Pin `back` to `v`'s type so `as _` casts back to the source type.
+                let mut back = v;
+                back = r as _;
+
+                ::core::assert!(
+                    back == v && (v < 0) == (r < 0),
+                    "value does not fit into the target type"
+                );
+
+                r
+            }
+        }
+    };
+    ($v:expr => u8) => { $crate::cv!(@cast $v => u8) };
+    ($v:expr => u16) => { $crate::cv!(@cast $v => u16) };
+    ($v:expr => u32) => { $crate::cv!(@cast $v => u32) };
+    ($v:expr => u64) => { $crate::cv!(@cast $v => u64) };
+    ($v:expr => u128) => { $crate::cv!(@cast $v => u128) };
+    ($v:expr => usize) => { $crate::cv!(@cast $v => usize) };
+    ($v:expr => i8) => { $crate::cv!(@cast $v => i8) };
+    ($v:expr => i16) => { $crate::cv!(@cast $v => i16) };
+    ($v:expr => i32) => { $crate::cv!(@cast $v => i32) };
+    ($v:expr => i64) => { $crate::cv!(@cast $v => i64) };
+    ($v:expr => i128) => { $crate::cv!(@cast $v => i128) };
+    ($v:expr => isize) => { $crate::cv!(@cast $v => isize) };
+    ($v:expr => $t:ty) => {
+        <$t as $crate::num::FromConst<{ $crate::cv!(@cast $v => i128) }>>::VALUE
+    };
+    ($v:expr) => {
+        <_ as $crate::num::FromConst<{ $crate::cv!(@cast $v => i128) }>>::VALUE
+    };
+}
+#[doc(inline)]
+pub use cv;
+
+/// Types that can be created from an integer constant expression validated at build time.
+///
+/// Implement this trait to make a type usable with [`cv!`]. Use the [`cv`] macro, not this trait
+/// directly, for creating values.
+#[diagnostic::on_unimplemented(message = "`{Self}` cannot be converted from a constant")]
+pub trait FromConst<const V: i128>: Sized {
+    /// The value that corresponds to the constant `V`.
+    ///
+    /// Fails the build if `V` is not a valid value for `Self`.
+    const VALUE: Self;
+}
+
+/// Implements [`FromConst`] for primitive integer types and their [`NonZero`](core::num::NonZero)
+/// versions.
+macro_rules! impl_from_const {
+    ($($type:ty)*) => {
+        $(
+        impl<const V: i128> FromConst<V> for $type {
+            const VALUE: Self = {
+                const_assert!(
+                    V >= <$type>::MIN as i128 && V <= <$type>::MAX as i128,
+                    "constant cannot be represented by the target type"
+                );
+
+                V as $type
+            };
+        }
+
+        impl<const V: i128> FromConst<V> for core::num::NonZero<$type> {
+            const VALUE: Self = {
+                const_assert!(
+                    V >= <$type>::MIN as i128 && V <= <$type>::MAX as i128,
+                    "constant cannot be represented by the underlying type"
+                );
+
+                match core::num::NonZero::new(V as $type) {
+                    Some(value) => value,
+                    None => panic!("constant cannot be zero"),
+                }
+            };
+        }
+        )*
+    };
+}
+
+impl_from_const!(
+    u8 u16 u32 u64 usize
+    i8 i16 i32 i64 isize
+);
+
 /// Designates unsigned primitive types.
 pub enum Unsigned {}
 
rust/kernel/num/bounded.rs +19 -0
index 2a2b0a4bca5e..f720eb44e7d3 100644
@@ -14,6 +14,7 @@
 
 use kernel::{
     num::{
+        FromConst,
         Integer,
         Unsigned, //
     },
@@ -272,6 +273,24 @@ pub const fn new<const VALUE: $type>() -> Self {
                 unsafe { Self::__new(VALUE) }
             }
         }
+
+        impl<const N: u32, const V: i128> FromConst<V> for Bounded<$type, N> {
+            const VALUE: Self = {
+                const_assert!(
+                    V >= <$type>::MIN as i128 && V <= <$type>::MAX as i128,
+                    "constant cannot be represented by the underlying type"
+                );
+                // Statically assert that `V` fits within the set number of bits.
+                const_assert!(
+                    fits_within!(V as $type, $type, N),
+                    "constant cannot be represented within the given number of bits"
+                );
+
+                // SAFETY: the asserts above confirmed that `V` can be represented within `N`
+                // bits.
+                unsafe { Self::__new(V as $type) }
+            };
+        }
         )*
     };
 }
rust/kernel/ptr.rs +14 -0
index 82acb531b17b..ac1662c3c8af 100644
@@ -166,6 +166,20 @@ pub const fn mask(self) -> usize {
     }
 }
 
+impl<const V: i128> crate::num::FromConst<V> for Alignment {
+    const VALUE: Self = {
+        const_assert!(
+            V > 0 && V <= usize::MAX as i128,
+            "constant cannot be represented as an Alignment"
+        );
+
+        match Alignment::new_checked(V as usize) {
+            Some(alignment) => alignment,
+            None => panic!("constant is not a power of two"),
+        }
+    };
+}
+
 /// Trait for items that can be aligned against an [`Alignment`].
 pub trait Alignable: Sized {
     /// Aligns `self` down to `alignment`.
Signature · 1 line
2.55.0
reviewer Reviewed-by on v3 1/3
#2 lore raw

Re: [PATCH v3 1/3] rust: num: add cv! macro to create values from constant expressions

Quoted 12 lines · Eliot Courtney

Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait FromConst. The value is then converted and appears in the associated constant FromConst::VALUE. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax.
For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).

Quoted 2 lines
Quoted 11 lines
---
 rust/kernel/num.rs         | 138 +++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/num/bounded.rs |  19 +++++++
 rust/kernel/ptr.rs         |  14 +++++
 3 files changed, 171 insertions(+)
rust/kernel/num.rs +0 -0
index dbe848e30efe..9435459376a4 100644

rust/kernel/num.rs line 6

Quoted 5 lines
rust/kernel/num.rs +1 -0
@@ -2,6 +2,7 @@
 
 //! Additional numerical features for the kernel.
 
+use crate::const_assert;
 use core::ops;

nit: commonly Rust code uses core/std -> dependency -> crate/super import order (known as std/extern/crate order), so this would be

    use core::ops;

    use crate::const_assert;

under that order. But I don't think we require that (so no need to resend).

Best,
Gary

#3 lore raw

Re: [PATCH v3 1/3] rust: num: add cv! macro to create values from constant expressions

In reply to Eliot Courtney
Quoted 12 lines · Eliot Courtney

Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait FromConst. The value is then converted and appears in the associated constant FromConst::VALUE. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax.
For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).

Quoted 2 lines

I don't think we have any user but nova-core at the moment, and it benefits from this in several series (patch 3 here, but also ID pool and later r000). Miguel, is this ok if we take it (i.e. the next revision) through drm-rust-next?

Some nits below.

Quoted 19 lines
---
 rust/kernel/num.rs         | 138 +++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/num/bounded.rs |  19 +++++++
 rust/kernel/ptr.rs         |  14 +++++
 3 files changed, 171 insertions(+)
rust/kernel/num.rs +1 -0
index dbe848e30efe..9435459376a4 100644
@@ -2,6 +2,7 @@
 
 //! Additional numerical features for the kernel.
 
+use crate::const_assert;
 use core::ops;
 
 pub mod bounded;

rust/kernel/num.rs line 11

Quoted 2 lines
rust/kernel/num.rs +0 -0
@@ -9,6 +10,143 @@
 
 pub use bounded::*;

Can we move the new code at the bottom of the file? I'd like to keep the Integer definition on top.

rust/kernel/num.rs line 15

Quoted 4 lines
rust/kernel/num.rs +3 -0
+/// Creates a value from an integer constant expression, with validity checked at build time.
+///
+/// This works for any type that implements [`FromConst`], with the target type inferred from

I am wondering about FromConst, do we want to make it public, or hide (and possibly seal) it?

Basically as it is anyone can implement a new type that works with cv!. If that's by design, then good, and I don't see any potential issue with that, but IIUC we also agree that this is a temporary workaround so we might not want to allow extensibility if it isn't future-proof.

If we decide to make FromConst more discreet without sealing it (which sounds like a good middle ground to me), then we should remove mentions of it from the public docs and mark it as #[doc(hidden)].

Quoted 29 lines
rust/kernel/num.rs +29 -0
+/// the context, or named explicitly with `cv!(value => Type)`.
+///
+/// # Examples
+///
+/// ```
+/// use core::num::NonZero;
+/// use kernel::num::Bounded;
+/// use kernel::num::cv;
+/// use kernel::ptr::Alignment;
+///
+/// let v: NonZero<usize> = cv!(8);
+/// assert_eq!(v.get(), 8);
+///
+/// // Any integer constant expression works, not only literals.
+/// let m: NonZero<usize> = cv!(usize::MAX);
+/// assert_eq!(m.get(), usize::MAX);
+///
+/// let b: Bounded<u32, 4> = cv!(15);
+/// assert_eq!(b.get(), 15);
+///
+/// let a: Alignment = cv!(4096);
+/// assert_eq!(a.as_usize(), 4096);
+///
+/// // Checked narrowing of integer constants, including in `const` items.
+/// const SMALL: u8 = cv!(200u32);
+/// assert_eq!(SMALL, 200);
+///
+/// const N: NonZero<u8> = cv!(5);
+/// assert_eq!(N.get(), 5);

rust/kernel/num.rs line 54

Quoted 10 lines
rust/kernel/num.rs +10 -0
+///
+/// // The target type can be given explicitly.
+/// let e = cv!(200u32 => u8);
+/// assert_eq!(e, 200);
+///
+/// // With an explicit primitive target, the expression can use generic parameters.
+/// const fn as_u64<const KEY: u16>() -> u64 {
+///     cv!(KEY => u64)
+/// }
+/// assert_eq!(as_u64::<0x40>(), 0x40);

These examples are excellent.

rust/kernel/num.rs line 61

Quoted 7 lines
rust/kernel/num.rs +7 -0
+/// ```
+#[macro_export]
+#[doc(hidden)]
+macro_rules! cv {
+    (@cast $v:expr => $t:ty) => {
+        const {
+            #[allow(unused_comparisons, unused_assignments, clippy::as_underscore)]

You may want to add clippy::unnecessary_cast, in case one does cv!(v => u32) where v is already a u32 (which would happen in macro or generic code).

Quoted 24 lines
rust/kernel/num.rs +24 -0
+            {
+                let v = $v;
+                let r = v as $t;
+                // Pin `back` to `v`'s type so `as _` casts back to the source type.
+                let mut back = v;
+                back = r as _;
+
+                ::core::assert!(
+                    back == v && (v < 0) == (r < 0),
+                    "value does not fit into the target type"
+                );
+
+                r
+            }
+        }
+    };
+    ($v:expr => u8) => { $crate::cv!(@cast $v => u8) };
+    ($v:expr => u16) => { $crate::cv!(@cast $v => u16) };
+    ($v:expr => u32) => { $crate::cv!(@cast $v => u32) };
+    ($v:expr => u64) => { $crate::cv!(@cast $v => u64) };
+    ($v:expr => u128) => { $crate::cv!(@cast $v => u128) };
+    ($v:expr => usize) => { $crate::cv!(@cast $v => usize) };
+    ($v:expr => i8) => { $crate::cv!(@cast $v => i8) };
+    ($v:expr => i16) => { $crate::cv!(@cast $v => i16) };

rust/kernel/num.rs line 95

Quoted 10 lines
rust/kernel/num.rs +10 -0
+    ($v:expr => i32) => { $crate::cv!(@cast $v => i32) };
+    ($v:expr => i64) => { $crate::cv!(@cast $v => i64) };
+    ($v:expr => i128) => { $crate::cv!(@cast $v => i128) };
+    ($v:expr => isize) => { $crate::cv!(@cast $v => isize) };
+    ($v:expr => $t:ty) => {
+        <$t as $crate::num::FromConst<{ $crate::cv!(@cast $v => i128) }>>::VALUE
+    };
+    ($v:expr) => {
+        <_ as $crate::num::FromConst<{ $crate::cv!(@cast $v => i128) }>>::VALUE
+    };

Can we document the arms a little bit? In particular the => u8... business. No need to document every single one, one comment for the group is fine.

Quoted 70 lines
rust/kernel/num.rs +54 -0
+}
+#[doc(inline)]
+pub use cv;
+
+/// Types that can be created from an integer constant expression validated at build time.
+///
+/// Implement this trait to make a type usable with [`cv!`]. Use the [`cv`] macro, not this trait
+/// directly, for creating values.
+#[diagnostic::on_unimplemented(message = "`{Self}` cannot be converted from a constant")]
+pub trait FromConst<const V: i128>: Sized {
+    /// The value that corresponds to the constant `V`.
+    ///
+    /// Fails the build if `V` is not a valid value for `Self`.
+    const VALUE: Self;
+}
+
+/// Implements [`FromConst`] for primitive integer types and their [`NonZero`](core::num::NonZero)
+/// versions.
+macro_rules! impl_from_const {
+    ($($type:ty)*) => {
+        $(
+        impl<const V: i128> FromConst<V> for $type {
+            const VALUE: Self = {
+                const_assert!(
+                    V >= <$type>::MIN as i128 && V <= <$type>::MAX as i128,
+                    "constant cannot be represented by the target type"
+                );
+
+                V as $type
+            };
+        }
+
+        impl<const V: i128> FromConst<V> for core::num::NonZero<$type> {
+            const VALUE: Self = {
+                const_assert!(
+                    V >= <$type>::MIN as i128 && V <= <$type>::MAX as i128,
+                    "constant cannot be represented by the underlying type"
+                );
+
+                match core::num::NonZero::new(V as $type) {
+                    Some(value) => value,
+                    None => panic!("constant cannot be zero"),
+                }
+            };
+        }
+        )*
+    };
+}
+
+impl_from_const!(
+    u8 u16 u32 u64 usize
+    i8 i16 i32 i64 isize
+);
+
 /// Designates unsigned primitive types.
 pub enum Unsigned {}
 
rust/kernel/num/bounded.rs +1 -0
index 2a2b0a4bca5e..f720eb44e7d3 100644
@@ -14,6 +14,7 @@
 
 use kernel::{
     num::{
+        FromConst,
         Integer,
         Unsigned, //
     },

rust/kernel/num/bounded.rs pub const fn new<const VALUE: $type>() -> Self { · line 282

Quoted 10 lines
rust/kernel/num/bounded.rs +7 -0
@@ -272,6 +273,24 @@ pub const fn new<const VALUE: $type>() -> Self {
                 unsafe { Self::__new(VALUE) }
             }
         }
+
+        impl<const N: u32, const V: i128> FromConst<V> for Bounded<$type, N> {
+            const VALUE: Self = {
+                const_assert!(
+                    V >= <$type>::MIN as i128 && V <= <$type>::MAX as i128,
+                    "constant cannot be represented by the underlying type"
+                );

Is it possible to leverage cv! on the primitive type to avoid this const_assert, which is basically a copy/paste of the one in num.rs?

As a bonus you would also get a value of the right type and don't need to use as twice below.

Quoted 19 lines
rust/kernel/num/bounded.rs +11 -0
+                // Statically assert that `V` fits within the set number of bits.
+                const_assert!(
+                    fits_within!(V as $type, $type, N),
+                    "constant cannot be represented within the given number of bits"
+                );
+
+                // SAFETY: the asserts above confirmed that `V` can be represented within `N`
+                // bits.
+                unsafe { Self::__new(V as $type) }
+            };
+        }
         )*
     };
 }
rust/kernel/ptr.rs +0 -0
index 82acb531b17b..ac1662c3c8af 100644

rust/kernel/ptr.rs pub const fn mask(self) -> usize { · line 174

Quoted 9 lines
rust/kernel/ptr.rs +6 -0
@@ -166,6 +166,20 @@ pub const fn mask(self) -> usize {
     }
 }
 
+impl<const V: i128> crate::num::FromConst<V> for Alignment {
+    const VALUE: Self = {
+        const_assert!(
+            V > 0 && V <= usize::MAX as i128,
+            "constant cannot be represented as an Alignment"
+        );

Same here if that works. Otherwise let's add a CAST: comment to the as statement below using this const_assert above as justification.

(also realized this could probably be done for the NonZero block as well)

#4 lore raw

Re: [PATCH v3 1/3] rust: num: add cv! macro to create values from constant expressions

Quoted 13 lines · Alexandre Courbot
Quoted 12 lines · Eliot Courtney

Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait FromConst. The value is then converted and appears in the associated constant FromConst::VALUE. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax.
For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).

Quoted 7 lines
Quoted 2 lines

I don't think we have any user but nova-core at the moment, and it benefits from this in several series (patch 3 here, but also ID pool and later r000). Miguel, is this ok if we take it (i.e. the next revision) through drm-rust-next?

Will send the next version based on drm-rust-next, but Miguel please let us know if it's ok to take through drm-rust-next. Thanks!

Quoted 20 lines

Some nits below.

Quoted 17 lines
---
 rust/kernel/num.rs         | 138 +++++++++++++++++++++++++++++++++++++++++++++
 rust/kernel/num/bounded.rs |  19 +++++++
 rust/kernel/ptr.rs         |  14 +++++
 3 files changed, 171 insertions(+)
rust/kernel/num.rs +1 -0
index dbe848e30efe..9435459376a4 100644
@@ -2,6 +2,7 @@
 
 //! Additional numerical features for the kernel.
 
+use crate::const_assert;
 use core::ops;
 
Quoted 7 lines

rust/kernel/num.rs line 11

Quoted 4 lines
rust/kernel/num.rs +0 -0
 pub mod bounded;
@@ -9,6 +10,143 @@
 
 pub use bounded::*;

Can we move the new code at the bottom of the file? I'd like to keep the Integer definition on top.

Done.

Quoted 15 lines

rust/kernel/num.rs line 15

Quoted 5 lines
rust/kernel/num.rs +3 -0
+/// Creates a value from an integer constant expression, with validity checked at build time.
+///
+/// This works for any type that implements [`FromConst`], with the target type inferred from

I am wondering about FromConst, do we want to make it public, or hide (and possibly seal) it?

Basically as it is anyone can implement a new type that works with cv!. If that's by design, then good, and I don't see any potential issue with that, but IIUC we also agree that this is a temporary workaround so we might not want to allow extensibility if it isn't future-proof.

Quoted 3 lines

If we decide to make FromConst more discreet without sealing it (which sounds like a good middle ground to me), then we should remove mentions of it from the public docs and mark it as #[doc(hidden)].

I think it's useful to make it public and it was my intention to let anyone implement a newtype that works with cv!. Drivers may have some type which has constants that is specific to their use case that they want to use. Also, if we expect more abstractions to initially appear in drivers then the good ones get moved into common code it's nice to let them use cv! from the beginning.

Quoted 34 lines
Quoted 34 lines
rust/kernel/num.rs +33 -0
+/// the context, or named explicitly with `cv!(value => Type)`.
+///
+/// # Examples
+///
+/// ```
+/// use core::num::NonZero;
+/// use kernel::num::Bounded;
+/// use kernel::num::cv;
+/// use kernel::ptr::Alignment;
+///
+/// let v: NonZero<usize> = cv!(8);
+/// assert_eq!(v.get(), 8);
+///
+/// // Any integer constant expression works, not only literals.
+/// let m: NonZero<usize> = cv!(usize::MAX);
+/// assert_eq!(m.get(), usize::MAX);
+///
+/// let b: Bounded<u32, 4> = cv!(15);
+/// assert_eq!(b.get(), 15);
+///
+/// let a: Alignment = cv!(4096);
+/// assert_eq!(a.as_usize(), 4096);
+///
+/// // Checked narrowing of integer constants, including in `const` items.
+/// const SMALL: u8 = cv!(200u32);
+/// assert_eq!(SMALL, 200);
+///
+/// const N: NonZero<u8> = cv!(5);
+/// assert_eq!(N.get(), 5);
+///
+/// // The target type can be given explicitly.
+/// let e = cv!(200u32 => u8);
+/// assert_eq!(e, 200);
Quoted 8 lines

rust/kernel/num.rs line 54

Quoted 6 lines
rust/kernel/num.rs +6 -0
+///
+/// // With an explicit primitive target, the expression can use generic parameters.
+/// const fn as_u64<const KEY: u16>() -> u64 {
+///     cv!(KEY => u64)
+/// }
+/// assert_eq!(as_u64::<0x40>(), 0x40);

These examples are excellent.

thank you~~

Quoted 12 lines

rust/kernel/num.rs line 61

Quoted 8 lines
rust/kernel/num.rs +7 -0
+/// ```
+#[macro_export]
+#[doc(hidden)]
+macro_rules! cv {
+    (@cast $v:expr => $t:ty) => {
+        const {
+            #[allow(unused_comparisons, unused_assignments, clippy::as_underscore)]

You may want to add clippy::unnecessary_cast, in case one does cv!(v => u32) where v is already a u32 (which would happen in macro or generic code).

I believe clippy ignores unnecessary_cast when it's generated from a macro. At least I couldn't get the warning to trigger.

Quoted 31 lines
Quoted 31 lines
rust/kernel/num.rs +30 -0
+            {
+                let v = $v;
+                let r = v as $t;
+                // Pin `back` to `v`'s type so `as _` casts back to the source type.
+                let mut back = v;
+                back = r as _;
+
+                ::core::assert!(
+                    back == v && (v < 0) == (r < 0),
+                    "value does not fit into the target type"
+                );
+
+                r
+            }
+        }
+    };
+    ($v:expr => u8) => { $crate::cv!(@cast $v => u8) };
+    ($v:expr => u16) => { $crate::cv!(@cast $v => u16) };
+    ($v:expr => u32) => { $crate::cv!(@cast $v => u32) };
+    ($v:expr => u64) => { $crate::cv!(@cast $v => u64) };
+    ($v:expr => u128) => { $crate::cv!(@cast $v => u128) };
+    ($v:expr => usize) => { $crate::cv!(@cast $v => usize) };
+    ($v:expr => i8) => { $crate::cv!(@cast $v => i8) };
+    ($v:expr => i16) => { $crate::cv!(@cast $v => i16) };
+    ($v:expr => i32) => { $crate::cv!(@cast $v => i32) };
+    ($v:expr => i64) => { $crate::cv!(@cast $v => i64) };
+    ($v:expr => i128) => { $crate::cv!(@cast $v => i128) };
+    ($v:expr => isize) => { $crate::cv!(@cast $v => isize) };
+    ($v:expr => $t:ty) => {
+        <$t as $crate::num::FromConst<{ $crate::cv!(@cast $v => i128) }>>::VALUE
Quoted 8 lines

rust/kernel/num.rs line 95

Quoted 4 lines
rust/kernel/num.rs +4 -0
+    };
+    ($v:expr) => {
+        <_ as $crate::num::FromConst<{ $crate::cv!(@cast $v => i128) }>>::VALUE
+    };

Can we document the arms a little bit? In particular the => u8... business. No need to document every single one, one comment for the group is fine.

Done.

Quoted 85 lines
Quoted 71 lines
rust/kernel/num.rs +54 -0
+}
+#[doc(inline)]
+pub use cv;
+
+/// Types that can be created from an integer constant expression validated at build time.
+///
+/// Implement this trait to make a type usable with [`cv!`]. Use the [`cv`] macro, not this trait
+/// directly, for creating values.
+#[diagnostic::on_unimplemented(message = "`{Self}` cannot be converted from a constant")]
+pub trait FromConst<const V: i128>: Sized {
+    /// The value that corresponds to the constant `V`.
+    ///
+    /// Fails the build if `V` is not a valid value for `Self`.
+    const VALUE: Self;
+}
+
+/// Implements [`FromConst`] for primitive integer types and their [`NonZero`](core::num::NonZero)
+/// versions.
+macro_rules! impl_from_const {
+    ($($type:ty)*) => {
+        $(
+        impl<const V: i128> FromConst<V> for $type {
+            const VALUE: Self = {
+                const_assert!(
+                    V >= <$type>::MIN as i128 && V <= <$type>::MAX as i128,
+                    "constant cannot be represented by the target type"
+                );
+
+                V as $type
+            };
+        }
+
+        impl<const V: i128> FromConst<V> for core::num::NonZero<$type> {
+            const VALUE: Self = {
+                const_assert!(
+                    V >= <$type>::MIN as i128 && V <= <$type>::MAX as i128,
+                    "constant cannot be represented by the underlying type"
+                );
+
+                match core::num::NonZero::new(V as $type) {
+                    Some(value) => value,
+                    None => panic!("constant cannot be zero"),
+                }
+            };
+        }
+        )*
+    };
+}
+
+impl_from_const!(
+    u8 u16 u32 u64 usize
+    i8 i16 i32 i64 isize
+);
+
 /// Designates unsigned primitive types.
 pub enum Unsigned {}
 
rust/kernel/num/bounded.rs +1 -0
index 2a2b0a4bca5e..f720eb44e7d3 100644
@@ -14,6 +14,7 @@
 
 use kernel::{
     num::{
+        FromConst,
         Integer,
         Unsigned, //
     },

rust/kernel/num/bounded.rs pub const fn new<const VALUE: $type>() -> Self { · line 282

Quoted 10 lines
rust/kernel/num/bounded.rs +7 -0
@@ -272,6 +273,24 @@ pub const fn new<const VALUE: $type>() -> Self {
                 unsafe { Self::__new(VALUE) }
             }
         }
+
+        impl<const N: u32, const V: i128> FromConst<V> for Bounded<$type, N> {
+            const VALUE: Self = {
+                const_assert!(
+                    V >= <$type>::MIN as i128 && V <= <$type>::MAX as i128,
+                    "constant cannot be represented by the underlying type"
+                );

Is it possible to leverage cv! on the primitive type to avoid this const_assert, which is basically a copy/paste of the one in num.rs?

Quoted 2 lines

As a bonus you would also get a value of the right type and don't need to use as twice below.

Yeah good idea. It seems like this doens't work since by the time you get inside the macro, it's already treating it as a $ty and that can't match the primitive arms of cv!. But we can use FromConst::VALUE directly, that's maybe a bit nicer.

Quoted 33 lines
Quoted 20 lines
rust/kernel/num/bounded.rs +11 -0
+                // Statically assert that `V` fits within the set number of bits.
+                const_assert!(
+                    fits_within!(V as $type, $type, N),
+                    "constant cannot be represented within the given number of bits"
+                );
+
+                // SAFETY: the asserts above confirmed that `V` can be represented within `N`
+                // bits.
+                unsafe { Self::__new(V as $type) }
+            };
+        }
         )*
     };
 }
rust/kernel/ptr.rs +0 -0
index 82acb531b17b..ac1662c3c8af 100644

rust/kernel/ptr.rs pub const fn mask(self) -> usize { · line 174

Quoted 9 lines
rust/kernel/ptr.rs +6 -0
@@ -166,6 +166,20 @@ pub const fn mask(self) -> usize {
     }
 }
 
+impl<const V: i128> crate::num::FromConst<V> for Alignment {
+    const VALUE: Self = {
+        const_assert!(
+            V > 0 && V <= usize::MAX as i128,
+            "constant cannot be represented as an Alignment"
+        );

Same here if that works. Otherwise let's add a CAST: comment to the as statement below using this const_assert above as justification.

Quoted 2 lines

(also realized this could probably be done for the NonZero block as well)

Did the same using FromConst<> directly here. I did add two CAST:
comments on the base FromConst<V> for <primitive> though that are unavoidable.

#5 lore raw

Re: [PATCH v3 1/3] rust: num: add cv! macro to create values from constant expressions

Quoted 3 lines · Eliot Courtney

Will send the next version based on drm-rust-next, but Miguel please let us know if it's ok to take through drm-rust-next. Thanks!

Ok, given the recent discussions, let's move this forward... I have replied in v4 with the Acked-by, although with some feedback.

Cheers,
Miguel

reviewer
#6 lore raw

Re: [PATCH v3 1/3] rust: num: add cv! macro to create values from constant expressions

In reply to Alexandre Courbot
Quoted 13 lines · Alexandre Courbot
Quoted 12 lines · Eliot Courtney

Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait FromConst. The value is then converted and appears in the associated constant FromConst::VALUE. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax.
For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).

Quoted 7 lines
Quoted 2 lines

I don't think we have any user but nova-core at the moment, and it benefits from this in several series (patch 3 here, but also ID pool and later r000). Miguel, is this ok if we take it (i.e. the next revision) through drm-rust-next?

How about a topic tag shared between Rust and drm-rust-next? We could also remove the old num casts API as part of topic tag and fix all existing users as part of merge.

Best,
Gary

#7 lore raw

Re: [PATCH v3 1/3] rust: num: add cv! macro to create values from constant expressions

Quoted 17 lines · Gary Guo
Quoted 16 lines · Alexandre Courbot
Quoted 14 lines · Eliot Courtney

Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait FromConst. The value is then converted and appears in the associated constant FromConst::VALUE. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax.
For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).

Quoted 8 lines
Quoted 4 lines

I don't think we have any user but nova-core at the moment, and it benefits from this in several series (patch 3 here, but also ID pool and later r000). Miguel, is this ok if we take it (i.e. the next revision) through drm-rust-next?

How about a topic tag shared between Rust and drm-rust-next? We could also remove the old num casts API as part of topic tag and fix all existing users as part of merge.

Not opposed to the idea but IIRC there was already some pushback to the idea. There doesn't seem to be an urgency to remove the old num casts API that justifies doing it now with a more complicated merge path.

reviewer
#8 lore raw

Re: [PATCH v3 1/3] rust: num: add cv! macro to create values from constant expressions

Quoted 23 lines · Alexandre Courbot
Quoted 22 lines · Gary Guo
Quoted 20 lines · Alexandre Courbot
Quoted 12 lines · Eliot Courtney

Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait FromConst. The value is then converted and appears in the associated constant FromConst::VALUE. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax.
For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).

Quoted 2 lines

I don't think we have any user but nova-core at the moment, and it benefits from this in several series (patch 3 here, but also ID pool and later r000). Miguel, is this ok if we take it (i.e. the next revision) through drm-rust-next?

Quoted 7 lines
Quoted 3 lines

How about a topic tag shared between Rust and drm-rust-next? We could also remove the old num casts API as part of topic tag and fix all existing users as part of merge.

Not opposed to the idea but IIRC there was already some pushback to the idea. There doesn't seem to be an urgency to remove the old num casts API that justifies doing it now with a more complicated merge path.

Sorry, what pushbacks? I thought that cv! is what everyone agrees on. I see no downside of this compared to the turbofish const conversion APIs.

I am not opposed to delaying removal for the next cycle, but IMO the cv! macro should be present on Rust tree so it's visible and improvements can be made from there, so I think we should do a topic tag regardless whether the old API removal happens or not.

Best,
Gary

maintainer
#9 lore raw

Re: [PATCH v3 1/3] rust: num: add cv! macro to create values from constant expressions

Quoted 32 lines · Gary Guo
Quoted 23 lines · Alexandre Courbot
Quoted 22 lines · Gary Guo
Quoted 20 lines · Alexandre Courbot
Quoted 12 lines · Eliot Courtney

Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait FromConst. The value is then converted and appears in the associated constant FromConst::VALUE. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax.
For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).

Quoted 2 lines

I don't think we have any user but nova-core at the moment, and it benefits from this in several series (patch 3 here, but also ID pool and later r000). Miguel, is this ok if we take it (i.e. the next revision) through drm-rust-next?

Quoted 7 lines
Quoted 3 lines

How about a topic tag shared between Rust and drm-rust-next? We could also remove the old num casts API as part of topic tag and fix all existing users as part of merge.

Not opposed to the idea but IIRC there was already some pushback to the idea. There doesn't seem to be an urgency to remove the old num casts API that justifies doing it now with a more complicated merge path.

Quoted 7 lines

Sorry, what pushbacks? I thought that cv! is what everyone agrees on. I see no downside of this compared to the turbofish const conversion APIs.

I am not opposed to delaying removal for the next cycle, but IMO the cv! macro should be present on Rust tree so it's visible and improvements can be made from there, so I think we should do a topic tag regardless whether the old API removal happens or not.

I think Alex refers to this thread [1]; there's was some more context to this though.

[1] https://lore.kernel.org/all/[email protected]/

reviewer
#10 lore raw

Re: [PATCH v3 1/3] rust: num: add cv! macro to create values from constant expressions

Quoted 36 lines · Danilo Krummrich
Quoted 35 lines · Gary Guo
Quoted 23 lines · Alexandre Courbot
Quoted 22 lines · Gary Guo
Quoted 20 lines · Alexandre Courbot
Quoted 12 lines · Eliot Courtney

Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait FromConst. The value is then converted and appears in the associated constant FromConst::VALUE. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax.
For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).

Quoted 2 lines

I don't think we have any user but nova-core at the moment, and it benefits from this in several series (patch 3 here, but also ID pool and later r000). Miguel, is this ok if we take it (i.e. the next revision) through drm-rust-next?

Quoted 7 lines
Quoted 3 lines

How about a topic tag shared between Rust and drm-rust-next? We could also remove the old num casts API as part of topic tag and fix all existing users as part of merge.

Not opposed to the idea but IIRC there was already some pushback to the idea. There doesn't seem to be an urgency to remove the old num casts API that justifies doing it now with a more complicated merge path.

Sorry, what pushbacks? I thought that cv! is what everyone agrees on. I see no downside of this compared to the turbofish const conversion APIs.

Quoted 7 lines
Quoted 4 lines

I am not opposed to delaying removal for the next cycle, but IMO the cv! macro should be present on Rust tree so it's visible and improvements can be made from there, so I think we should do a topic tag regardless whether the old API removal happens or not.

I think Alex refers to this thread [1]; there's was some more context to this though.

Right, so "pushback" here relates to the logistics of old API removal, not the idea of cv!?

Best,
Gary

Quoted 2 lines

[1] https://lore.kernel.org/all/[email protected]/

#11 lore raw

Re: [PATCH v3 1/3] rust: num: add cv! macro to create values from constant expressions

Quoted 42 lines · Gary Guo
Quoted 41 lines · Danilo Krummrich
Quoted 39 lines · Gary Guo
Quoted 23 lines · Alexandre Courbot
Quoted 22 lines · Gary Guo
Quoted 20 lines · Alexandre Courbot
Quoted 12 lines · Eliot Courtney

Currently, using NonZero/Bounded constants is quite verbose. It's unfortunate because it disincentivizes using it in interface boundaries. Introduce a macro to make it nicer to use. The macro cv! (for constant value) takes a const integer expression and widens it to i128 (at build time only) before passing it as a const generic value to a new trait FromConst. The value is then converted and appears in the associated constant FromConst::VALUE. The trait is implemented by NonZero, Bounded, and Alignment and lets values of each be constructed from constants without a verbose turbofish syntax.
For example, const { NonZero::new(1).unwrap() } can be written as cv!(1).

Quoted 2 lines

I don't think we have any user but nova-core at the moment, and it benefits from this in several series (patch 3 here, but also ID pool and later r000). Miguel, is this ok if we take it (i.e. the next revision) through drm-rust-next?

Quoted 7 lines
Quoted 3 lines

How about a topic tag shared between Rust and drm-rust-next? We could also remove the old num casts API as part of topic tag and fix all existing users as part of merge.

Not opposed to the idea but IIRC there was already some pushback to the idea. There doesn't seem to be an urgency to remove the old num casts API that justifies doing it now with a more complicated merge path.

Sorry, what pushbacks? I thought that cv! is what everyone agrees on. I see no downside of this compared to the turbofish const conversion APIs.

I am not opposed to delaying removal for the next cycle, but IMO the cv! macro should be present on Rust tree so it's visible and improvements can be made from there, so I think we should do a topic tag regardless whether the old API removal happens or not.

Quoted 5 lines
Quoted 2 lines

I think Alex refers to this thread [1]; there's was some more context to this though.

Right, so "pushback" here relates to the logistics of old API removal, not the idea of cv!?

Correct - sorry about the confusion.

#12 lore raw

PATCH v3 2/3 rust: prelude: add `num::cv`

In reply to Eliot Courtney

Add the cv! macro to the prelude so it doesn't need to be imported explicitly to use it.

---
 rust/kernel/num.rs     | 1 -
 rust/kernel/prelude.rs | 1 +
 2 files changed, 1 insertion(+), 1 deletion(-)
rust/kernel/num.rs +0 -1
index 9435459376a4..08862fe6ceee 100644
@@ -20,7 +20,6 @@
 /// ```
 /// use core::num::NonZero;
 /// use kernel::num::Bounded;
-/// use kernel::num::cv;
 /// use kernel::ptr::Alignment;
 ///
 /// let v: NonZero<usize> = cv!(8);
rust/kernel/prelude.rs +1 -0
index ca396f1f78a6..5facf8f7af90 100644
@@ -106,6 +106,7 @@
         Result, //
     },
     init::InPlaceInit,
+    num::cv,
     pr_alert,
     pr_crit,
     pr_debug,
Signature · 1 line
2.55.0
#13 lore raw

Re: [PATCH v3 2/3] rust: prelude: add `num::cv`

Quoted 5 lines · Eliot Courtney

Add the cv! macro to the prelude so it doesn't need to be imported explicitly to use it.

I believe this can be squashed into patch 1, there is no need for a state where cv exists but isn't in the prelude if we agree it should be there.

#14 lore raw

PATCH v3 3/3 gpu: nova-core: use cv! for constant casts

In reply to Eliot Courtney

The new cv! macro allows safe casting of constant expressions in a const context. Update code in nova-core to use it.

---
 drivers/gpu/nova-core/falcon.rs                    |  9 ++--
 drivers/gpu/nova-core/fb/hal/gb100.rs              |  4 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |  7 +--
 drivers/gpu/nova-core/fsp.rs                       |  3 +-
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  6 +--
 drivers/gpu/nova-core/gsp/fw.rs                    | 38 +++++++--------
 drivers/gpu/nova-core/gsp/fw/commands.rs           |  2 +-
 drivers/gpu/nova-core/num.rs                       | 55 +---------------------
 8 files changed, 28 insertions(+), 96 deletions(-)
drivers/gpu/nova-core/falcon.rs +3 -6
index 65cb12d26e2b..0e0383331f42 100644
@@ -29,11 +29,8 @@
     driver::Bar0,
     falcon::hal::LoadMethod,
     gpu::Chipset,
-    num::{
-        self,
-        FromSafeCast, //
-    },
-    regs,
+    num::FromSafeCast,
+    regs, //
 };
 
 pub(crate) mod fsp;
@@ -510,7 +507,7 @@ fn dma_wr(
         target_mem: FalconMem,
         load_offsets: FalconDmaLoadTarget,
     ) -> Result {
-        const DMA_LEN: u32 = num::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();
+        const DMA_LEN: u32 = cv!(MEM_BLOCK_ALIGNMENT);
 
         // DMA transfers can only be done in units of 256 bytes. Compute how many such transfers we
         // need to perform.
drivers/gpu/nova-core/fb/hal/gb100.rs +1 -3
index d9e4d62ae632..0bf00d381607 100644
@@ -26,7 +26,6 @@
         hal::FbHal,
         regs, //
     },
-    num::usize_into_u32,
 };
 
 struct Gb100;
@@ -82,8 +81,7 @@ fn write_sysmem_flush_page_gb100(bar: Bar0<'_>, addr: Bounded<u64, 52>) {
 
 // This PMU reservation size is r570-specific.
 pub(super) const fn pmu_reserved_size_gb100() -> u32 {
-    usize_into_u32::<{ const_align_up(SZ_8M + SZ_16M + SZ_4K, Alignment::new::<SZ_128K>()).unwrap() }>(
-    )
+    cv!(const_align_up(SZ_8M + SZ_16M + SZ_4K, Alignment::new::<SZ_128K>()).unwrap())
 }
 
 impl FbHal for Gb100 {
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +2 -5
index ec4d92317a93..b51aca619a8c 100644
@@ -14,10 +14,7 @@
     dma::Coherent,
     io::{register::WithBase, Io},
     prelude::*,
-    ptr::{
-        Alignable,
-        Alignment, //
-    },
+    ptr::Alignable,
     sizes,
     transmute::AsBytes,
 };
@@ -134,7 +131,7 @@ pub(crate) fn new(
             let code_size = usize::from_safe_cast(tlv.get_u32(b"CDSZ")?);
             let code = blob.get(..code_size).ok_or(EINVAL)?;
             let aligned_code_size = code_size
-                .align_up(Alignment::new::<{ falcon::MEM_BLOCK_ALIGNMENT }>())
+                .align_up(cv!(falcon::MEM_BLOCK_ALIGNMENT))
                 .ok_or(EINVAL)?;
 
             let mut ucode = KVec::with_capacity(aligned_code_size, GFP_KERNEL)?;
drivers/gpu/nova-core/fsp.rs +1 -2
index ab685fb4168f..e15d0af95499 100644
@@ -47,7 +47,6 @@
         NvdmHeader,
         NvdmType, //
     },
-    num,
     regs, //
 };
 
@@ -285,7 +284,7 @@ fn new<'a>(
         };
 
         let version = hal.cot_version();
-        let size = num::usize_into_u16::<{ core::mem::size_of::<NvdmPayloadCot>() }>();
+        let size = cv!(core::mem::size_of::<NvdmPayloadCot>() => u16);
 
         Ok(init!(Self {
             header: FspMessageHeader::new(NvdmType::Cot),
drivers/gpu/nova-core/gsp/cmdq.rs +3 -3
index 6da728201281..bf8ade55b304 100644
@@ -162,7 +162,7 @@ fn read(
 #[repr(C, align(0x1000))]
 #[derive(Debug)]
 struct MsgqData {
-    data: [[u8; GSP_PAGE_SIZE]; num::u32_as_usize(MSGQ_NUM_PAGES)],
+    data: [[u8; GSP_PAGE_SIZE]; cv!(MSGQ_NUM_PAGES)],
 }
 
 // Annoyingly we are forced to use a literal to specify the alignment of
@@ -235,8 +235,8 @@ unsafe impl FromBytes for GspMem {}
 impl DmaGspMem {
     /// Allocate a new instance and map it for `dev`.
     fn new(dev: &device::Device<device::Bound>) -> Result<Self> {
-        const MSGQ_SIZE: u32 = num::usize_into_u32::<{ size_of::<Msgq>() }>();
-        const RX_HDR_OFF: u32 = num::usize_into_u32::<{ mem::offset_of!(Msgq, rx) }>();
+        const MSGQ_SIZE: u32 = cv!(size_of::<Msgq>());
+        const RX_HDR_OFF: u32 = cv!(mem::offset_of!(Msgq, rx));
 
         let mut gsp_mem = CoherentBox::<GspMem>::zeroed(dev, GFP_KERNEL)?;
         gsp_mem.cpuq.tx = MsgqTxHeader::new(MSGQ_SIZE, RX_HDR_OFF, MSGQ_NUM_PAGES);
drivers/gpu/nova-core/gsp/fw.rs +16 -22
index 05f54fee6186..33ec3d983c08 100644
@@ -57,7 +57,7 @@
 
 /// Maximum size of a single GSP message queue element in bytes.
 pub(crate) const GSP_MSG_QUEUE_ELEMENT_SIZE_MAX: usize =
-    num::u32_as_usize(bindings::GSP_MSG_QUEUE_ELEMENT_SIZE_MAX);
+    cv!(bindings::GSP_MSG_QUEUE_ELEMENT_SIZE_MAX);
 
 /// Empty type to group methods related to heap parameters for running the GSP firmware.
 enum GspFwHeapParams {}
@@ -110,20 +110,18 @@ pub(crate) struct LibosParams {
 impl LibosParams {
     /// Version 2 of the GSP LIBOS (Turing and GA100)
     const LIBOS2: LibosParams = LibosParams {
-        carveout_size: num::u32_as_u64(bindings::GSP_FW_HEAP_PARAM_OS_SIZE_LIBOS2),
-        allowed_heap_size: num::u32_as_u64(bindings::GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS2_MIN_MB)
+        carveout_size: cv!(bindings::GSP_FW_HEAP_PARAM_OS_SIZE_LIBOS2),
+        allowed_heap_size: cv!(bindings::GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS2_MIN_MB => u64)
             * u64::SZ_1M
-            ..num::u32_as_u64(bindings::GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS2_MAX_MB) * u64::SZ_1M,
+            ..cv!(bindings::GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS2_MAX_MB => u64) * u64::SZ_1M,
     };
 
     /// Version 3 of the GSP LIBOS (GA102+)
     const LIBOS3: LibosParams = LibosParams {
-        carveout_size: num::u32_as_u64(bindings::GSP_FW_HEAP_PARAM_OS_SIZE_LIBOS3_BAREMETAL),
-        allowed_heap_size: num::u32_as_u64(
-            bindings::GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS3_BAREMETAL_MIN_MB,
-        ) * u64::SZ_1M
-            ..num::u32_as_u64(bindings::GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS3_BAREMETAL_MAX_MB)
-                * u64::SZ_1M,
+        carveout_size: cv!(bindings::GSP_FW_HEAP_PARAM_OS_SIZE_LIBOS3_BAREMETAL),
+        allowed_heap_size: cv!(bindings::GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS3_BAREMETAL_MIN_MB => u64)
+            * u64::SZ_1M
+            ..cv!(bindings::GSP_FW_HEAP_SIZE_OVERRIDE_LIBOS3_BAREMETAL_MAX_MB => u64) * u64::SZ_1M,
     };
 
     /// Returns the libos parameters corresponding to `chipset`.
@@ -682,12 +680,8 @@ fn id8(name: &str) -> u64 {
             id8: id8(name),
             pa: obj.dma_address(),
             size: num::usize_as_u64(obj.size()),
-            kind: num::u32_into_u8::<
-                { bindings::LibosMemoryRegionKind_LIBOS_MEMORY_REGION_CONTIGUOUS },
-            >(),
-            loc: num::u32_into_u8::<
-                { bindings::LibosMemoryRegionLoc_LIBOS_MEMORY_REGION_LOC_SYSMEM },
-            >(),
+            kind: cv!(bindings::LibosMemoryRegionKind_LIBOS_MEMORY_REGION_CONTIGUOUS),
+            loc: cv!(bindings::LibosMemoryRegionLoc_LIBOS_MEMORY_REGION_LOC_SYSMEM),
             ..Zeroable::init_zeroed()
         });
 
@@ -715,12 +709,12 @@ pub(crate) fn new(msgq_size: u32, rx_hdr_offset: u32, msg_count: u32) -> Self {
         Self(bindings::msgqTxHeader {
             version: 0,
             size: msgq_size,
-            msgSize: num::usize_into_u32::<GSP_PAGE_SIZE>(),
+            msgSize: cv!(GSP_PAGE_SIZE),
             msgCount: msg_count,
             writePtr: 0,
             flags: 1,
             rxHdrOff: rx_hdr_offset,
-            entryOff: num::usize_into_u32::<GSP_PAGE_SIZE>(),
+            entryOff: cv!(GSP_PAGE_SIZE),
         })
     }
 
@@ -947,9 +941,9 @@ impl MessageQueueInitArguments {
     fn new(cmdq: &Cmdq) -> impl Init<Self> + '_ {
         init!(MessageQueueInitArguments {
             sharedMemPhysAddr: cmdq.dma_addr,
-            pageTableEntryCount: num::usize_into_u32::<{ Cmdq::NUM_PTES }>(),
-            cmdQueueOffset: num::usize_as_u64(Cmdq::CMDQ_OFFSET),
-            statQueueOffset: num::usize_as_u64(Cmdq::STATQ_OFFSET),
+            pageTableEntryCount: cv!(Cmdq::NUM_PTES),
+            cmdQueueOffset: u64::from_safe_cast(Cmdq::CMDQ_OFFSET),
+            statQueueOffset: u64::from_safe_cast(Cmdq::STATQ_OFFSET),
             ..Zeroable::init_zeroed()
         })
     }
@@ -969,7 +963,7 @@ impl GspAcrBootGspRmParams {
     fn new(target: GspDmaTarget, wpr_meta_addr: u64) -> impl Init<Self> {
         let params = init!(Self {
             target: target as u32,
-            gspRmDescSize: num::usize_into_u32::<{ size_of::<GspFwWprMeta>() }>(),
+            gspRmDescSize: cv!(size_of::<GspFwWprMeta>()),
             gspRmDescOffset: wpr_meta_addr,
             bIsGspRmBoot: 1,
             wprCarveoutOffset: 0,
drivers/gpu/nova-core/gsp/fw/commands.rs +1 -1
index 6dc31d1bf5ae..384eccf3c44a 100644
@@ -82,7 +82,7 @@ pub(crate) fn new(offset: u32, value: u32) -> Self {
 
                 // We only support DWORD types for now. Support for other types
                 // will come later if required.
-                type_: bindings::REGISTRY_TABLE_ENTRY_TYPE_DWORD as u8,
+                type_: cv!(bindings::REGISTRY_TABLE_ENTRY_TYPE_DWORD),
                 __bindgen_padding_0: Default::default(),
                 data: value,
                 length: 0,
drivers/gpu/nova-core/num.rs +1 -54

67 lines not on this page · raw message

Signature · 1 line
2.55.0