Skip to contentSkip to conversation

rust: num: casts: replace const type narrowing methods with a macro

PATCH In review Alexandre Courbot 5 participants 19 messages Aug 25 – Aug 27

Subsystems (6)
lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

cover rust: num: casts: replace const type narrowing methods with a macro

The casts module includes lossless const converter functions, as it is sometimes necessary to cast a bindgen-generated constant into a narrower type. Such conversions are known to be lossless at compile-time, but using as for them still requires a CAST comment and carries the risk of the conversion becoming lossy should the value of the constant change.

Since these functions need to be evaluated at compile-time, they take the expression to narrow as a generic const argument, requiring the use of the turbofish syntax by callers. Also, a dedicated function is needed per type conversion, resulting in 9 functions generated by a single macro. All these factors make them hard to discover and a bit cumbersome to use.

This series replaces these functions with a single const_as macro that ensures an as conversion is lossless at build-time. Since it is unique and not generated, it is easy to discover, and its syntax also looks more accessible than the turbofish one.

Patch 2 then performs the conversion of nova-core to use these conversion helpers in the process of removing its own superseded num module.

This series is based on today's master.

---
Alexandre Courbot (2):
rust: num: casts: replace const type narrowing methods with a macro
gpu: nova-core: use kernel lossless integer conversion module

 drivers/gpu/nova-core/falcon.rs                    |  12 +-
 drivers/gpu/nova-core/falcon/fsp.rs                |   4 +-
 drivers/gpu/nova-core/fb.rs                        |   2 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   9 +-
 drivers/gpu/nova-core/firmware.rs                  |   4 +-
 drivers/gpu/nova-core/firmware/booter.rs           |   4 +-
 drivers/gpu/nova-core/firmware/fwsec.rs            |   2 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   4 +-
 drivers/gpu/nova-core/firmware/gsp.rs              |   9 +-
 drivers/gpu/nova-core/firmware/tlv.rs              |  11 +-
 drivers/gpu/nova-core/fsp.rs                       |   8 +-
 drivers/gpu/nova-core/gsp.rs                       |   4 +-
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  22 +--
 drivers/gpu/nova-core/gsp/fw.rs                    |  50 ++---
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   4 +-
 drivers/gpu/nova-core/gsp/sequencer.rs             |   2 +-
 drivers/gpu/nova-core/mctp.rs                      |   8 +-
 drivers/gpu/nova-core/num.rs                       | 211 ---------------------
 drivers/gpu/nova-core/vbios.rs                     |   2 +-
 rust/kernel/num/casts.rs                           | 129 ++++++++-----
 20 files changed, 163 insertions(+), 338 deletions(-)

---
base-commit: 66498c75b4f8017f62d720d9b59675bdf3abce91
change-id: 20260825-const_as-a792dad39943

Best regards,

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

PATCH 1/2 rust: num: casts: replace const type narrowing methods with a macro

The casts module features a series of const converters (e.g. u32_into_u16) that narrow the type of a const expression provided that its value can be proven to fit into the destination type at compile-time.

These functions are numerous (9 of them), generated by a macro and thus not easily discoverable, and cumbersome to use as they require a turbofish and const expression between { and } braces.

Replace them all by a single const_as! macro that expands to a const block verifying the lossless nature of the conversion at compile-time. This turns e.g.:

    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);

This makes things easier to read and understand, while shifting the burden of checking the conversion's validity from reviewers (via a CAST comment) to the compiler.

---
 rust/kernel/num/casts.rs | 129 +++++++++++++++++++++++++++++------------------
 1 file changed, 79 insertions(+), 50 deletions(-)
rust/kernel/num/casts.rs +79 -50
index 7e6c7dec747d..a4a18a6f2ba8 100644
@@ -20,10 +20,8 @@
 //! - Two extension traits, [`FromSafeCast`] and [`IntoSafeCast`], providing conversion methods
 //!   similar to [`From`] and [`Into`] for conversions that are safe to perform in the kernel, but
 //!   not supported by the standard library.
-//! - Another series of const functions (e.g. [`u64_into_u8`]) supporting the conversion of a const
-//!   value from a larger type into a smaller one, provided the value fits into the destination
-//!   type. This is useful if a constant is defined as a larger type, but needs to be used as a
-//!   smaller one.
+//! - A [`const_as!`] macro, losslessly casting a constant expression between any two integer
+//!   types, with conversions that would alter the value reported as build errors.
 //! - An [`arch`] sub-module, defining more conversion functions that are only guaranteed to be
 //!   lossless for a given pointer size. These can only be used in code that is specific to a
 //!   given pointer size.
@@ -36,6 +34,9 @@
 //! // Conversion from const context.
 //! const USIZED_CONST: usize = casts::u8_as_usize(255u8);
 //!
+//! // Build-time checked narrowing conversion of a constant expression.
+//! const NARROWED_CONST: u16 = casts::const_as!(0xf00u32 => u16);
+//!
 //! // Non-const conversions.
 //! let a = u64::from_safe_cast(4096usize);
 //! let b: u64 = 4096usize.into_safe_cast();
@@ -182,57 +183,85 @@ fn into_safe_cast(self) -> T {
     }
 }
 
-/// Implements lossless conversion of a constant from a larger type into a smaller one.
-macro_rules! impl_const_into {
-    ($from:ty => { $($into:ty),* }) => {
-        $(
-        $crate::macros::paste! {
-            #[doc = ::core::concat!(
-                "Performs a build-time safe conversion of a [`",
-                ::core::stringify!($from),
-                "`] constant value into a [`",
-                ::core::stringify!($into),
-                "`].")]
-            ///
-            /// This checks at compile-time that the conversion is lossless, and triggers a build
-            /// error if it isn't.
-            ///
-            /// # Examples
-            ///
-            /// ```
-            /// use kernel::num::casts;
-            ///
-            /// // Succeeds because the value of the source fits into the destination's type.
-            #[doc = ::core::concat!(
-                "assert_eq!(casts::",
-                ::core::stringify!($from),
-                "_into_",
-                ::core::stringify!($into),
-                "::<1",
-                ::core::stringify!($from),
-                ">(), 1",
-                ::core::stringify!($into),
-                ");")]
-            /// ```
-            #[inline]
-            pub const fn [<$from _into_ $into>]<const N: $from>() -> $into {
-                // Make sure that the target type is smaller than the source one.
-                $crate::static_assert!($from::BITS >= $into::BITS);
-                // CAST: we statically enforced above that `$from` is larger than `$into`, so the
-                // `as` conversion will be lossless.
-                $crate::const_assert!(N >= $into::MIN as $from && N <= $into::MAX as $from);
+/// Losslessly casts a constant expression into a target integer type, or fails the build.
+///
+/// This is a checked replacement for the `as` keyword on constant expressions: the conversion is
+/// evaluated at build time, and a build error is triggered if the source value does not fit into
+/// the destination type. Since the compiler verifies that the conversion is lossless, a `CAST`
+/// comment is not needed.
+///
+/// The argument is a constant expression.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::num::casts;
+///
+/// // Narrows the type of a constant in const context.
+/// const CAP_ID: u16 = casts::const_as!(0x0010u32 => u16);
+/// assert_eq!(CAP_ID, 0x0010u16);
+///
+/// // Widens the type of a constant, outside of const context.
+/// let v: u64 = casts::const_as!(42u16 => u64);
+/// assert_eq!(v, 42u64);
+///
+/// // Signed conversions work as well...
+/// assert_eq!(casts::const_as!(-42i32 => i16), -42i16);
+///
+/// // ...and so do cross-signedness conversions as long as the value fits.
+/// assert_eq!(casts::const_as!(258i32 => u16), 258u16);
+/// ```
+///
+/// A value that does not fit into the destination type fails to build:
+///
+/// ```ignore,compile_fail
+/// # use kernel::num::casts;
+/// // Fails to build: `0x10000` does not fit into a `u16`.
+/// const ID: u16 = casts::const_as!(0x10000u32 => u16);
+/// ```
+///
+/// Conversions that alter the value also fail to build:
+///
+/// ```ignore,compile_fail
+/// # use kernel::num::casts;
+/// // Fails to build: `-1i64 as u64` yields `u64::MAX`.
+/// const V: u64 = casts::const_as!(-1i64 => u64);
+/// ```
+///
+/// Runtime values are rejected:
+///
+/// ```ignore,compile_fail
+/// # use kernel::num::casts;
+/// fn f(v: u32) -> u16 {
+///     // Fails to build: `v` is not a constant expression.
+///     casts::const_as!(v => u16)
+/// }
+/// ```
+#[macro_export]
+#[doc(hidden)]
+macro_rules! const_as {
+    ($v:expr => $into:ty) => {
+        const {
+            #[allow(unused_comparisons, unused_assignments, clippy::as_underscore)]
+            {
+                let v = $v;
+                let r = v as $into;
+                // Pin `back` to `v`'s type so `as _` casts back to the source type.
+                let mut back = v;
+                back = r as _;
 
-                N as $into
+                ::core::assert!(
+                    back == v && (v < 0) == (r < 0),
+                    "value does not fit into the target type"
+                );
+
+                r
             }
         }
-        )*
     };
 }
-
-impl_const_into!(usize => { u8, u16, u32 });
-impl_const_into!(u64 => { u8, u16, u32 });
-impl_const_into!(u32 => { u8, u16 });
-impl_const_into!(u16 => { u8 });
+#[doc(inline)]
+pub use const_as;
 
 /// Conversions that are only lossless for the current architecture.
 ///
Signature · 1 line
2.55.0
#2 lore raw
Quoted 35 lines · Alexandre Courbot

The casts module features a series of const converters (e.g. u32_into_u16) that narrow the type of a const expression provided that its value can be proven to fit into the destination type at compile-time.

These functions are numerous (9 of them), generated by a macro and thus not easily discoverable, and cumbersome to use as they require a turbofish and const expression between { and } braces.

Replace them all by a single const_as! macro that expands to a const block verifying the lossless nature of the conversion at compile-time. This turns e.g.:

    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);

This makes things easier to read and understand, while shifting the burden of checking the conversion's validity from reviewers (via a CAST comment) to the compiler.

---
 rust/kernel/num/casts.rs | 129 +++++++++++++++++++++++++++++------------------
 1 file changed, 79 insertions(+), 50 deletions(-)
rust/kernel/num/casts.rs +0 -0
index 7e6c7dec747d..a4a18a6f2ba8 100644
@@ -20,10 +20,8 @@
 //! - Two extension traits, [`FromSafeCast`] and [`IntoSafeCast`], providing conversion methods
 //!   similar to [`From`] and [`Into`] for conversions that are safe to perform in the kernel, but

rust/kernel/num/casts.rs line 27

Quoted 10 lines
rust/kernel/num/casts.rs +2 -4
 //!   not supported by the standard library.
-//! - Another series of const functions (e.g. [`u64_into_u8`]) supporting the conversion of a const
-//!   value from a larger type into a smaller one, provided the value fits into the destination
-//!   type. This is useful if a constant is defined as a larger type, but needs to be used as a
-//!   smaller one.
+//! - A [`const_as!`] macro, losslessly casting a constant expression between any two integer
+//!   types, with conversions that would alter the value reported as build errors.
 //! - An [`arch`] sub-module, defining more conversion functions that are only guaranteed to be
 //!   lossless for a given pointer size. These can only be used in code that is specific to a
 //!   given pointer size.

Can we add guidance somewhere in this file on when to use const_as! vs when to use the u8_as_usize etc ones, when both could work? e.g. use const_as! if you can, otherwise use the function version, or, use the function version if it's sufficient (types alone are enough to prove) otherwise use the macro.

[...]

Quoted 8 lines
rust/kernel/num/casts.rs +8 -0
+#[macro_export]
+#[doc(hidden)]
+macro_rules! const_as {
+    ($v:expr => $into:ty) => {
+        const {
+            #[allow(unused_comparisons, unused_assignments, clippy::as_underscore)]
+            {
+                let v = $v;

rust/kernel/num/casts.rs fn into_safe_cast(self) -> T { · line 256

Quoted 10 lines
rust/kernel/num/casts.rs +8 -1
+                let r = v as $into;
+                // Pin `back` to `v`'s type so `as _` casts back to the source type.
+                let mut back = v;
+                back = r as _;
 
-                N as $into
+                ::core::assert!(
+                    back == v && (v < 0) == (r < 0),
+                    "value does not fit into the target type"
+                );

What about giving some text on what doesn't fit where? e.g.
::core::concat!("", ::core::stringify!($v), " does not fit into ", ::core::stringify!($into), "")

author maintainer
#3 lore raw
Quoted 44 lines · Eliot Courtney
Quoted 43 lines · Alexandre Courbot

The casts module features a series of const converters (e.g. u32_into_u16) that narrow the type of a const expression provided that its value can be proven to fit into the destination type at compile-time.

These functions are numerous (9 of them), generated by a macro and thus not easily discoverable, and cumbersome to use as they require a turbofish and const expression between { and } braces.

Replace them all by a single const_as! macro that expands to a const block verifying the lossless nature of the conversion at compile-time. This turns e.g.:

    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);

This makes things easier to read and understand, while shifting the burden of checking the conversion's validity from reviewers (via a CAST comment) to the compiler.

---
 rust/kernel/num/casts.rs | 129 +++++++++++++++++++++++++++++------------------
 1 file changed, 79 insertions(+), 50 deletions(-)
rust/kernel/num/casts.rs +2 -4
index 7e6c7dec747d..a4a18a6f2ba8 100644
@@ -20,10 +20,8 @@
 //! - Two extension traits, [`FromSafeCast`] and [`IntoSafeCast`], providing conversion methods
 //!   similar to [`From`] and [`Into`] for conversions that are safe to perform in the kernel, but
 //!   not supported by the standard library.
-//! - Another series of const functions (e.g. [`u64_into_u8`]) supporting the conversion of a const
-//!   value from a larger type into a smaller one, provided the value fits into the destination
-//!   type. This is useful if a constant is defined as a larger type, but needs to be used as a
-//!   smaller one.
+//! - A [`const_as!`] macro, losslessly casting a constant expression between any two integer
+//!   types, with conversions that would alter the value reported as build errors.
 //! - An [`arch`] sub-module, defining more conversion functions that are only guaranteed to be
Quoted 8 lines

rust/kernel/num/casts.rs line 27

Quoted 2 lines
rust/kernel/num/casts.rs +0 -0
 //!   lossless for a given pointer size. These can only be used in code that is specific to a
 //!   given pointer size.

Can we add guidance somewhere in this file on when to use const_as! vs when to use the u8_as_usize etc ones, when both could work? e.g. use const_as! if you can, otherwise use the function version, or, use the function version if it's sufficient (types alone are enough to prove) otherwise use the macro.

Yes, that's a very good idea and the use we are currently doing in Nova is also not consistent. Basically I think that the priority should be, in order of preference:

- stdlib's From,
- FromSafeCast/IntoSafeCast (for non-const contexts)
- const_as! (for constant expressions including narrowing)
- *_as_* (for const fns with a runtime value)

Quoted 15 lines

[...]

Quoted 13 lines
rust/kernel/num/casts.rs +12 -0
+#[macro_export]
+#[doc(hidden)]
+macro_rules! const_as {
+    ($v:expr => $into:ty) => {
+        const {
+            #[allow(unused_comparisons, unused_assignments, clippy::as_underscore)]
+            {
+                let v = $v;
+                let r = v as $into;
+                // Pin `back` to `v`'s type so `as _` casts back to the source type.
+                let mut back = v;
+                back = r as _;
Quoted 8 lines

rust/kernel/num/casts.rs fn into_safe_cast(self) -> T { · line 256

Quoted 5 lines
rust/kernel/num/casts.rs +4 -1
-                N as $into
+                ::core::assert!(
+                    back == v && (v < 0) == (r < 0),
+                    "value does not fit into the target type"
+                );

What about giving some text on what doesn't fit where? e.g.
::core::concat!("", ::core::stringify!($v), " does not fit into ", ::core::stringify!($into), "")

Will do.

author maintainer
#4 lore raw
Quoted 87 lines · Alexandre Courbot
Quoted 44 lines · Eliot Courtney
Quoted 43 lines · Alexandre Courbot

The casts module features a series of const converters (e.g. u32_into_u16) that narrow the type of a const expression provided that its value can be proven to fit into the destination type at compile-time.

These functions are numerous (9 of them), generated by a macro and thus not easily discoverable, and cumbersome to use as they require a turbofish and const expression between { and } braces.

Replace them all by a single const_as! macro that expands to a const block verifying the lossless nature of the conversion at compile-time. This turns e.g.:

    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);

This makes things easier to read and understand, while shifting the burden of checking the conversion's validity from reviewers (via a CAST comment) to the compiler.

---
 rust/kernel/num/casts.rs | 129 +++++++++++++++++++++++++++++------------------
 1 file changed, 79 insertions(+), 50 deletions(-)
rust/kernel/num/casts.rs +2 -4
index 7e6c7dec747d..a4a18a6f2ba8 100644
@@ -20,10 +20,8 @@
 //! - Two extension traits, [`FromSafeCast`] and [`IntoSafeCast`], providing conversion methods
 //!   similar to [`From`] and [`Into`] for conversions that are safe to perform in the kernel, but
 //!   not supported by the standard library.
-//! - Another series of const functions (e.g. [`u64_into_u8`]) supporting the conversion of a const
-//!   value from a larger type into a smaller one, provided the value fits into the destination
-//!   type. This is useful if a constant is defined as a larger type, but needs to be used as a
-//!   smaller one.
+//! - A [`const_as!`] macro, losslessly casting a constant expression between any two integer
+//!   types, with conversions that would alter the value reported as build errors.
 //! - An [`arch`] sub-module, defining more conversion functions that are only guaranteed to be
Quoted 8 lines

rust/kernel/num/casts.rs line 27

Quoted 2 lines
rust/kernel/num/casts.rs +0 -0
 //!   lossless for a given pointer size. These can only be used in code that is specific to a
 //!   given pointer size.

Can we add guidance somewhere in this file on when to use const_as! vs when to use the u8_as_usize etc ones, when both could work? e.g. use const_as! if you can, otherwise use the function version, or, use the function version if it's sufficient (types alone are enough to prove) otherwise use the macro.

Yes, that's a very good idea and the use we are currently doing in Nova is also not consistent. Basically I think that the priority should be, in order of preference:

- stdlib's From,
- FromSafeCast/IntoSafeCast (for non-const contexts)
- const_as! (for constant expressions including narrowing)
- *_as_* (for const fns with a runtime value)

Quoted 15 lines

[...]

Quoted 13 lines
rust/kernel/num/casts.rs +12 -0
+#[macro_export]
+#[doc(hidden)]
+macro_rules! const_as {
+    ($v:expr => $into:ty) => {
+        const {
+            #[allow(unused_comparisons, unused_assignments, clippy::as_underscore)]
+            {
+                let v = $v;
+                let r = v as $into;
+                // Pin `back` to `v`'s type so `as _` casts back to the source type.
+                let mut back = v;
+                back = r as _;
Quoted 8 lines

rust/kernel/num/casts.rs fn into_safe_cast(self) -> T { · line 256

Quoted 5 lines
rust/kernel/num/casts.rs +4 -1
-                N as $into
+                ::core::assert!(
+                    back == v && (v < 0) == (r < 0),
+                    "value does not fit into the target type"
+                );

What about giving some text on what doesn't fit where? e.g.
::core::concat!("", ::core::stringify!($v), " does not fit into ", ::core::stringify!($into), "")

Quoted 1 line

Will do.

... actually, that's probably not needed. Compiler diagnostics already print the faulting line verbatim, so the expression is fully visible. Stringifying it would just duplicate information that sits on the very next line.

#5 lore raw
In reply to Alexandre Courbot
Quoted 6 lines · Alexandre Courbot
    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);

Hmm... I have been following the discussion and listening to both sides of the argument.

The macro interface looks obvious enough, and we could consider adding it to the prelude.

Having said that, macros have a cost too when they introduce new "syntax", so since the beginning we have tried to minimize their use to where we feel is worth it.

The former line above is not perfect by any means, but it is nevertheless syntax that one needs to already know. Personally speaking, I don't care if I have to write the former or the latter, to be honest, so I am OK with both ways. But I worked with C++ TMP in the past, so my eyes may be desensitized. :)

Apart from readability concerns, we are saving here a few characters; getting possibly different codegen (forced textual inline), and maybe having better or worse compiler-side time/memory/disk numbers. Is that about it? It would be good to measure any actual difference.

What I wouldn't want is a raw as, because the point of the saga we started a long time ago is to introduce better tools that allow us to get rid of the almighty as into weaker (i.e. safer) options, even if some uses of as may be "obviously right".

Cheers,
Miguel

reviewer
#6 lore raw
Quoted 18 lines · Miguel Ojeda
Quoted 6 lines · Alexandre Courbot
    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);

Hmm... I have been following the discussion and listening to both sides of the argument.

The macro interface looks obvious enough, and we could consider adding it to the prelude.

Having said that, macros have a cost too when they introduce new "syntax", so since the beginning we have tried to minimize their use to where we feel is worth it.

Quoted 5 lines

The former line above is not perfect by any means, but it is nevertheless syntax that one needs to already know. Personally speaking, I don't care if I have to write the former or the latter, to be honest, so I am OK with both ways. But I worked with C++ TMP in the past, so my eyes may be desensitized. :)

What I have issue with is to have things that do not belong to the type system in const generics. Expressive power is really limited in it, so any expressions involving generic parameter, for example, won't be usable inside the turbofish. It also doesn't work for custom types, so the approach does not generalize.

The type/value distinction is one of the biggest change I made to const {} implementation, many features of const {} is possible (e.g. reference to generic parameter freely) precisely because values don't flow to the type system.

Yes const_generic_exprs is being worked on and it'll blur the line between type and values. But we're not there yet, and I think it still worth having a clear distinction and we don't put things that don't need to be in the type system there.

Quoted 5 lines

Apart from readability concerns, we are saving here a few characters; getting possibly different codegen (forced textual inline), and maybe having better or worse compiler-side time/memory/disk numbers. Is that about it? It would be good to measure any actual difference.

The macros are much better than functions in my opinion, because it compose well with the type system. The all "foo_as_bar" methods also compose poorly with type alias, where this macro doesn't have that issue. Also, values no longer end up in the type system to begin with.

Quoted 5 lines

What I wouldn't want is a raw as, because the point of the saga we started a long time ago is to introduce better tools that allow us to get rid of the almighty as into weaker (i.e. safer) options, even if some uses of as may be "obviously right".

I think that is rather a linting issue, not something that warrants extra code in kernel. We have been requesting some extra clippy features and I think that is the correct way to go, not add a ton of methods and macros. Yes, it wasn't moving on clippy end, but I could add a feature to klint instead?

Do you think we still need all these extra function and macros if we can get clippy (or klint) to enforce CAST comments?

I can imagine the following rules that would practically solve all the footgun of as numerical casts without having to use awkward syntax:

* widening casts are allowed
* narrowing casts is disallowed unless CAST comment exists, except where its value is constant and truncation does not happen.

Best,
Gary

author maintainer
#7 lore raw
Quoted 14 lines · Gary Guo
Quoted 4 lines · Miguel Ojeda

What I wouldn't want is a raw as, because the point of the saga we started a long time ago is to introduce better tools that allow us to get rid of the almighty as into weaker (i.e. safer) options, even if some uses of as may be "obviously right".

I think that is rather a linting issue, not something that warrants extra code in kernel. We have been requesting some extra clippy features and I think that is the correct way to go, not add a ton of methods and macros. Yes, it wasn't moving on clippy end, but I could add a feature to klint instead?

Do you think we still need all these extra function and macros if we can get clippy (or klint) to enforce CAST comments?

Quoted 6 lines

I can imagine the following rules that would practically solve all the footgun of as numerical casts without having to use awkward syntax:

* widening casts are allowed
* narrowing casts is disallowed unless CAST comment exists, except where its value is constant and truncation does not happen.

These rules classify casts by width, but the footguns really are about which values are actually being converted.

In particular for value narrowing we still end up with CAST comments, whose existence a lint can check, but not their correctness (for instance, a bindgen-provided constant that changes in a breaking way). const_as! lets us drop them altogether.

reviewer
#8 lore raw
Quoted 22 lines · Alexandre Courbot
Quoted 14 lines · Gary Guo
Quoted 4 lines · Miguel Ojeda

What I wouldn't want is a raw as, because the point of the saga we started a long time ago is to introduce better tools that allow us to get rid of the almighty as into weaker (i.e. safer) options, even if some uses of as may be "obviously right".

I think that is rather a linting issue, not something that warrants extra code in kernel. We have been requesting some extra clippy features and I think that is the correct way to go, not add a ton of methods and macros. Yes, it wasn't moving on clippy end, but I could add a feature to klint instead?

Do you think we still need all these extra function and macros if we can get clippy (or klint) to enforce CAST comments?

Quoted 6 lines

I can imagine the following rules that would practically solve all the footgun of as numerical casts without having to use awkward syntax:

* widening casts are allowed
* narrowing casts is disallowed unless CAST comment exists, except where its value is constant and truncation does not happen.

Quoted 7 lines

These rules classify casts by width, but the footguns really are about which values are actually being converted.

In particular for value narrowing we still end up with CAST comments, whose existence a lint can check, but not their correctness (for instance, a bindgen-provided constant that changes in a breaking way). const_as! lets us drop them altogether.

The rule says "except where its value is constant and truncation does not happen".

So I'd imagine just writing

bindings::FOO as u32

and *NOT* have CAST comment, and a warning being generated if truncation happens.

Best,
Gary

author maintainer
#9 lore raw
Quoted 34 lines · Gary Guo
Quoted 22 lines · Alexandre Courbot
Quoted 14 lines · Gary Guo
Quoted 4 lines · Miguel Ojeda

What I wouldn't want is a raw as, because the point of the saga we started a long time ago is to introduce better tools that allow us to get rid of the almighty as into weaker (i.e. safer) options, even if some uses of as may be "obviously right".

I think that is rather a linting issue, not something that warrants extra code in kernel. We have been requesting some extra clippy features and I think that is the correct way to go, not add a ton of methods and macros. Yes, it wasn't moving on clippy end, but I could add a feature to klint instead?

Do you think we still need all these extra function and macros if we can get clippy (or klint) to enforce CAST comments?

Quoted 6 lines

I can imagine the following rules that would practically solve all the footgun of as numerical casts without having to use awkward syntax:

* widening casts are allowed
* narrowing casts is disallowed unless CAST comment exists, except where its value is constant and truncation does not happen.

Quoted 7 lines

These rules classify casts by width, but the footguns really are about which values are actually being converted.

In particular for value narrowing we still end up with CAST comments, whose existence a lint can check, but not their correctness (for instance, a bindgen-provided constant that changes in a breaking way). const_as! lets us drop them altogether.

The rule says "except where its value is constant and truncation does not happen".

Quoted 6 lines

So I'd imagine just writing

bindings::FOO as u32

and *NOT* have CAST comment, and a warning being generated if truncation happens.

I can see a use for a lint that warns about as expressions without a CAST comment, yes. But the warning should be unconditional imho - otherwise an as without a CAST comment could be intended as non-truncating, or it could just be an omission from the author of the code, and there is no good way to tell.

const_as! basically provides everything we need to document intent and verify the behavior of non-truncating casts, and I think it is useful to keep as much as possible at the compiler level. KLint is not part of a regular build, and enabling it involves some effort that not everybody will go through. const_as! emits an error exactly when we need it to, without any extra tool, and is both simple in its implementation and its use.

I am also not sure whether KLint could cover something like this, that requires post-monomorphization analysis:

    fn f<const N: usize>() -> u16 {
        N as u16
    }

Generally speaking, I believe a sane policy is to delegate tasks to the lowest layer that can do the job. Here the compiler is clearly capable.

reviewer
#10 lore raw
Quoted 39 lines · Alexandre Courbot
Quoted 38 lines · Gary Guo
Quoted 22 lines · Alexandre Courbot
Quoted 14 lines · Gary Guo
Quoted 4 lines · Miguel Ojeda

What I wouldn't want is a raw as, because the point of the saga we started a long time ago is to introduce better tools that allow us to get rid of the almighty as into weaker (i.e. safer) options, even if some uses of as may be "obviously right".

I think that is rather a linting issue, not something that warrants extra code in kernel. We have been requesting some extra clippy features and I think that is the correct way to go, not add a ton of methods and macros. Yes, it wasn't moving on clippy end, but I could add a feature to klint instead?

Do you think we still need all these extra function and macros if we can get clippy (or klint) to enforce CAST comments?

Quoted 6 lines

I can imagine the following rules that would practically solve all the footgun of as numerical casts without having to use awkward syntax:

* widening casts are allowed
* narrowing casts is disallowed unless CAST comment exists, except where its value is constant and truncation does not happen.

Quoted 7 lines

These rules classify casts by width, but the footguns really are about which values are actually being converted.

In particular for value narrowing we still end up with CAST comments, whose existence a lint can check, but not their correctness (for instance, a bindgen-provided constant that changes in a breaking way). const_as! lets us drop them altogether.

The rule says "except where its value is constant and truncation does not happen".

So I'd imagine just writing

bindings::FOO as u32

Quoted 8 lines
Quoted 2 lines

and *NOT* have CAST comment, and a warning being generated if truncation happens.

I can see a use for a lint that warns about as expressions without a CAST comment, yes. But the warning should be unconditional imho - otherwise an as without a CAST comment could be intended as non-truncating, or it could just be an omission from the author of the code, and there is no good way to tell.

I think a "no comment means no truncation is going to happen" enforced by linter is the point? I'd use "unsafe" as the parallel analogy. You don't see if a function is unsafe or not, you use the absence of "unsafe" block as a guarantee that there's no unsafe code within a block.

Quoted 8 lines

const_as! basically provides everything we need to document intent and verify the behavior of non-truncating casts, and I think it is useful to keep as much as possible at the compiler level. KLint is not part of a regular build, and enabling it involves some effort that not everybody will go through. const_as! emits an error exactly when we need it to, without any extra tool, and is both simple in its implementation and its use.

Enabling it is quite easy actually, just that it is more involved to package if one is not using rustup nor nix. Once it's installed the only thing needed is a RUSTC=klint in make command line.

The bare installation does not however allow you to name the lints so everything is at the default level and you cannot suppress it. The required feature register_tool is being worked on and I intend to upstream klint support some time this year.

Also, as long as we have CI systems to do a build, I think it's not necessary for everyone to run it themselves.

Quoted 7 lines

I am also not sure whether KLint could cover something like this, that requires post-monomorphization analysis:

    fn f<const N: usize>() -> u16 {
        N as u16
    }

So for clippy (and likely klint if it implements the feature), it would be done pre-mono so it would require a CAST comment without checking.

Quoted 3 lines

Generally speaking, I believe a sane policy is to delegate tasks to the lowest layer that can do the job. Here the compiler is clearly capable.

That's why I want to get the task done by clippy/klint instead. Because it *is* the compiler, which is lower layer than a macro.

Best,
Gary

author maintainer
#11 lore raw
In reply to Miguel Ojeda
Quoted 11 lines · Miguel Ojeda
Quoted 6 lines · Alexandre Courbot
    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);

Hmm... I have been following the discussion and listening to both sides of the argument.

Quoted 6 lines

The macro interface looks obvious enough, and we could consider adding it to the prelude.

Having said that, macros have a cost too when they introduce new "syntax", so since the beginning we have tried to minimize their use to where we feel is worth it.

Ideally we could write it like const_as!(MEM_BLOCK_ALIGNMENT as u32) but unfortunately declarative macros won't let us do that. That being said there might be a better syntax.

Quoted 6 lines

The former line above is not perfect by any means, but it is nevertheless syntax that one needs to already know. Personally speaking, I don't care if I have to write the former or the latter, to be honest, so I am OK with both ways. But I worked with C++ TMP in the past, so my eyes may be desensitized. :)

I also don't mind the turbofish. Actually I like how it unambiguously signals that something is evaluated at build time. But in this case the macro seems justified to me as we are trading 9 different macro-generated declarations for a single one that is much more obvious to discover and use. The declaration site of the previous helpers was a paste-party that is difficult to read and edit.

const_as! also has the benefit that it can probably survive the TryFrom constification, as I don't believe we will want users to sprinkle unwraps in their const blocks.

Another bonus, especially if we add it to the prelude: const_as! also covers expanding conversions, so we can also replace many of the e.g. u8_as_u32 calls with it, with FromSafeCast covering the non-const cases. This leaves the *_as_* family of functions only needed for const fns that need to expand a parameter, for which there are no in-tree users at the moment.

Quoted 5 lines

Apart from readability concerns, we are saving here a few characters; getting possibly different codegen (forced textual inline), and maybe having better or worse compiler-side time/memory/disk numbers. Is that about it? It would be good to measure any actual difference.

I don't expect much difference between the two, but will try to gather some metrics for v2.

maintainer
#12 lore raw
In reply to Miguel Ojeda
Quoted 8 lines · Miguel Ojeda
Quoted 6 lines · Alexandre Courbot
    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);
Quoted 8 lines

Having said that, macros have a cost too when they introduce new "syntax", so since the beginning we have tried to minimize their use to where we feel is worth it.

The former line above is not perfect by any means, but it is nevertheless syntax that one needs to already know. Personally speaking, I don't care if I have to write the former or the latter, to be honest, so I am OK with both ways.

As mentioned in [1], I also think it's not great, but I also don't mind having it as is for now.

I guess my main question is how we expect this to evolve. How do we want this to look like once we have things like const function arguments or const trait methods? Is it worth getting back and forth on a macro solution with this in mind?

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

reviewer
#13 lore raw
Quoted 18 lines · Danilo Krummrich
Quoted 8 lines · Miguel Ojeda
Quoted 6 lines · Alexandre Courbot
    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);
Quoted 8 lines

Having said that, macros have a cost too when they introduce new "syntax", so since the beginning we have tried to minimize their use to where we feel is worth it.

The former line above is not perfect by any means, but it is nevertheless syntax that one needs to already know. Personally speaking, I don't care if I have to write the former or the latter, to be honest, so I am OK with both ways.

Quoted 7 lines

As mentioned in [1], I also think it's not great, but I also don't mind having it as is for now.

I guess my main question is how we expect this to evolve. How do we want this to look like once we have things like const function arguments or const trait methods? Is it worth getting back and forth on a macro solution with this in mind?

It's easier to evolve with macros. Once we have const trait, the cast becomes

    const { from_expr.try_into().unwrap() }

or

    const { TargetType::try_from(from_expr).unwrap() }

which we can just change the macro to expand to.

That said, whether we want raw

    const { u32::try_from(MEM_BLOCK_ALIGNMENT).unwrap() }

vs

    const_as!(MEM_BLOCK_ALIGNMENT => u32)

is a different question. We probably can have a const_try!() macro that unwraps both Option and Result in const eval so write

    const_try!(u32::try_from(MEM_BLOCK_ALIGNMENT))

or

const_try!(MEM_BLOCK_ALIGNMENT.try_into())

Regardless, the "ultimate state" is not going to be turbofish and would take a form of expression syntax wrapped in const block.

Best,
Gary

author maintainer
#14 lore raw
In reply to Danilo Krummrich
Quoted 18 lines · Danilo Krummrich
Quoted 8 lines · Miguel Ojeda
Quoted 6 lines · Alexandre Courbot
    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);
Quoted 8 lines

Having said that, macros have a cost too when they introduce new "syntax", so since the beginning we have tried to minimize their use to where we feel is worth it.

The former line above is not perfect by any means, but it is nevertheless syntax that one needs to already know. Personally speaking, I don't care if I have to write the former or the latter, to be honest, so I am OK with both ways.

Quoted 7 lines

As mentioned in [1], I also think it's not great, but I also don't mind having it as is for now.

I guess my main question is how we expect this to evolve. How do we want this to look like once we have things like const function arguments or const trait methods? Is it worth getting back and forth on a macro solution with this in mind?

I've thought about this a bit actually. Let's imagine we have a const TryFrom trait. Even with that, we probably won't want users to do e.g. u8::try_from(SOME_U32_CONST).unwrap() every time they need to narrow something (if only because it would translate into a runtime panic if somehow moved outside of a const block).

So for the same reason we are considering nz! to build non-zero values efficiently, I expect const_as! to remain around in some capacity, which should make the transition invisible to users.

reviewer Reviewed-by on v1 1/2
#15 lore raw
In reply to Alexandre Courbot
Quoted 15 lines · Alexandre Courbot

The casts module features a series of const converters (e.g. u32_into_u16) that narrow the type of a const expression provided that its value can be proven to fit into the destination type at compile-time.

These functions are numerous (9 of them), generated by a macro and thus not easily discoverable, and cumbersome to use as they require a turbofish and const expression between { and } braces.

Replace them all by a single const_as! macro that expands to a const block verifying the lossless nature of the conversion at compile-time. This turns e.g.:

    const DMA_LEN: u32 = casts::usize_into_u32::<{ MEM_BLOCK_ALIGNMENT }>();
Quoted 7 lines

into

    const DMA_LEN: u32 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);

This makes things easier to read and understand, while shifting the burden of checking the conversion's validity from reviewers (via a CAST comment) to the compiler.

Thanks, I like this much better than the methods (for reasons that I explained in my reply to Miguel), and also that this looks nicer.

Quoted 5 lines
---
 rust/kernel/num/casts.rs | 129 +++++++++++++++++++++++++++++------------------
 1 file changed, 79 insertions(+), 50 deletions(-)
author maintainer
#16 lore raw

PATCH 2/2 gpu: nova-core: use kernel lossless integer conversion module

In reply to Alexandre Courbot

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

---
 drivers/gpu/nova-core/falcon.rs                    |  12 +-
 drivers/gpu/nova-core/falcon/fsp.rs                |   4 +-
 drivers/gpu/nova-core/fb.rs                        |   2 +-
 drivers/gpu/nova-core/fb/hal/gb100.rs              |   9 +-
 drivers/gpu/nova-core/firmware.rs                  |   4 +-
 drivers/gpu/nova-core/firmware/booter.rs           |   4 +-
 drivers/gpu/nova-core/firmware/fwsec.rs            |   2 +-
 drivers/gpu/nova-core/firmware/fwsec/bootloader.rs |   4 +-
 drivers/gpu/nova-core/firmware/gsp.rs              |   9 +-
 drivers/gpu/nova-core/firmware/tlv.rs              |  11 +-
 drivers/gpu/nova-core/fsp.rs                       |   8 +-
 drivers/gpu/nova-core/gsp.rs                       |   4 +-
 drivers/gpu/nova-core/gsp/cmdq.rs                  |  22 +--
 drivers/gpu/nova-core/gsp/fw.rs                    |  50 ++---
 drivers/gpu/nova-core/gsp/fw/commands.rs           |   4 +-
 drivers/gpu/nova-core/gsp/sequencer.rs             |   2 +-
 drivers/gpu/nova-core/mctp.rs                      |   8 +-
 drivers/gpu/nova-core/num.rs                       | 211 ---------------------
 drivers/gpu/nova-core/vbios.rs                     |   2 +-
 19 files changed, 84 insertions(+), 288 deletions(-)
drivers/gpu/nova-core/falcon.rs +6 -6
index 65cb12d26e2b..eb54aa41e8bf 100644
@@ -20,6 +20,10 @@
         },
         Io,
     },
+    num::casts::{
+        self,
+        FromSafeCast, //
+    },
     prelude::*,
     time::Delta,
 };
@@ -29,11 +33,7 @@
     driver::Bar0,
     falcon::hal::LoadMethod,
     gpu::Chipset,
-    num::{
-        self,
-        FromSafeCast, //
-    },
-    regs,
+    regs, //
 };
 
 pub(crate) mod fsp;
@@ -510,7 +510,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 = casts::const_as!(MEM_BLOCK_ALIGNMENT => u32);
 
         // DMA transfers can only be done in units of 256 bytes. Compute how many such transfers we
         // need to perform.
drivers/gpu/nova-core/falcon/fsp.rs +2 -2
index 0437180b8829..2470ac511c98 100644
@@ -16,6 +16,7 @@
         },
         Io, //
     },
+    num::casts,
     prelude::*,
     sizes::SZ_1K,
     time::Delta,
@@ -28,7 +29,6 @@
         PFalcon2Base,
         PFalconBase, //
     },
-    num,
     regs, //
 };
 
@@ -165,7 +165,7 @@ pub(crate) fn recv_msg(&mut self) -> Result<KVec<u8>> {
             Delta::from_millis(10),
             Delta::from_millis(FSP_MSG_TIMEOUT_MS),
         )
-        .map(num::u32_as_usize)?;
+        .map(casts::u32_as_usize)?;
 
         // Don't blindly allocate more than the maximum we expect from FSP.
         if msg_size > FSP_EMEM_CHANNEL_0_SIZE {
drivers/gpu/nova-core/fb.rs +1 -1
index 1576399389b1..8d5d9480378f 100644
@@ -10,6 +10,7 @@
     dma::CoherentHandle,
     fmt,
     io::Io,
+    num::casts::FromSafeCast,
     prelude::*,
     ptr::{
         Alignable,
@@ -23,7 +24,6 @@
     firmware::gsp::GspFirmware,
     gpu::Chipset,
     gsp,
-    num::FromSafeCast,
     vgpu::VgpuState, //
 };
 
drivers/gpu/nova-core/fb/hal/gb100.rs +6 -3
index d9e4d62ae632..8fb94696c715 100644
@@ -11,7 +11,10 @@
         },
         Io, //
     },
-    num::Bounded,
+    num::{
+        casts,
+        Bounded, //
+    },
     prelude::*,
     ptr::{
         const_align_up,
@@ -26,7 +29,6 @@
         hal::FbHal,
         regs, //
     },
-    num::usize_into_u32,
 };
 
 struct Gb100;
@@ -82,7 +84,8 @@ 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() }>(
+    casts::const_as!(
+        const_align_up(SZ_8M + SZ_16M + SZ_4K, Alignment::new::<SZ_128K>()).unwrap() => u32
     )
 }
 
drivers/gpu/nova-core/firmware.rs +2 -2
index b49613a90bf0..19f13779bb30 100644
@@ -9,6 +9,7 @@
 
 use kernel::{
     firmware,
+    num::casts::IntoSafeCast,
     prelude::*, //
 };
 
@@ -18,8 +19,7 @@
         FalconFirmware, //
     },
     gpu,
-    gsp::boot_firmware_files,
-    num::IntoSafeCast, //
+    gsp::boot_firmware_files, //
 };
 
 pub(crate) mod booter;
drivers/gpu/nova-core/firmware/booter.rs +2 -2
index dc071edba331..aa830455b7e7 100644
@@ -10,6 +10,7 @@
 use kernel::{
     device,
     dma::Coherent,
+    num::casts::IntoSafeCast,
     prelude::*, //
 };
 
@@ -32,8 +33,7 @@
         Signed,
         Unsigned, //
     },
-    gpu::Chipset,
-    num::IntoSafeCast,
+    gpu::Chipset, //
 };
 
 /// Signature for Booter firmware. Their size is encoded into the header and not known a compile
drivers/gpu/nova-core/firmware/fwsec.rs +1 -1
index 7a931f22f629..7f7ca3ba2298 100644
@@ -19,6 +19,7 @@
         self,
         Device, //
     },
+    num::casts::FromSafeCast,
     prelude::*,
     transmute::{
         AsBytes,
@@ -42,7 +43,6 @@
         Signed,
         Unsigned, //
     },
-    num::FromSafeCast,
     vbios::Vbios,
 };
 
drivers/gpu/nova-core/firmware/fwsec/bootloader.rs +2 -2
index ec4d92317a93..d1fb7d2d7480 100644
@@ -13,6 +13,7 @@
     },
     dma::Coherent,
     io::{register::WithBase, Io},
+    num::casts::FromSafeCast,
     prelude::*,
     ptr::{
         Alignable,
@@ -45,8 +46,7 @@
         },
     },
     gpu::Chipset,
-    num::FromSafeCast, //
-    regs,
+    regs, //
 };
 
 /// Structure used by the boot-loader to load the rest of the code.
drivers/gpu/nova-core/firmware/gsp.rs +6 -3
index e8f9491e84cc..e75ce6fe47d8 100644
@@ -9,6 +9,10 @@
         DmaAddress, //
     },
     firmware,
+    num::casts::{
+        arch::FromSafeCastArch,
+        FromSafeCast, //
+    },
     prelude::*,
     scatterlist::{
         Owned,
@@ -26,8 +30,7 @@
         },
     },
     gpu::Chipset,
-    gsp::GSP_PAGE_SIZE,
-    num::FromSafeCast,
+    gsp::GSP_PAGE_SIZE, //
 };
 
 /// GSP firmware with 3-level radix page tables for the GSP bootloader.
@@ -154,7 +157,7 @@ pub(crate) fn radix3_dma_address(&self) -> DmaAddress {
 fn map_into_lvl(sg_table: &SGTable<Owned<VVec<u8>>>, mut dst: VVec<u8>) -> Result<VVec<u8>> {
     for sg_entry in sg_table.iter() {
         // Number of pages we need to map.
-        let num_pages = usize::from_safe_cast(sg_entry.dma_len()).div_ceil(GSP_PAGE_SIZE);
+        let num_pages = usize::from_safe_cast_arch(sg_entry.dma_len()).div_ceil(GSP_PAGE_SIZE);
 
         for i in 0..num_pages {
             let entry = sg_entry.dma_address()
drivers/gpu/nova-core/firmware/tlv.rs +6 -5
index 7b879f13a61e..6653c10e3e0a 100644
@@ -4,14 +4,15 @@
 use kernel::{
     device,
     firmware,
+    num::casts::{
+        self,
+        IntoSafeCast, //
+    },
     prelude::*,
     str::CString, //
 };
 
-use crate::{
-    gpu,
-    num::*, //
-};
+use crate::gpu;
 
 /// Requests the GPU firmware TLV `name` suitable for `chipset`.
 pub(crate) fn request_tlv(
@@ -51,7 +52,7 @@ fn parse(hdr: &[u8]) -> Option<Self> {
             return None;
         }
         let len_arr = <[u8; 4]>::try_from(hdr.get(4..Self::SIZE)?).ok()?;
-        let length = u32_as_usize(u32::from_le_bytes(len_arr));
+        let length = casts::u32_as_usize(u32::from_le_bytes(len_arr));
         Some(Self { tag, length })
     }
 }
drivers/gpu/nova-core/fsp.rs +5 -3
index ab685fb4168f..bd8505addd25 100644
@@ -11,7 +11,10 @@
     device,
     dma::Coherent,
     io::poll::read_poll_timeout,
-    num::TryIntoBounded,
+    num::{
+        casts,
+        TryIntoBounded, //
+    },
     prelude::*,
     ptr::{
         Alignable,
@@ -47,7 +50,6 @@
         NvdmHeader,
         NvdmType, //
     },
-    num,
     regs, //
 };
 
@@ -285,7 +287,7 @@ fn new<'a>(
         };
 
         let version = hal.cot_version();
-        let size = num::usize_into_u16::<{ core::mem::size_of::<NvdmPayloadCot>() }>();
+        let size = casts::const_as!(core::mem::size_of::<NvdmPayloadCot>() => u16);
 
         Ok(init!(Self {
             header: FspMessageHeader::new(NvdmType::Cot),
drivers/gpu/nova-core/gsp.rs +2 -2
index 13f361406a6c..fc8648de84c2 100644
@@ -17,6 +17,7 @@
         io_write,
         Io, //
     },
+    num::casts,
     pci,
     prelude::*, //
 };
@@ -48,7 +49,6 @@
         cmdq::Cmdq,
         fw::GspArgumentsPadded, //
     },
-    num,
     vgpu::VgpuManager, //
 };
 
@@ -92,7 +92,7 @@ fn init(view: CoherentView<'_, Self>, start: DmaAddress) -> Result<()> {
         for i in 0..NUM_PAGES {
             io_write!(view, .0[build: i],
                 start
-                    .checked_add(num::usize_as_u64(i) << GSP_PAGE_SHIFT)
+                    .checked_add(casts::usize_as_u64(i) << GSP_PAGE_SHIFT)
                     .ok_or(EOVERFLOW)?
             );
         }
drivers/gpu/nova-core/gsp/cmdq.rs +11 -11
index 6da728201281..99e775f6071e 100644
@@ -23,6 +23,7 @@
         Io, //
     },
     new_mutex,
+    num::casts,
     prelude::*,
     ptr,
     sync::{
@@ -57,7 +58,6 @@
         GSP_PAGE_SHIFT,
         GSP_PAGE_SIZE, //
     },
-    num,
     sbuffer::SBufferIter, //
 };
 
@@ -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]; casts::u32_as_usize(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 = casts::const_as!(size_of::<Msgq>() => u32);
+        const RX_HDR_OFF: u32 = casts::const_as!(mem::offset_of!(Msgq, rx) => u32);
 
         let mut gsp_mem = CoherentBox::<GspMem>::zeroed(dev, GFP_KERNEL)?;
         gsp_mem.cpuq.tx = MsgqTxHeader::new(MSGQ_SIZE, RX_HDR_OFF, MSGQ_NUM_PAGES);
@@ -289,10 +289,10 @@ fn new(dev: &device::Device<device::Bound>) -> Result<Self> {
         unsafe {
             (
                 core::slice::from_raw_parts_mut(
-                    data.add(num::u32_as_usize(tx)),
-                    num::u32_as_usize(tail_end - tx),
+                    data.add(casts::u32_as_usize(tx)),
+                    casts::u32_as_usize(tail_end - tx),
                 ),
-                core::slice::from_raw_parts_mut(data, num::u32_as_usize(wrap_end)),
+                core::slice::from_raw_parts_mut(data, casts::u32_as_usize(wrap_end)),
             )
         }
     }
@@ -307,7 +307,7 @@ fn driver_write_area_size(&self) -> usize {
         // `cpu_write_ptr`. The minimum value case is where `rx == 0` and `tx == MSGQ_NUM_PAGES -
         // 1`, which gives `0 + MSGQ_NUM_PAGES - (MSGQ_NUM_PAGES - 1) - 1 == 0`.
         let slots = (rx + MSGQ_NUM_PAGES - tx - 1) % MSGQ_NUM_PAGES;
-        num::u32_as_usize(slots) * GSP_PAGE_SIZE
+        casts::u32_as_usize(slots) * GSP_PAGE_SIZE
     }
 
     /// Returns the region of the GSP message queue that the driver is currently allowed to read
@@ -343,10 +343,10 @@ fn driver_write_area_size(&self) -> usize {
         unsafe {
             (
                 core::slice::from_raw_parts(
-                    data.add(num::u32_as_usize(rx)),
-                    num::u32_as_usize(tail_end - rx),
+                    data.add(casts::u32_as_usize(rx)),
+                    casts::u32_as_usize(tail_end - rx),
                 ),
-                core::slice::from_raw_parts(data, num::u32_as_usize(wrap_end)),
+                core::slice::from_raw_parts(data, casts::u32_as_usize(wrap_end)),
             )
         }
     }
drivers/gpu/nova-core/gsp/fw.rs +25 -25

113 lines not on this page · raw message

drivers/gpu/nova-core/gsp/fw/commands.rs +2 -2
index 6dc31d1bf5ae..201594fa437b 100644
@@ -5,6 +5,7 @@
 
 use kernel::{
     device,
+    num::casts::IntoSafeCast,
     pci,
     prelude::*,
     transmute::{
@@ -15,8 +16,7 @@
 
 use crate::{
     gpu::Chipset,
-    gsp::GSP_PAGE_SIZE,
-    num::IntoSafeCast, //
+    gsp::GSP_PAGE_SIZE, //
 };
 
 use super::bindings;
drivers/gpu/nova-core/gsp/sequencer.rs +1 -1
index bcad1421953a..fed881ba80b0 100644
@@ -11,6 +11,7 @@
         poll::read_poll_timeout,
         Io, //
     },
+    num::casts::FromSafeCast,
     prelude::*,
     time::{
         delay::fsleep,
@@ -35,7 +36,6 @@
         GspBootContext,
         LibosMemoryRegionInitArgument, //
     },
-    num::FromSafeCast,
     sbuffer::SBufferIter,
 };
 
drivers/gpu/nova-core/mctp.rs +3 -5
index 90c642c91a72..67f64ac2b8d1 100644
@@ -9,14 +9,12 @@
 
 use kernel::{
     bitfield,
+    num::casts,
     pci::Vendor,
     prelude::*, //
 };
 
-use crate::{
-    bounded_enum,
-    num, //
-};
+use crate::bounded_enum;
 
 bounded_enum! {
     /// NVDM message type identifiers carried over MCTP.
@@ -76,7 +74,7 @@ impl NvdmHeader {
     /// Builds an NVDM header for the given message type.
     pub(crate) fn new(nvdm_type: NvdmType) -> Self {
         Self::zeroed()
-            .with_const_msg_type::<{ num::u8_as_u32(MSG_TYPE_VENDOR_PCI) }>()
+            .with_const_msg_type::<{ casts::u8_as_u32(MSG_TYPE_VENDOR_PCI) }>()
             .with_vendor_id(Vendor::NVIDIA.as_raw())
             .with_nvdm_type(nvdm_type)
     }
drivers/gpu/nova-core/num.rs +0 -211

217 lines not on this page · raw message

drivers/gpu/nova-core/vbios.rs +1 -1
index c03650ee5226..7a2ee29cbb91 100644
@@ -5,6 +5,7 @@
 use kernel::{
     device,
     io::Io,
+    num::casts::FromSafeCast,
     prelude::*,
     ptr::{
         Alignable,
@@ -23,7 +24,6 @@
         FalconUCodeDescV2,
         FalconUCodeDescV3, //
     },
-    num::FromSafeCast,
 };
 
 /// BIOS Image Type from PCI Data Structure code_type field.
Signature · 1 line
2.55.0
Reviewed-by on v1 2/2
#17 lore raw

Re: [PATCH 2/2] gpu: nova-core: use kernel lossless integer conversion module

Quoted 5 lines · Alexandre Courbot

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

---

nit: casts:: prefix feels noisy to me in actual usages - just import const_as!, etc and use them directly?

author maintainer
#18 lore raw

Re: [PATCH 2/2] gpu: nova-core: use kernel lossless integer conversion module

Quoted 9 lines · Eliot Courtney
Quoted 5 lines · Alexandre Courbot

The kernel crate now features a replacement for our lossless integer conversion routines. Switch to the kernel version and remove our own.

---

nit: casts:: prefix feels noisy to me in actual usages - just import const_as!, etc and use them directly?

Yup, I used the prefix to keep the import list short because we were calling various *_as_* and *_into_* methods in some modules, but since we can convert all of them to either FromSafeCast or const_as, this is much more manageable so we'll be able to drop it.