Skip to contentSkip to conversation

rust: io: use newtype for PhysAddr

PATCH Superseded [email protected] 5 participants 9 messages May 3 – May 5

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 rust: io: use newtype for PhysAddr

From: Favilances Noir <[email protected]>

From: Favilances Noir <[email protected]>

Currently, PhysAddr is a type alias for phys_addr_t. This means that physical addresses can be mixed with unrelated integer values without Rust noticing.

Use a transparent newtype for PhysAddr instead, and update the affected call sites to perform explicit raw conversions at the FFI boundary.

This keeps the existing phys_addr_t representation while making physical addresses distinct in Rust type checking.

---
 rust/kernel/devres.rs        |  8 +++++---
 rust/kernel/io.rs            | 30 ++++++++++++++++++++++++------
 rust/kernel/io/mem.rs        |  4 ++--
 rust/kernel/io/resource.rs   |  6 +++---
 rust/kernel/iommu/pgtable.rs |  2 +-
 5 files changed, 35 insertions(+), 15 deletions(-)
rust/kernel/devres.rs +5 -3
index 9e5f93aed20c..beb3723d2519 100644
@@ -85,10 +85,10 @@ struct Inner<T> {
 ///     ///
 ///     /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
 ///     /// virtual address space.
-///     unsafe fn new(paddr: usize) -> Result<Self>{
+///     unsafe fn new(paddr: PhysAddr) -> Result<Self>{
 ///         // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
 ///         // valid for `ioremap`.
-///         let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };
+///         let addr = unsafe { bindings::ioremap(paddr.into_raw(), SIZE) };
 ///         if addr.is_null() {
 ///             return Err(ENOMEM);
 ///         }
@@ -114,7 +114,9 @@ struct Inner<T> {
 /// }
 /// # fn no_run(dev: &Device<Bound>) -> Result<(), Error> {
 /// // SAFETY: Invalid usage for example purposes.
-/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
+/// let iomem = unsafe {
+///     IoMem::<{ core::mem::size_of::<u32>() }>::new(PhysAddr::from_raw(0xBAAAAAAD))?
+/// };
 /// let devres = Devres::new(dev, iomem)?;
 ///
 /// let res = devres.try_access().ok_or(ENXIO)?;
rust/kernel/io.rs +24 -6
index fcc7678fd9e3..2d55ee93caae 100644
@@ -21,9 +21,25 @@
 
 /// Physical address type.
 ///
-/// This is a type alias to either `u32` or `u64` depending on the config option
-/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit architectures.
-pub type PhysAddr = bindings::phys_addr_t;
+/// This wraps either `u32` or `u64` depending on the config option
+/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a `u64` even on 32-bit architectures.
+#[repr(transparent)]
+#[derive(Clone, Copy)]
+pub struct PhysAddr(bindings::phys_addr_t);
+
+impl PhysAddr {
+    /// Creates a physical address from the raw C type.
+    #[inline]
+    pub const fn from_raw(value: bindings::phys_addr_t) -> Self {
+        Self(value)
+    }
+
+    /// Turns this physical address into the raw C type.
+    #[inline]
+    pub const fn into_raw(self) -> bindings::phys_addr_t {
+        self.0
+    }
+}
 
 /// Resource Size type.
 ///
@@ -101,10 +117,10 @@ pub fn maxsize(&self) -> usize {
 ///     ///
 ///     /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
 ///     /// virtual address space.
-///     unsafe fn new(paddr: usize) -> Result<Self>{
+///     unsafe fn new(paddr: PhysAddr) -> Result<Self>{
 ///         // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
 ///         // valid for `ioremap`.
-///         let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };
+///         let addr = unsafe { bindings::ioremap(paddr.into_raw(), SIZE) };
 ///         if addr.is_null() {
 ///             return Err(ENOMEM);
 ///         }
@@ -131,7 +147,9 @@ pub fn maxsize(&self) -> usize {
 ///
 ///# fn no_run() -> Result<(), Error> {
 /// // SAFETY: Invalid usage for example purposes.
-/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
+/// let iomem = unsafe {
+///     IoMem::<{ core::mem::size_of::<u32>() }>::new(PhysAddr::from_raw(0xBAAAAAAD))?
+/// };
 /// iomem.write32(0x42, 0x0);
 /// assert!(iomem.try_write32(0x42, 0x0).is_ok());
 /// assert!(iomem.try_write32(0x42, 0x4).is_err());
rust/kernel/io/mem.rs +2 -2
index 7dc78d547f7a..f21f9038b297 100644
@@ -254,12 +254,12 @@ fn ioremap(resource: &Resource) -> Result<Self> {
             // SAFETY:
             // - `res_start` and `size` are read from a presumably valid `struct resource`.
             // - `size` is known not to be zero at this point.
-            unsafe { bindings::ioremap_np(res_start, size) }
+            unsafe { bindings::ioremap_np(res_start.into_raw(), size) }
         } else {
             // SAFETY:
             // - `res_start` and `size` are read from a presumably valid `struct resource`.
             // - `size` is known not to be zero at this point.
-            unsafe { bindings::ioremap(res_start, size) }
+            unsafe { bindings::ioremap(res_start.into_raw(), size) }
         };
 
         if addr.is_null() {
rust/kernel/io/resource.rs +3 -3
index b7ac9faf141d..5dda1061db68 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.into_raw(), size) };
     }
 }
 
@@ -113,7 +113,7 @@ pub fn request_region(
         let region = unsafe {
             bindings::__request_region(
                 self.0.get(),
-                start,
+                start.into_raw(),
                 size,
                 name.as_char_ptr(),
                 flags.0 as c_int,
@@ -137,7 +137,7 @@ pub fn size(&self) -> ResourceSize {
     pub fn start(&self) -> PhysAddr {
         let inner = self.0.get();
         // SAFETY: Safe as per the invariants of `Resource`.
-        unsafe { (*inner).start }
+        PhysAddr::from_raw(unsafe { (*inner).start })
     }
 
     /// Returns the name of the resource.
rust/kernel/iommu/pgtable.rs +1 -1
index c88e38fd938a..ae724ca1e8ad 100644
@@ -182,7 +182,7 @@ pub unsafe fn map_pages(
             (map_pages)(
                 self.raw_ops(),
                 iova,
-                paddr,
+                paddr.into_raw(),
                 pgsize,
                 pgcount,
                 prot as i32,
Signature · 1 line
2.54.0
reviewer
#2 lore raw
In reply to [email protected]
Quoted 57 lines · On Sun, 03 May 2026 13:30:50 +0300 [email protected] wrote:

From: Favilances Noir <[email protected]>

From: Favilances Noir <[email protected]>

Currently, PhysAddr is a type alias for phys_addr_t. This means that physical addresses can be mixed with unrelated integer values without Rust noticing.

Use a transparent newtype for PhysAddr instead, and update the affected call sites to perform explicit raw conversions at the FFI boundary.

This keeps the existing phys_addr_t representation while making physical addresses distinct in Rust type checking.

---
 rust/kernel/devres.rs        |  8 +++++---
 rust/kernel/io.rs            | 30 ++++++++++++++++++++++++------
 rust/kernel/io/mem.rs        |  4 ++--
 rust/kernel/io/resource.rs   |  6 +++---
 rust/kernel/iommu/pgtable.rs |  2 +-
 5 files changed, 35 insertions(+), 15 deletions(-)
rust/kernel/devres.rs +5 -3
index 9e5f93aed20c..beb3723d2519 100644
@@ -85,10 +85,10 @@ struct Inner<T> {
 ///     ///
 ///     /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
 ///     /// virtual address space.
-///     unsafe fn new(paddr: usize) -> Result<Self>{
+///     unsafe fn new(paddr: PhysAddr) -> Result<Self>{
 ///         // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
 ///         // valid for `ioremap`.
-///         let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };
+///         let addr = unsafe { bindings::ioremap(paddr.into_raw(), SIZE) };
 ///         if addr.is_null() {
 ///             return Err(ENOMEM);
 ///         }
@@ -114,7 +114,9 @@ struct Inner<T> {
 /// }
 /// # fn no_run(dev: &Device<Bound>) -> Result<(), Error> {
 /// // SAFETY: Invalid usage for example purposes.
-/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
+/// let iomem = unsafe {
+///     IoMem::<{ core::mem::size_of::<u32>() }>::new(PhysAddr::from_raw(0xBAAAAAAD))?
+/// };
 /// let devres = Devres::new(dev, iomem)?;
 ///
 /// let res = devres.try_access().ok_or(ENXIO)?;
rust/kernel/io.rs +0 -0
index fcc7678fd9e3..2d55ee93caae 100644

rust/kernel/io.rs line 27

Quoted 10 lines
rust/kernel/io.rs +4 -3
@@ -21,9 +21,25 @@
 
 /// Physical address type.
 ///
-/// This is a type alias to either `u32` or `u64` depending on the config option
-/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit architectures.
-pub type PhysAddr = bindings::phys_addr_t;
+/// This wraps either `u32` or `u64` depending on the config option
+/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a `u64` even on 32-bit architectures.
+#[repr(transparent)]
+#[derive(Clone, Copy)]

Copy and Clone seem never used, please drop them (also see [1]).

[1]: https://rust-for-linux.zulipchat.com/#narrow/channel/509436-Nova/topic/clone.2Fcopy.20additions

Regards,
Onur

Quoted 108 lines
rust/kernel/io.rs +20 -3
+pub struct PhysAddr(bindings::phys_addr_t);
+
+impl PhysAddr {
+    /// Creates a physical address from the raw C type.
+    #[inline]
+    pub const fn from_raw(value: bindings::phys_addr_t) -> Self {
+        Self(value)
+    }
+
+    /// Turns this physical address into the raw C type.
+    #[inline]
+    pub const fn into_raw(self) -> bindings::phys_addr_t {
+        self.0
+    }
+}
 
 /// Resource Size type.
 ///
@@ -101,10 +117,10 @@ pub fn maxsize(&self) -> usize {
 ///     ///
 ///     /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
 ///     /// virtual address space.
-///     unsafe fn new(paddr: usize) -> Result<Self>{
+///     unsafe fn new(paddr: PhysAddr) -> Result<Self>{
 ///         // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
 ///         // valid for `ioremap`.
-///         let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };
+///         let addr = unsafe { bindings::ioremap(paddr.into_raw(), SIZE) };
 ///         if addr.is_null() {
 ///             return Err(ENOMEM);
 ///         }
@@ -131,7 +147,9 @@ pub fn maxsize(&self) -> usize {
 ///
 ///# fn no_run() -> Result<(), Error> {
 /// // SAFETY: Invalid usage for example purposes.
-/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
+/// let iomem = unsafe {
+///     IoMem::<{ core::mem::size_of::<u32>() }>::new(PhysAddr::from_raw(0xBAAAAAAD))?
+/// };
 /// iomem.write32(0x42, 0x0);
 /// assert!(iomem.try_write32(0x42, 0x0).is_ok());
 /// assert!(iomem.try_write32(0x42, 0x4).is_err());
rust/kernel/io/mem.rs +2 -2
index 7dc78d547f7a..f21f9038b297 100644
@@ -254,12 +254,12 @@ fn ioremap(resource: &Resource) -> Result<Self> {
             // SAFETY:
             // - `res_start` and `size` are read from a presumably valid `struct resource`.
             // - `size` is known not to be zero at this point.
-            unsafe { bindings::ioremap_np(res_start, size) }
+            unsafe { bindings::ioremap_np(res_start.into_raw(), size) }
         } else {
             // SAFETY:
             // - `res_start` and `size` are read from a presumably valid `struct resource`.
             // - `size` is known not to be zero at this point.
-            unsafe { bindings::ioremap(res_start, size) }
+            unsafe { bindings::ioremap(res_start.into_raw(), size) }
         };
 
         if addr.is_null() {
rust/kernel/io/resource.rs +3 -3
index b7ac9faf141d..5dda1061db68 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.into_raw(), size) };
     }
 }
 
@@ -113,7 +113,7 @@ pub fn request_region(
         let region = unsafe {
             bindings::__request_region(
                 self.0.get(),
-                start,
+                start.into_raw(),
                 size,
                 name.as_char_ptr(),
                 flags.0 as c_int,
@@ -137,7 +137,7 @@ pub fn size(&self) -> ResourceSize {
     pub fn start(&self) -> PhysAddr {
         let inner = self.0.get();
         // SAFETY: Safe as per the invariants of `Resource`.
-        unsafe { (*inner).start }
+        PhysAddr::from_raw(unsafe { (*inner).start })
     }
 
     /// Returns the name of the resource.
rust/kernel/iommu/pgtable.rs +1 -1
index c88e38fd938a..ae724ca1e8ad 100644
@@ -182,7 +182,7 @@ pub unsafe fn map_pages(
             (map_pages)(
                 self.raw_ops(),
                 iova,
-                paddr,
+                paddr.into_raw(),
                 pgsize,
                 pgcount,
                 prot as i32,
Signature · 1 line
2.54.0
maintainer
#3 lore raw
Quoted 1 line · Onur Özkan

Copy and Clone seem never used, please drop them (also see [1]).

This is a transparent wrapper of a primitive, so passing by value is a very natural and idiomatic thing to do, so we should keep them.

What you are referring to is more meant for larger types where a copy might actually hurt performance.

reviewer
#4 lore raw
Quoted 5 lines · On Sun, 03 May 2026 20:45:50 +0200 Danilo Krummrich <[email protected]> wrote:
Quoted 1 line · Onur Özkan

Copy and Clone seem never used, please drop them (also see [1]).

This is a transparent wrapper of a primitive, so passing by value is a very natural and idiomatic thing to do, so we should keep them.

Right, my bad. I didn't pay attention to the type itself.

Quoted 3 lines

What you are referring to is more meant for larger types where a copy might actually hurt performance.

#5 lore raw

PATCH v2 1/1 rust: io: use newtype for PhysAddr

In reply to [email protected]

From: Favilances Noir <[email protected]>

Currently, PhysAddr is a type alias for phys_addr_t. This means that physical addresses can be mixed with unrelated integer values without Rust noticing.

Use a transparent newtype for PhysAddr instead, and update the affected call sites to perform explicit raw conversions at the FFI boundary.

This keeps the existing phys_addr_t representation while making physical addresses distinct in Rust type checking.

Drop the unused Clone and Copy derives from PhysAddr, as pointed out in review.

---
 rust/kernel/devres.rs        |  8 +++++---
 rust/kernel/io.rs            | 29 +++++++++++++++++++++++------
 rust/kernel/io/mem.rs        |  4 ++--
 rust/kernel/io/resource.rs   |  6 +++---
 rust/kernel/iommu/pgtable.rs |  2 +-
 5 files changed, 34 insertions(+), 15 deletions(-)
rust/kernel/devres.rs +5 -3
index 9e5f93aed20c..beb3723d2519 100644
@@ -85,10 +85,10 @@ struct Inner<T> {
 ///     ///
 ///     /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
 ///     /// virtual address space.
-///     unsafe fn new(paddr: usize) -> Result<Self>{
+///     unsafe fn new(paddr: PhysAddr) -> Result<Self>{
 ///         // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
 ///         // valid for `ioremap`.
-///         let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };
+///         let addr = unsafe { bindings::ioremap(paddr.into_raw(), SIZE) };
 ///         if addr.is_null() {
 ///             return Err(ENOMEM);
 ///         }
@@ -114,7 +114,9 @@ struct Inner<T> {
 /// }
 /// # fn no_run(dev: &Device<Bound>) -> Result<(), Error> {
 /// // SAFETY: Invalid usage for example purposes.
-/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
+/// let iomem = unsafe {
+///     IoMem::<{ core::mem::size_of::<u32>() }>::new(PhysAddr::from_raw(0xBAAAAAAD))?
+/// };
 /// let devres = Devres::new(dev, iomem)?;
 ///
 /// let res = devres.try_access().ok_or(ENXIO)?;
rust/kernel/io.rs +23 -6
index fcc7678fd9e3..999fa285a6ec 100644
@@ -21,9 +21,24 @@
 
 /// Physical address type.
 ///
-/// This is a type alias to either `u32` or `u64` depending on the config option
-/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit architectures.
-pub type PhysAddr = bindings::phys_addr_t;
+/// This wraps either `u32` or `u64` depending on the config option
+/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a `u64` even on 32-bit architectures.
+#[repr(transparent)]
+pub struct PhysAddr(bindings::phys_addr_t);
+
+impl PhysAddr {
+    /// Creates a physical address from the raw C type.
+    #[inline]
+    pub const fn from_raw(value: bindings::phys_addr_t) -> Self {
+        Self(value)
+    }
+
+    /// Turns this physical address into the raw C type.
+    #[inline]
+    pub const fn into_raw(self) -> bindings::phys_addr_t {
+        self.0
+    }
+}
 
 /// Resource Size type.
 ///
@@ -101,10 +116,10 @@ pub fn maxsize(&self) -> usize {
 ///     ///
 ///     /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
 ///     /// virtual address space.
-///     unsafe fn new(paddr: usize) -> Result<Self>{
+///     unsafe fn new(paddr: PhysAddr) -> Result<Self>{
 ///         // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
 ///         // valid for `ioremap`.
-///         let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };
+///         let addr = unsafe { bindings::ioremap(paddr.into_raw(), SIZE) };
 ///         if addr.is_null() {
 ///             return Err(ENOMEM);
 ///         }
@@ -131,7 +146,9 @@ pub fn maxsize(&self) -> usize {
 ///
 ///# fn no_run() -> Result<(), Error> {
 /// // SAFETY: Invalid usage for example purposes.
-/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
+/// let iomem = unsafe {
+///     IoMem::<{ core::mem::size_of::<u32>() }>::new(PhysAddr::from_raw(0xBAAAAAAD))?
+/// };
 /// iomem.write32(0x42, 0x0);
 /// assert!(iomem.try_write32(0x42, 0x0).is_ok());
 /// assert!(iomem.try_write32(0x42, 0x4).is_err());
rust/kernel/io/mem.rs +2 -2
index 7dc78d547f7a..f21f9038b297 100644
@@ -254,12 +254,12 @@ fn ioremap(resource: &Resource) -> Result<Self> {
             // SAFETY:
             // - `res_start` and `size` are read from a presumably valid `struct resource`.
             // - `size` is known not to be zero at this point.
-            unsafe { bindings::ioremap_np(res_start, size) }
+            unsafe { bindings::ioremap_np(res_start.into_raw(), size) }
         } else {
             // SAFETY:
             // - `res_start` and `size` are read from a presumably valid `struct resource`.
             // - `size` is known not to be zero at this point.
-            unsafe { bindings::ioremap(res_start, size) }
+            unsafe { bindings::ioremap(res_start.into_raw(), size) }
         };
 
         if addr.is_null() {
rust/kernel/io/resource.rs +3 -3
index b7ac9faf141d..5dda1061db68 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.into_raw(), size) };
     }
 }
 
@@ -113,7 +113,7 @@ pub fn request_region(
         let region = unsafe {
             bindings::__request_region(
                 self.0.get(),
-                start,
+                start.into_raw(),
                 size,
                 name.as_char_ptr(),
                 flags.0 as c_int,
@@ -137,7 +137,7 @@ pub fn size(&self) -> ResourceSize {
     pub fn start(&self) -> PhysAddr {
         let inner = self.0.get();
         // SAFETY: Safe as per the invariants of `Resource`.
-        unsafe { (*inner).start }
+        PhysAddr::from_raw(unsafe { (*inner).start })
     }
 
     /// Returns the name of the resource.
rust/kernel/iommu/pgtable.rs +1 -1
index c88e38fd938a..ae724ca1e8ad 100644
@@ -182,7 +182,7 @@ pub unsafe fn map_pages(
             (map_pages)(
                 self.raw_ops(),
                 iova,
-                paddr,
+                paddr.into_raw(),
                 pgsize,
                 pgcount,
                 prot as i32,
Signature · 1 line
2.54.0
maintainer
#6 lore raw

Hi Favilances,

(I assume you are Favilances; asking since the mail came from just [email protected].)

Quoted 10 lines · On Mon May 4, 2026 at 1:14 PM CEST, x wrote:

From: Favilances Noir <[email protected]>

Currently, PhysAddr is a type alias for phys_addr_t. This means that physical addresses can be mixed with unrelated integer values without Rust noticing.

Use a transparent newtype for PhysAddr instead, and update the affected call sites to perform explicit raw conversions at the FFI boundary.

Quoted 5 lines

This keeps the existing phys_addr_t representation while making physical addresses distinct in Rust type checking.

Drop the unused Clone and Copy derives from PhysAddr, as pointed out in review.

This should be part of the version change log and should go below the "---" line.

Please also consider the subsequent replies to this feedback, which point out that this should indeed have Clone and Copy (and probably also other derives such as PartialEq).

For instance, consider the case where you call into_raw() because you need the raw value but then still want to do something with the PhysAddr. Without Copy you'd need to write something like:

	let r = p.into_raw();
	let p = PhysAddr::from_raw(r); // `r` implements `Copy`.

	// Use `r` and `p`.
Quoted 1 line

<snip>

Quoted 19 lines
rust/kernel/io.rs +8 -3
index fcc7678fd9e3..999fa285a6ec 100644
@@ -21,9 +21,24 @@
 
 /// Physical address type.
 ///
-/// This is a type alias to either `u32` or `u64` depending on the config option
-/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit architectures.
-pub type PhysAddr = bindings::phys_addr_t;
+/// This wraps either `u32` or `u64` depending on the config option
+/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a `u64` even on 32-bit architectures.
+#[repr(transparent)]
+pub struct PhysAddr(bindings::phys_addr_t);
+
+impl PhysAddr {
+    /// Creates a physical address from the raw C type.
+    #[inline]

rust/kernel/io.rs line 41

Quoted 10 lines
rust/kernel/io.rs +10 -0
+    pub const fn from_raw(value: bindings::phys_addr_t) -> Self {
+        Self(value)
+    }
+
+    /// Turns this physical address into the raw C type.
+    #[inline]
+    pub const fn into_raw(self) -> bindings::phys_addr_t {
+        self.0
+    }
+}

I like the explicit methods, but I can also see that this might become a bit verbose; maybe consider adding From impls as well.

I think eventually we also want {Try}From impls for usize etc., but let's wait until we have a user.

Maybe also consider a Debug impl that prints a hex value.

#7 lore raw

PATCH v3 1/1 rust: io: use newtype for PhysAddr

In reply to [email protected]

From: Favilances Noir <[email protected]>

Currently, PhysAddr is a type alias for phys_addr_t. This means that physical addresses can be mixed with unrelated integer values without Rust noticing.

Use a transparent newtype for PhysAddr instead, and update the affected call sites to perform explicit raw conversions at the FFI boundary.

This keeps the existing phys_addr_t representation while making physical addresses distinct in Rust type checking.

Derive Clone, Copy, PartialEq, and Eq for PhysAddr, implement Debug printing physical addresses in hexadecimal, and add From conversions between PhysAddr and the raw phys_addr_t type for API ergonomics.

A fallible TryFrom<usize> conversion can be added later if needed.

---
v3:
- Re-add Clone and Copy derives as suggested
- Add PartialEq and Eq
- Add From impls for better ergonomics
- Add Debug impl printing hexadecimal values
- Keep explicit conversions at the FFI boundary
- Thanks to Onur and Danilo for the review and suggestions

 rust/kernel/devres.rs        |  8 +++---
 rust/kernel/io.rs            | 49 +++++++++++++++++++++++++++++++-----
 rust/kernel/io/mem.rs        |  4 +--
 rust/kernel/io/resource.rs   |  6 ++---
 rust/kernel/iommu/pgtable.rs |  2 +-
 5 files changed, 54 insertions(+), 15 deletions(-)
rust/kernel/devres.rs +5 -3
index 9e5f93aed20c..beb3723d2519 100644
@@ -85,10 +85,10 @@ struct Inner<T> {
 ///     ///
 ///     /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
 ///     /// virtual address space.
-///     unsafe fn new(paddr: usize) -> Result<Self>{
+///     unsafe fn new(paddr: PhysAddr) -> Result<Self>{
 ///         // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
 ///         // valid for `ioremap`.
-///         let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };
+///         let addr = unsafe { bindings::ioremap(paddr.into_raw(), SIZE) };
 ///         if addr.is_null() {
 ///             return Err(ENOMEM);
 ///         }
@@ -114,7 +114,9 @@ struct Inner<T> {
 /// }
 /// # fn no_run(dev: &Device<Bound>) -> Result<(), Error> {
 /// // SAFETY: Invalid usage for example purposes.
-/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
+/// let iomem = unsafe {
+///     IoMem::<{ core::mem::size_of::<u32>() }>::new(PhysAddr::from_raw(0xBAAAAAAD))?
+/// };
 /// let devres = Devres::new(dev, iomem)?;
 ///
 /// let res = devres.try_access().ok_or(ENXIO)?;
rust/kernel/io.rs +43 -6

75 lines not on this page · raw message

rust/kernel/io/mem.rs +2 -2
index 7dc78d547f7a..f21f9038b297 100644
@@ -254,12 +254,12 @@ fn ioremap(resource: &Resource) -> Result<Self> {
             // SAFETY:
             // - `res_start` and `size` are read from a presumably valid `struct resource`.
             // - `size` is known not to be zero at this point.
-            unsafe { bindings::ioremap_np(res_start, size) }
+            unsafe { bindings::ioremap_np(res_start.into_raw(), size) }
         } else {
             // SAFETY:
             // - `res_start` and `size` are read from a presumably valid `struct resource`.
             // - `size` is known not to be zero at this point.
-            unsafe { bindings::ioremap(res_start, size) }
+            unsafe { bindings::ioremap(res_start.into_raw(), size) }
         };
 
         if addr.is_null() {
rust/kernel/io/resource.rs +3 -3
index b7ac9faf141d..5dda1061db68 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.into_raw(), size) };
     }
 }
 
@@ -113,7 +113,7 @@ pub fn request_region(
         let region = unsafe {
             bindings::__request_region(
                 self.0.get(),
-                start,
+                start.into_raw(),
                 size,
                 name.as_char_ptr(),
                 flags.0 as c_int,
@@ -137,7 +137,7 @@ pub fn size(&self) -> ResourceSize {
     pub fn start(&self) -> PhysAddr {
         let inner = self.0.get();
         // SAFETY: Safe as per the invariants of `Resource`.
-        unsafe { (*inner).start }
+        PhysAddr::from_raw(unsafe { (*inner).start })
     }
 
     /// Returns the name of the resource.
rust/kernel/iommu/pgtable.rs +1 -1
index c88e38fd938a..ae724ca1e8ad 100644
@@ -182,7 +182,7 @@ pub unsafe fn map_pages(
             (map_pages)(
                 self.raw_ops(),
                 iova,
-                paddr,
+                paddr.into_raw(),
                 pgsize,
                 pgcount,
                 prot as i32,
Signature · 1 line
2.54.0
#8 lore raw
Quoted 2 lines · On Tue, May 5, 2026 at 10:24 AM <[email protected]> wrote:

From: Favilances Noir <[email protected]>

It is great to see more strong types, thanks for this!

From the other parallel patch:

By the way, please try to fix the email From header -- it can be quite confusing to see "x" in the mailing list and other tooling... :)

We also probably want a few more #[inline]s as Sashiko mentions.

Cheers,
Miguel