Skip to contentSkip to conversation

rust: io: convert ResourceSize into a transparent newtype

PATCH Superseded Lorenzo Delgado 5 participants 8 messages Jul 12 – Jul 26

Subsystems (8)

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 rust: io: convert ResourceSize into a transparent newtype

ResourceSize was a bare type alias for resource_size_t, so it inherited every integer operation and as cast. That silently permits operations that are meaningless for the size of a hardware resource:
mixing it with unrelated integers and truncating casts.

Wrap it in a #[repr(transparent)] newtype so each conversion at a boundary becomes explicit and reviewable. The representation is unchanged, so this is ABI-identical; only the spelling at the FFI boundary changes. Provide the minimal conversion surface the call sites
need: from_raw/into_raw, From in both directions, and a fallible TryFrom<ResourceSize> for usize for the page-count site that can truncate on 32-bit. Update the two producers, Resource::size and SGEntry::dma_len, and the request_region and nova-core consumers so the tree builds green. Add doctest examples for the new type.

---
An earlier attempt at this conversion was posted by Moritz Zielke [1]. This is a fresh, independent implementation that reuses none of that code; it additionally converts the nova-core consumer and adds doctest examples.

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

 drivers/gpu/nova-core/firmware/gsp.rs |  2 +-
 rust/kernel/io.rs                     | 73 +++++++++++++++++++++++++--
 rust/kernel/io/resource.rs            |  6 +--
 rust/kernel/scatterlist.rs            |  2 +-
 4 files changed, 74 insertions(+), 9 deletions(-)
drivers/gpu/nova-core/firmware/gsp.rs +1 -1
index 99a302bae567..d7593888e65b 100644
@@ -175,7 +175,7 @@ pub(crate) fn radix3_dma_handle(&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::try_from(sg_entry.dma_len())?.div_ceil(GSP_PAGE_SIZE);
 
         for i in 0..num_pages {
             let entry = sg_entry.dma_address()
rust/kernel/io.rs +69 -4

89 lines not on this page · raw message

rust/kernel/io/resource.rs +3 -3
index 17b0c174cfc5..a33a416b289a 100644
@@ -58,7 +58,7 @@ fn drop(&mut self) {
         };
 
         // SAFETY: Safe as per the invariant of `Region`.
-        unsafe { release_fn(start, size) };
+        unsafe { release_fn(start, size.into_raw()) };
     }
 }
 
@@ -114,7 +114,7 @@ pub fn request_region(
             bindings::__request_region(
                 self.0.get(),
                 start,
-                size,
+                size.into_raw(),
                 name.as_char_ptr(),
                 flags.0 as c_int,
             )
@@ -130,7 +130,7 @@ pub fn request_region(
     pub fn size(&self) -> ResourceSize {
         let inner = self.0.get();
         // SAFETY: Safe as per the invariants of `Resource`.
-        unsafe { bindings::resource_size(inner) }
+        ResourceSize::from_raw(unsafe { bindings::resource_size(inner) })
     }
 
     /// Returns the start address of the resource.
rust/kernel/scatterlist.rs +1 -1
index b83c468b5c63..5d67242befd8 100644
@@ -93,7 +93,7 @@ pub fn dma_address(&self) -> dma::DmaAddress {
     pub fn dma_len(&self) -> ResourceSize {
         #[allow(clippy::useless_conversion)]
         // SAFETY: `self.as_raw()` is a valid pointer to a `struct scatterlist`.
-        unsafe { bindings::sg_dma_len(self.as_raw()) }.into()
+        ResourceSize::from_raw(unsafe { bindings::sg_dma_len(self.as_raw()) }.into())
     }
 }
 

base-commit: 8cdeaa50eae8dad34885515f62559ee83e7e8dda

Signature · 1 line
2.54.0
maintainer
#1 lore raw

drivers/gpu/nova-core/firmware/gsp.rs pub(crate) fn radix3_dma_handle(&self) -> DmaAddress { · line 178

Quoted 10 lines · Lorenzo Delgado
drivers/gpu/nova-core/firmware/gsp.rs +1 -1
index 99a302bae567..d7593888e65b 100644
@@ -175,7 +175,7 @@ pub(crate) fn radix3_dma_handle(&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::try_from(sg_entry.dma_len())?.div_ceil(GSP_PAGE_SIZE);

I think this is worse, as the conversion becomes fallible.

You could implement From<ResourceSize> for u64 and then keep using usize::from_safe_cast() in nova-core.

Alternatively, we could also consider moving the FromSafeCast trait to rust/kernel/num.rs and add FromSafeCast<ResourceSize> impls for usize.

I originally proposed the approach [1], since in nova-core we had a lot of fallible conversion, while our Kconfig mandates that they can never actually fail.

However, by making it commonly availble I do see a risk with the cfg-gated impls silently breaking the build.

Now, technically that's the feature and 0-day etc. should usually catch it, but on the other hand we also usually try to avoid cfg-gates in the kernel.

Miguel, I think you were in favor of this as well, what do you think?

[1] https://lore.kernel.org/rust-for-linux/[email protected]/

#2 lore raw
Quoted 5 lines · Danilo Krummrich

drivers/gpu/nova-core/firmware/gsp.rs pub(crate) fn radix3_dma_handle(&self) -> DmaAddress { · line 178

Quoted 2 lines · Lorenzo Delgado
drivers/gpu/nova-core/firmware/gsp.rs +1 -1
-        let num_pages = usize::from_safe_cast(sg_entry.dma_len()).div_ceil(GSP_PAGE_SIZE);
+        let num_pages = usize::try_from(sg_entry.dma_len())?.div_ceil(GSP_PAGE_SIZE);

I think this is worse, as the conversion becomes fallible.

Agreed, that's a regression for nova-core, where the Kconfig guarantees the value fits and the conversion should stay infallible. I'll drop the try_from() there.

Quoted 2 lines

You could implement From<ResourceSize> for u64 and then keep using usize::from_safe_cast() in nova-core.

I tried that, but it doesn't build. ResourceSize wraps resource_size_t, which is u64 on 64-bit (CONFIG_PHYS_ADDR_T_64BIT), so the impl the patch already has,

impl From<ResourceSize> for bindings::resource_size_t

is already From<ResourceSize> for u64 there, and a second one conflicts:

error[E0119]: conflicting implementations of trait
From<ResourceSize> for type u64

There's a simpler way that stays infallible and adds nothing to io.rs. ResourceSize already has into_raw() (io/resource.rs uses it at the C boundaries), so nova-core can do:

let num_pages =
usize::from_safe_cast(sg_entry.dma_len().into_raw()).div_ceil(GSP_PAGE_SIZE);

into_raw() gives back resource_size_t, and from_safe_cast handles that as u32 or u64 depending on the config, so it stays infallible. I'll use that in v2 unless you'd prefer something else.

Quoted 5 lines

Alternatively, we could also consider moving the FromSafeCast trait to rust/kernel/num.rs and add FromSafeCast<ResourceSize> impls for usize. [...]
However, by making it commonly availble I do see a risk with the cfg-gated impls silently breaking the build.

Agreed on the risk. A FromSafeCast<ResourceSize> for usize impl would have to be cfg-gated like the u64 one, which is the same silent-breakage-under-randconfig case you mention.

Since into_raw() keeps this patch self-contained, moving FromSafeCast into the kernel crate is a separate change from the newtype conversion. It seems worth doing on its own, and I'm happy to send it as its own series so it gets reviewed as a new core API, but it doesn't need to block this patch. I'll post v2 with the into_raw() change.

Thanks for the review.

Lorenzo

maintainer
#3 lore raw
Quoted 10 lines · Lorenzo Delgado

I tried that, but it doesn't build. ResourceSize wraps resource_size_t, which is u64 on 64-bit (CONFIG_PHYS_ADDR_T_64BIT), so the impl the patch already has,

impl From<ResourceSize> for bindings::resource_size_t

is already From<ResourceSize> for u64 there, and a second one conflicts:

error[E0119]: conflicting implementations of trait
From<ResourceSize> for type u64

Sure, but in the case a cfg-gate is perfectly fine, as the impl will always be availble. Either through impl for u64 directly or through impl for bindings::resource_size_t.

Quoted 10 lines

There's a simpler way that stays infallible and adds nothing to io.rs. ResourceSize already has into_raw() (io/resource.rs uses it at the C boundaries), so nova-core can do:

let num_pages =
usize::from_safe_cast(sg_entry.dma_len().into_raw()).div_ceil(GSP_PAGE_SIZE);

into_raw() gives back resource_size_t, and from_safe_cast handles that as u32 or u64 depending on the config, so it stays infallible. I'll use that in v2 unless you'd prefer something else.

I don't want to grow it arbitrarily in nova-core - which is also why I opened the question of moving FromSafeCast to generic infrastructure again - but in this case we should rather add the FromSafeCast<ResourceSize> for usize impl in drivers/gpu/nova-core/num.rs for now and move it subsequently.

reviewer
#4 lore raw
Quoted 7 lines · Danilo Krummrich
Quoted 6 lines · Lorenzo Delgado

I tried that, but it doesn't build. ResourceSize wraps resource_size_t, which is u64 on 64-bit (CONFIG_PHYS_ADDR_T_64BIT), so the impl the patch already has,

impl From<ResourceSize> for bindings::resource_size_t

Quoted 8 lines
Quoted 4 lines

is already From<ResourceSize> for u64 there, and a second one conflicts:

error[E0119]: conflicting implementations of trait
From<ResourceSize> for type u64

Sure, but in the case a cfg-gate is perfectly fine, as the impl will always be availble. Either through impl for u64 directly or through impl for bindings::resource_size_t.

Given that resource_size_t is either u32 or u64 depending on cfg, essentially From<ResourceSize> for bindings::resource_size_t has cfg-gating. So basically we always unconditionally have u64 impl, and for !CONFIG_PHYS_ADDR_T_64BIT we have a condition u32 impl.

Best,
Gary

#5 lore raw
In reply to Danilo Krummrich
Quoted 17 lines · Danilo Krummrich

drivers/gpu/nova-core/firmware/gsp.rs pub(crate) fn radix3_dma_handle(&self) -> DmaAddress { · line 178

Quoted 10 lines · Lorenzo Delgado
drivers/gpu/nova-core/firmware/gsp.rs +1 -1
index 99a302bae567..d7593888e65b 100644
@@ -175,7 +175,7 @@ pub(crate) fn radix3_dma_handle(&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::try_from(sg_entry.dma_len())?.div_ceil(GSP_PAGE_SIZE);

I think this is worse, as the conversion becomes fallible.

You could implement From<ResourceSize> for u64 and then keep using usize::from_safe_cast() in nova-core.

Quoted 6 lines

Alternatively, we could also consider moving the FromSafeCast trait to rust/kernel/num.rs and add FromSafeCast<ResourceSize> impls for usize.

I originally proposed the approach [1], since in nova-core we had a lot of fallible conversion, while our Kconfig mandates that they can never actually fail.

Back last year (!) I sent a RFC for this [1] but never followed up somehow. Let me send a proper patch as it should be useful to have globally.

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

#6 lore raw

PATCH v2 1/1 rust: io: convert ResourceSize into a transparent newtype

In reply to Lorenzo Delgado

ResourceSize was a bare type alias for resource_size_t, so it inherited every integer operation and as cast. That silently permits operations that are meaningless for the size of a hardware resource:
mixing it with unrelated integers and truncating casts.

Wrap it in a #[repr(transparent)] newtype so each conversion at a boundary becomes explicit and reviewable. The representation is unchanged, so this is ABI-identical; only the spelling at the FFI boundary changes. Provide the conversion surface from_raw/into_raw, From in both directions, and a fallible TryFrom<ResourceSize> for usize for checked narrowing. Update the two producers, Resource::size and SGEntry::dma_len, and the request_region consumer. In nova-core, add an impl FromSafeCast<ResourceSize> for usize so its page-count conversion keeps the infallible usize::from_safe_cast(sg_entry.dma_len()) unchanged.

---
v2: keep the nova-core page-count conversion infallible, per review
(Danilo Krummrich). v1 changed it to a fallible usize::try_from(sg_entry.dma_len())?; instead of touching the call site, add an impl FromSafeCast<ResourceSize> for usize in nova-core's num.rs, so drivers/gpu/nova-core/firmware/gsp.rs keeps usize::from_safe_cast(sg_entry.dma_len()) unchanged. FromSafeCast is to move to the kernel crate subsequently. io.rs is unchanged from v1.

v1: https://lore.kernel.org/r/[email protected]

 drivers/gpu/nova-core/num.rs | 10 +++++
 rust/kernel/io.rs            | 73 ++++++++++++++++++++++++++++++++++--
 rust/kernel/io/resource.rs   |  6 +--
 rust/kernel/scatterlist.rs   |  2 +-
 4 files changed, 83 insertions(+), 8 deletions(-)
drivers/gpu/nova-core/num.rs +10 -0
index 6eb174d136ab..7c0e878bbfb2 100644
@@ -6,6 +6,7 @@
 //! crate.
 
 use kernel::{
+    io::ResourceSize,
     macros::paste,
     prelude::*, //
 };
@@ -137,6 +138,15 @@ fn from_safe_cast(value: u64) -> Self {
     }
 }
 
+// A `resource_size_t` fits into a `usize` on 64-bit platforms, where a `usize` is a `u64` and a
+// `resource_size_t` is at most a `u64`. Delegates to the primitive impl for the underlying type.
+#[cfg(CONFIG_64BIT)]
+impl FromSafeCast<ResourceSize> for usize {
+    fn from_safe_cast(value: ResourceSize) -> Self {
+        Self::from_safe_cast(value.into_raw())
+    }
+}
+
 /// Counterpart to the [`FromSafeCast`] trait, i.e. this trait is to [`FromSafeCast`] what [`Into`]
 /// is to [`From`].
 ///
rust/kernel/io.rs +69 -4

89 lines not on this page · raw message

rust/kernel/io/resource.rs +3 -3
index 17b0c174cfc5..a33a416b289a 100644
@@ -58,7 +58,7 @@ fn drop(&mut self) {
         };
 
         // SAFETY: Safe as per the invariant of `Region`.
-        unsafe { release_fn(start, size) };
+        unsafe { release_fn(start, size.into_raw()) };
     }
 }
 
@@ -114,7 +114,7 @@ pub fn request_region(
             bindings::__request_region(
                 self.0.get(),
                 start,
-                size,
+                size.into_raw(),
                 name.as_char_ptr(),
                 flags.0 as c_int,
             )
@@ -130,7 +130,7 @@ pub fn request_region(
     pub fn size(&self) -> ResourceSize {
         let inner = self.0.get();
         // SAFETY: Safe as per the invariants of `Resource`.
-        unsafe { bindings::resource_size(inner) }
+        ResourceSize::from_raw(unsafe { bindings::resource_size(inner) })
     }
 
     /// Returns the start address of the resource.
rust/kernel/scatterlist.rs +1 -1
index b83c468b5c63..5d67242befd8 100644
@@ -93,7 +93,7 @@ pub fn dma_address(&self) -> dma::DmaAddress {
     pub fn dma_len(&self) -> ResourceSize {
         #[allow(clippy::useless_conversion)]
         // SAFETY: `self.as_raw()` is a valid pointer to a `struct scatterlist`.
-        unsafe { bindings::sg_dma_len(self.as_raw()) }.into()
+        ResourceSize::from_raw(unsafe { bindings::sg_dma_len(self.as_raw()) }.into())
     }
 }
 

base-commit: 7059bdf4f04a3e14f4fafb3ac35fdca913e3e21a

Signature · 1 line
2.54.0
#7 lore raw
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] Incomplete API Implementation: PCI FFI boundary methods continue to return raw…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] Incomplete API Implementation: PCI FFI boundary methods continue to return raw bindings::resource_size_t instead of the typed ResourceSize API.
- [Low] Incorrect import order for core::num::TryFromIntError violating kernel guidelines.
--

--- Patch [1]: [PATCH v2] rust: io: convert ResourceSize into a transparent newtype --- commit b81b66fe76cbe9487443105d289e399a714dd21d
Author: Lorenzo Delgado <[email protected]>

rust: io: convert ResourceSize into a transparent newtype

This patch wraps ResourceSize in a #[repr(transparent)] newtype to prevent unintended integer operations and truncating casts. It provides explicit boundary conversions and updates existing producers and consumers to use the new typed API.

Quoted 7 lines

Wrap it in a #[repr(transparent)] newtype so each conversion at a boundary becomes explicit and reviewable. The representation is unchanged, so this is ABI-identical; only the spelling at the FFI boundary changes. Provide the conversion surface from_raw/into_raw, From in both directions, and a fallible TryFrom<ResourceSize> for usize for checked narrowing. Update the two producers, Resource::size and SGEntry::dma_len, and the request_region consumer. In nova-core,

[Severity: Medium]
Does this miss other producers in the FFI boundary?

Looking at rust/kernel/pci.rs, both resource_start() and resource_len() continue to return the raw bindings::resource_size_t type rather than the new ResourceSize type.

Should these functions also be updated to return the new ResourceSize type to ensure the API remains consistent and fully protected against implicit casts across the subsystem?

rust/kernel/io.rs line 13

Quoted 13 lines
rust/kernel/io.rs +2 -0
index fcc7678fd9e3c..ebf00b4536d6d 100644
@@ -6,9 +6,12 @@
 
 use crate::{
     bindings,
+    fmt,
     prelude::*, //
 };
 
+use core::num::TryFromIntError;

[Severity: Low]
This isn't a bug, but should the core import be placed before the crate imports?

The kernel's Rust coding guidelines typically require vertical imports where core and alloc are grouped together and placed before kernel (or crate) imports.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1