Skip to contentSkip to conversation

rust: io: turn IoCapable into a functional trait

PATCH Superseded Alexandre Courbot 5 participants 18 messages Feb 2 – Feb 4

Subsystems (5)
PCI Driver core Rust PCI Rust +1 more subsystems

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Alexandre Courbot

author reviewer
#0 lore raw

cover rust: io: turn IoCapable into a functional trait

IoCapable<T> is currently used as a marker trait to signal that the methods of the Io trait corresponding to T have been overridden by the implementor (the default implementations triggering a build-time error).

This goes against the DRY principle and separates the signaling of the capability from its implementation, making it possible to forget a step while implementing a new Io.

Another undesirable side-effect is that it makes the implementation of I/O backends boilerplate-y and convoluted: currently this is done using two levels of imbricated macros that generate unsafe code.

This patchset fixes these issues by turning IoCapable into a functional trait including the raw implementation of the I/O accessors for T using unsafe methods that work with an arbitrary address, and making the default methods of Io call into these implementations after checking the bounds.

This makes overriding these accessors on all I/O backends unneeded, resulting in a net -90 LoCs while avoiding a violation of the DRY principle and reducing (and simplifying) the use of macros generating unsafe code.

Patch 1 adds the io_read and io_write unsafe methods to IoCapable, provides the required implementations for Mmio and pci::ConfigSpace, and make the default I/O accessors of Io call into them instead of failing.

Patches 2 to 4 get rid of the _relaxed variants we had in Mmio, since these are not usable in code generic against Io and makes use of the macros we want to remove. They are replaced by a RelaxedMmio wrapper type that implements the required IoCapables and is thus usable in generic code.

Patches 5 and 6 remove the overloaded implementations of the Io methods for pci::ConfigSpace and Mmio, respectively, while also deleting the macros that have become unused.

There is more work coming on top of this patchset (notably the register! macro with proper I/O), but I wanted to send this work first as it stands on its own IMHO and is more digestible from a review perspective.

The base for this patchset is driver-core-testing.

Cc Zhi Wang <[email protected]>
Cc Lyude Paul <[email protected]>
Cc Eliot Courtney <[email protected]>

---
Alexandre Courbot (6):
rust: io: turn IoCapable into a functional trait
rust: io: mem: use non-relaxed I/O ops in examples
rust: io: provide Mmio relaxed ops through a wrapper type
rust: io: remove legacy relaxed accessors of Mmio
rust: pci: io: remove overloaded Io methods of ConfigSpace
rust: io: remove overloaded Io methods of Mmio

 rust/kernel/io.rs     | 435 ++++++++++++++++++++++----------------------------
 rust/kernel/io/mem.rs |  10 +-
 rust/kernel/pci/io.rs |  99 ++++--------
 3 files changed, 227 insertions(+), 317 deletions(-)

---
base-commit: 289b14592cefe95f7d0ef334873c12b96ce3824f
change-id: 20260202-io-81fd368f7565

Best regards,

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

PATCH 1/6 rust: io: turn IoCapable into a functional trait

IoCapable<T> is currently used as a marker trait to signal that the methods of the Io trait corresponding to T have been overridden by the implementor (the default implementations triggering a build-time error).

This goes against the DRY principle and separates the signaling of the capability from its implementation, making it possible to forget a step while implementing a new Io.

Another undesirable side-effect is that it makes the implementation of I/O backends boilerplate-y and convoluted: currently this is done using two levels of imbricated macros that generate unsafe code.

Fix these issues by turning IoCapable into a functional trait that includes the raw implementation of the I/O access for T using unsafe methods that work with an arbitrary address.

This allows us to turn the default methods of Io into regular methods that check the passed offset, turn it into an address, and call into the corresponding IoCapable functions, removing the need to overload them at all.

IoCapable must still be implemented for all supported primitive types, which is still done more concisely using a macro, but this macro becomes much simpler and does not require calling into another one.

---
 rust/kernel/io.rs     | 169 ++++++++++++++++++++++++++++++++++++++------------
 rust/kernel/pci/io.rs |  37 ++++++++++-
 2 files changed, 163 insertions(+), 43 deletions(-)
rust/kernel/io.rs +129 -40
index c1cca7b438c3..dc894a45bbcc 100644
@@ -273,14 +273,29 @@ const fn offset_valid<U>(offset: usize, size: usize) -> bool {
     }
 }
 
-/// Marker trait indicating that an I/O backend supports operations of a certain type.
+/// Trait indicating that an I/O backend supports operations of a certain type and providing an
+/// implementation for these operations.
 ///
 /// Different I/O backends can implement this trait to expose only the operations they support.
 ///
 /// For example, a PCI configuration space may implement `IoCapable<u8>`, `IoCapable<u16>`,
 /// and `IoCapable<u32>`, but not `IoCapable<u64>`, while an MMIO region on a 64-bit
 /// system might implement all four.
-pub trait IoCapable<T> {}
+pub trait IoCapable<T> {
+    /// Performs an I/O read of type `T` at `address` and returns the result.
+    ///
+    /// # Safety
+    ///
+    /// The range `[address..address + size_of::<T>()]` must be within the bounds of `Self`.
+    unsafe fn io_read(&self, address: usize) -> T;
+
+    /// Performs an I/O write of `value` at `address`.
+    ///
+    /// # Safety
+    ///
+    /// The range `[address..address + size_of::<T>()]` must be within the bounds of `Self`.
+    unsafe fn io_write(&self, value: T, address: usize);
+}
 
 /// Types implementing this trait (e.g. MMIO BARs or PCI config regions)
 /// can perform I/O operations on regions of memory.
@@ -322,146 +337,198 @@ fn io_addr<U>(&self, offset: usize) -> Result<usize> {
 
     /// Fallible 8-bit read with runtime bounds check.
     #[inline(always)]
-    fn try_read8(&self, _offset: usize) -> Result<u8>
+    fn try_read8(&self, offset: usize) -> Result<u8>
     where
         Self: IoCapable<u8>,
     {
-        build_error!("Backend does not support fallible 8-bit read")
+        let address = self.io_addr::<u8>(offset)?;
+
+        // SAFETY: `address` has been validated by `io_addr`.
+        Ok(unsafe { self.io_read(address) })
     }
 
     /// Fallible 16-bit read with runtime bounds check.
     #[inline(always)]
-    fn try_read16(&self, _offset: usize) -> Result<u16>
+    fn try_read16(&self, offset: usize) -> Result<u16>
     where
         Self: IoCapable<u16>,
     {
-        build_error!("Backend does not support fallible 16-bit read")
+        let address = self.io_addr::<u16>(offset)?;
+
+        // SAFETY: `address` has been validated by `io_addr`.
+        Ok(unsafe { self.io_read(address) })
     }
 
     /// Fallible 32-bit read with runtime bounds check.
     #[inline(always)]
-    fn try_read32(&self, _offset: usize) -> Result<u32>
+    fn try_read32(&self, offset: usize) -> Result<u32>
     where
         Self: IoCapable<u32>,
     {
-        build_error!("Backend does not support fallible 32-bit read")
+        let address = self.io_addr::<u32>(offset)?;
+
+        // SAFETY: `address` has been validated by `io_addr`.
+        Ok(unsafe { self.io_read(address) })
     }
 
     /// Fallible 64-bit read with runtime bounds check.
     #[inline(always)]
-    fn try_read64(&self, _offset: usize) -> Result<u64>
+    fn try_read64(&self, offset: usize) -> Result<u64>
     where
         Self: IoCapable<u64>,
     {
-        build_error!("Backend does not support fallible 64-bit read")
+        let address = self.io_addr::<u64>(offset)?;
+
+        // SAFETY: `address` has been validated by `io_addr`.
+        Ok(unsafe { self.io_read(address) })
     }
 
     /// Fallible 8-bit write with runtime bounds check.
     #[inline(always)]
-    fn try_write8(&self, _value: u8, _offset: usize) -> Result
+    fn try_write8(&self, value: u8, offset: usize) -> Result
     where
         Self: IoCapable<u8>,
     {
-        build_error!("Backend does not support fallible 8-bit write")
+        let address = self.io_addr::<u8>(offset)?;
+
+        // SAFETY: `address` has been validated by `io_addr`.
+        unsafe { self.io_write(value, address) };
+        Ok(())
     }
 
     /// Fallible 16-bit write with runtime bounds check.
     #[inline(always)]
-    fn try_write16(&self, _value: u16, _offset: usize) -> Result
+    fn try_write16(&self, value: u16, offset: usize) -> Result
     where
         Self: IoCapable<u16>,
     {
-        build_error!("Backend does not support fallible 16-bit write")
+        let address = self.io_addr::<u16>(offset)?;
+
+        // SAFETY: `address` has been validated by `io_addr`.
+        unsafe { self.io_write(value, address) };
+        Ok(())
     }
 
     /// Fallible 32-bit write with runtime bounds check.
     #[inline(always)]
-    fn try_write32(&self, _value: u32, _offset: usize) -> Result
+    fn try_write32(&self, value: u32, offset: usize) -> Result
     where
         Self: IoCapable<u32>,
     {
-        build_error!("Backend does not support fallible 32-bit write")
+        let address = self.io_addr::<u32>(offset)?;
+
+        // SAFETY: `address` has been validated by `io_addr`.
+        unsafe { self.io_write(value, address) };
+        Ok(())
     }
 
     /// Fallible 64-bit write with runtime bounds check.
     #[inline(always)]
-    fn try_write64(&self, _value: u64, _offset: usize) -> Result
+    fn try_write64(&self, value: u64, offset: usize) -> Result
     where
         Self: IoCapable<u64>,
     {
-        build_error!("Backend does not support fallible 64-bit write")
+        let address = self.io_addr::<u64>(offset)?;
+
+        // SAFETY: `address` has been validated by `io_addr`.
+        unsafe { self.io_write(value, address) };
+        Ok(())
     }
 
     /// Infallible 8-bit read with compile-time bounds check.
     #[inline(always)]
-    fn read8(&self, _offset: usize) -> u8
+    fn read8(&self, offset: usize) -> u8
     where
         Self: IoKnownSize + IoCapable<u8>,
     {
-        build_error!("Backend does not support infallible 8-bit read")
+        let address = self.io_addr_assert::<u8>(offset);
+
+        // SAFETY: `address` has been validated by `io_addr_assert`.
+        unsafe { self.io_read(address) }
     }
 
     /// Infallible 16-bit read with compile-time bounds check.
     #[inline(always)]
-    fn read16(&self, _offset: usize) -> u16
+    fn read16(&self, offset: usize) -> u16
     where
         Self: IoKnownSize + IoCapable<u16>,
     {
-        build_error!("Backend does not support infallible 16-bit read")
+        let address = self.io_addr_assert::<u16>(offset);
+
+        // SAFETY: `address` has been validated by `io_addr_assert`.
+        unsafe { self.io_read(address) }
     }
 
     /// Infallible 32-bit read with compile-time bounds check.
     #[inline(always)]
-    fn read32(&self, _offset: usize) -> u32
+    fn read32(&self, offset: usize) -> u32
     where
         Self: IoKnownSize + IoCapable<u32>,
     {
-        build_error!("Backend does not support infallible 32-bit read")
+        let address = self.io_addr_assert::<u32>(offset);
+
+        // SAFETY: `address` has been validated by `io_addr_assert`.
+        unsafe { self.io_read(address) }
     }
 
     /// Infallible 64-bit read with compile-time bounds check.
     #[inline(always)]
-    fn read64(&self, _offset: usize) -> u64
+    fn read64(&self, offset: usize) -> u64
     where
         Self: IoKnownSize + IoCapable<u64>,
     {
-        build_error!("Backend does not support infallible 64-bit read")
+        let address = self.io_addr_assert::<u64>(offset);
+
+        // SAFETY: `address` has been validated by `io_addr_assert`.
+        unsafe { self.io_read(address) }
     }
 
     /// Infallible 8-bit write with compile-time bounds check.
     #[inline(always)]
-    fn write8(&self, _value: u8, _offset: usize)
+    fn write8(&self, value: u8, offset: usize)
     where
         Self: IoKnownSize + IoCapable<u8>,
     {
-        build_error!("Backend does not support infallible 8-bit write")
+        let address = self.io_addr_assert::<u8>(offset);
+
+        // SAFETY: `address` has been validated by `io_addr_assert`.
+        unsafe { self.io_write(value, address) }
     }
 
     /// Infallible 16-bit write with compile-time bounds check.
     #[inline(always)]
-    fn write16(&self, _value: u16, _offset: usize)
+    fn write16(&self, value: u16, offset: usize)
     where
         Self: IoKnownSize + IoCapable<u16>,
     {
-        build_error!("Backend does not support infallible 16-bit write")
+        let address = self.io_addr_assert::<u16>(offset);
+
+        // SAFETY: `address` has been validated by `io_addr_assert`.
+        unsafe { self.io_write(value, address) }
     }
 
     /// Infallible 32-bit write with compile-time bounds check.
     #[inline(always)]
-    fn write32(&self, _value: u32, _offset: usize)
+    fn write32(&self, value: u32, offset: usize)
     where
         Self: IoKnownSize + IoCapable<u32>,
     {
-        build_error!("Backend does not support infallible 32-bit write")
+        let address = self.io_addr_assert::<u32>(offset);
+
+        // SAFETY: `address` has been validated by `io_addr_assert`.
+        unsafe { self.io_write(value, address) }
     }
 
     /// Infallible 64-bit write with compile-time bounds check.
     #[inline(always)]
-    fn write64(&self, _value: u64, _offset: usize)
+    fn write64(&self, value: u64, offset: usize)
     where
         Self: IoKnownSize + IoCapable<u64>,
     {
-        build_error!("Backend does not support infallible 64-bit write")
+        let address = self.io_addr_assert::<u64>(offset);
+
+        // SAFETY: `address` has been validated by `io_addr_assert`.
+        unsafe { self.io_write(value, address) }
     }
 }
 
@@ -487,14 +554,36 @@ fn io_addr_assert<U>(&self, offset: usize) -> usize {
     }
 }
 
-// MMIO regions support 8, 16, and 32-bit accesses.
-impl<const SIZE: usize> IoCapable<u8> for Mmio<SIZE> {}
-impl<const SIZE: usize> IoCapable<u16> for Mmio<SIZE> {}
-impl<const SIZE: usize> IoCapable<u32> for Mmio<SIZE> {}
+/// Implements [`IoCapable`] on `$mmio` for `$ty` using `$read_fn` and `$write_fn`.
+macro_rules! impl_mmio_io_capable {
+    ($mmio:ident, $(#[$attr:meta])* $ty:ty, $read_fn:ident, $write_fn:ident) => {
+        $(#[$attr])*
+        impl<const SIZE: usize> IoCapable<$ty> for $mmio<SIZE> {
+            unsafe fn io_read(&self, address: usize) -> $ty {
+                // SAFETY: By the trait invariant `address` is a valid address for MMIO operations.
+                unsafe { bindings::$read_fn(address as *const c_void) }
+            }
 
+            unsafe fn io_write(&self, value: $ty, address: usize) {
+                // SAFETY: By the trait invariant `address` is a valid address for MMIO operations.
+                unsafe { bindings::$write_fn(value, address as *mut c_void) }
+            }
+        }
+    };
+}
+
+// MMIO regions support 8, 16, and 32-bit accesses.
+impl_mmio_io_capable!(Mmio, u8, readb, writeb);
+impl_mmio_io_capable!(Mmio, u16, readw, writew);
+impl_mmio_io_capable!(Mmio, u32, readl, writel);
 // MMIO regions on 64-bit systems also support 64-bit accesses.
-#[cfg(CONFIG_64BIT)]
-impl<const SIZE: usize> IoCapable<u64> for Mmio<SIZE> {}
+impl_mmio_io_capable!(
+    Mmio,
+    #[cfg(CONFIG_64BIT)]
+    u64,
+    readq,
+    writeq
+);
 
 impl<const SIZE: usize> Io for Mmio<SIZE> {
     /// Returns the base address of this mapping.
rust/kernel/pci/io.rs +34 -3
index 6ca4cf75594c..8c8aab2e3f22 100644
@@ -142,10 +142,41 @@ macro_rules! call_config_write {
     };
 }
 
+/// Implements [`IoCapable`] on [`ConfigSpace`] for `$ty` using `$read_fn` and `$write_fn`.
+macro_rules! impl_config_space_io_capable {
+    ($ty:ty, $read_fn:ident, $write_fn:ident) => {
+        impl<'a, S: ConfigSpaceKind> IoCapable<$ty> for ConfigSpace<'a, S> {
+            unsafe fn io_read(&self, address: usize) -> $ty {
+                let mut val: $ty = 0;
+
+                // Return value from C function is ignored in infallible accessors.
+                let _ret =
+                    // SAFETY: By the type invariant `self.pdev` is a valid address.
+                    // CAST: The offset is cast to `i32` because the C functions expect a 32-bit
+                    // signed offset parameter. PCI configuration space size is at most 4096 bytes,
+                    // so the value always fits within `i32` without truncation or sign change.
+                    unsafe { bindings::$read_fn(self.pdev.as_raw(), address as i32, &mut val) };
+
+                val
+            }
+
+            unsafe fn io_write(&self, value: $ty, address: usize) {
+                // Return value from C function is ignored in infallible accessors.
+                let _ret =
+                    // SAFETY: By the type invariant `self.pdev` is a valid address.
+                    // CAST: The offset is cast to `i32` because the C functions expect a 32-bit
+                    // signed offset parameter. PCI configuration space size is at most 4096 bytes,
+                    // so the value always fits within `i32` without truncation or sign change.
+                    unsafe { bindings::$write_fn(self.pdev.as_raw(), address as i32, value) };
+            }
+        }
+    };
+}
+
 // PCI configuration space supports 8, 16, and 32-bit accesses.
-impl<'a, S: ConfigSpaceKind> IoCapable<u8> for ConfigSpace<'a, S> {}
-impl<'a, S: ConfigSpaceKind> IoCapable<u16> for ConfigSpace<'a, S> {}
-impl<'a, S: ConfigSpaceKind> IoCapable<u32> for ConfigSpace<'a, S> {}
+impl_config_space_io_capable!(u8, pci_read_config_byte, pci_write_config_byte);
+impl_config_space_io_capable!(u16, pci_read_config_word, pci_write_config_word);
+impl_config_space_io_capable!(u32, pci_read_config_dword, pci_write_config_dword);
 
 impl<'a, S: ConfigSpaceKind> Io for ConfigSpace<'a, S> {
     /// Returns the base address of the I/O region. It is always 0 for configuration space.
Signature · 1 line
2.52.0
author reviewer
#3 lore raw

PATCH 2/6 rust: io: mem: use non-relaxed I/O ops in examples

In reply to Alexandre Courbot

The _relaxed I/O variant methods are about to be replaced by a wrapper type exposing this access pattern with the regular methods of the Io trait. Thus replace the examples to use the regular I/O methods.

Since these are examples, we want them to use the most standard ops anyway, and the relaxed variants were but an addition that was MMIO-specific.

---
 rust/kernel/io/mem.rs | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
rust/kernel/io/mem.rs +6 -4
index 620022cff401..7dc78d547f7a 100644
@@ -54,6 +54,7 @@ pub(crate) unsafe fn new(device: &'a Device<Bound>, resource: &'a Resource) -> S
     /// use kernel::{
     ///     bindings,
     ///     device::Core,
+    ///     io::Io,
     ///     of,
     ///     platform,
     /// };
@@ -78,9 +79,9 @@ pub(crate) unsafe fn new(device: &'a Device<Bound>, resource: &'a Resource) -> S
     ///       let io = iomem.access(pdev.as_ref())?;
     ///
     ///       // Read and write a 32-bit value at `offset`.
-    ///       let data = io.read32_relaxed(offset);
+    ///       let data = io.read32(offset);
     ///
-    ///       io.write32_relaxed(data, offset);
+    ///       io.write32(data, offset);
     ///
     ///       # Ok(SampleDriver)
     ///     }
@@ -117,6 +118,7 @@ pub fn iomap_exclusive_sized<const SIZE: usize>(
     /// use kernel::{
     ///     bindings,
     ///     device::Core,
+    ///     io::Io,
     ///     of,
     ///     platform,
     /// };
@@ -141,9 +143,9 @@ pub fn iomap_exclusive_sized<const SIZE: usize>(
     ///
     ///       let io = iomem.access(pdev.as_ref())?;
     ///
-    ///       let data = io.try_read32_relaxed(offset)?;
+    ///       let data = io.try_read32(offset)?;
     ///
-    ///       io.try_write32_relaxed(data, offset)?;
+    ///       io.try_write32(data, offset)?;
     ///
     ///       # Ok(SampleDriver)
     ///     }
Signature · 1 line
2.52.0
maintainer Reviewed-by on v1 2/6
#4 lore raw

Re: [PATCH 2/6] rust: io: mem: use non-relaxed I/O ops in examples

Quoted 66 lines · Alexandre Courbot

The _relaxed I/O variant methods are about to be replaced by a wrapper type exposing this access pattern with the regular methods of the Io trait. Thus replace the examples to use the regular I/O methods.

Since these are examples, we want them to use the most standard ops anyway, and the relaxed variants were but an addition that was MMIO-specific.

---
rust/kernel/io/mem.rs | 10 ++++++----

1 file changed, 6 insertions(+), 4 deletions(-)
rust/kernel/io/mem.rs +6 -4
index 620022cff401..7dc78d547f7a 100644
@@ -54,6 +54,7 @@ pub(crate) unsafe fn new(device: &'a Device<Bound>, resource: &'a Resource) -> S
    /// use kernel::{
    ///     bindings,
    ///     device::Core,
+    ///     io::Io,
    ///     of,
    ///     platform,
    /// };
@@ -78,9 +79,9 @@ pub(crate) unsafe fn new(device: &'a Device<Bound>, resource: &'a Resource) -> S
    ///       let io = iomem.access(pdev.as_ref())?;
    ///
    ///       // Read and write a 32-bit value at `offset`.
-    ///       let data = io.read32_relaxed(offset);
+    ///       let data = io.read32(offset);
    ///
-    ///       io.write32_relaxed(data, offset);
+    ///       io.write32(data, offset);
    ///
    ///       # Ok(SampleDriver)
    ///     }
@@ -117,6 +118,7 @@ pub fn iomap_exclusive_sized<const SIZE: usize>(
    /// use kernel::{
    ///     bindings,
    ///     device::Core,
+    ///     io::Io,
    ///     of,
    ///     platform,
    /// };
@@ -141,9 +143,9 @@ pub fn iomap_exclusive_sized<const SIZE: usize>(
    ///
    ///       let io = iomem.access(pdev.as_ref())?;
    ///
-    ///       let data = io.try_read32_relaxed(offset)?;
+    ///       let data = io.try_read32(offset)?;
    ///
-    ///       io.try_write32_relaxed(data, offset)?;
+    ///       io.try_write32(data, offset)?;
    ///
    ///       # Ok(SampleDriver)
    ///     }
Signature · 2 lines
-- 
2.52.0
author reviewer
#5 lore raw

PATCH 3/6 rust: io: provide Mmio relaxed ops through a wrapper type

In reply to Alexandre Courbot

Relaxed I/O accessors for Mmio are currently implemented as an extra set of methods that mirror the ones defined in Io, but with the _relaxed suffix.

This makes these methods impossible to use with generic code, which is a highly plausible proposition now that we have the Io trait.

Address this by adding a new RelaxedMmio wrapper type for Mmio that provides its own IoCapable implementations relying on the relaxed C accessors. This makes it possible to use relaxed operations on a Mmio simply by wrapping it, and to use RelaxedMmio in code generic against Io.

---
 rust/kernel/io.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 64 insertions(+), 2 deletions(-)
rust/kernel/io.rs +64 -2
index dc894a45bbcc..baa8d3baa20c 100644
@@ -556,9 +556,15 @@ fn io_addr_assert<U>(&self, offset: usize) -> usize {
 
 /// Implements [`IoCapable`] on `$mmio` for `$ty` using `$read_fn` and `$write_fn`.
 macro_rules! impl_mmio_io_capable {
-    ($mmio:ident, $(#[$attr:meta])* $ty:ty, $read_fn:ident, $write_fn:ident) => {
+    (
+        $mmio:ident $(< $($generics:tt),+ >)*,
+        $(#[$attr:meta])* $ty:ty,
+        $read_fn:ident, $write_fn:ident
+    ) => {
         $(#[$attr])*
-        impl<const SIZE: usize> IoCapable<$ty> for $mmio<SIZE> {
+        impl<$($($generics),+,)* const SIZE: usize> IoCapable<$ty>
+            for $mmio<$($($generics),+,)* SIZE>
+        {
             unsafe fn io_read(&self, address: usize) -> $ty {
                 // SAFETY: By the trait invariant `address` is a valid address for MMIO operations.
                 unsafe { bindings::$read_fn(address as *const c_void) }
@@ -695,3 +701,59 @@ pub unsafe fn from_raw(raw: &MmioRaw<SIZE>) -> &Self {
         call_mmio_write(writeq_relaxed) <- u64
     );
 }
+
+/// [`Mmio`] wrapper using relaxed accessors.
+///
+/// This provides an implementation of [`Io`] that uses relaxed I/O MMIO operands instead of the
+/// regular ones.
+///
+/// # Examples
+///
+/// ```no_run
+/// use kernel::io::{Io, Mmio, RelaxedMmio};
+///
+/// fn do_io(io: &Mmio<0x100>) {
+///     let relaxed_io = RelaxedMmio::from(io);
+///
+///     // The access is performed using `readl_relaxed` instead of `readl`.
+///     let v = relaxed_io.read32(0x10);
+/// }
+///
+/// ```
+#[repr(transparent)]
+pub struct RelaxedMmio<'a, const SIZE: usize = 0>(&'a Mmio<SIZE>);
+
+impl<'a, const SIZE: usize> From<&'a Mmio<SIZE>> for RelaxedMmio<'a, SIZE> {
+    fn from(value: &'a Mmio<SIZE>) -> Self {
+        Self(value)
+    }
+}
+
+impl<'a, const SIZE: usize> Io for RelaxedMmio<'a, SIZE> {
+    #[inline]
+    fn addr(&self) -> usize {
+        self.0.addr()
+    }
+
+    #[inline]
+    fn maxsize(&self) -> usize {
+        self.0.maxsize()
+    }
+}
+
+impl<'a, const SIZE: usize> IoKnownSize for RelaxedMmio<'a, SIZE> {
+    const MIN_SIZE: usize = SIZE;
+}
+
+// MMIO regions support 8, 16, and 32-bit accesses.
+impl_mmio_io_capable!(RelaxedMmio<'a>, u8, readb_relaxed, writeb_relaxed);
+impl_mmio_io_capable!(RelaxedMmio<'a>, u16, readw_relaxed, writew_relaxed);
+impl_mmio_io_capable!(RelaxedMmio<'a>, u32, readl_relaxed, writel_relaxed);
+// MMIO regions on 64-bit systems also support 64-bit accesses.
+impl_mmio_io_capable!(
+    RelaxedMmio<'a>,
+    #[cfg(CONFIG_64BIT)]
+    u64,
+    readq_relaxed,
+    writeq_relaxed
+);
Signature · 1 line
2.52.0
reviewer
#6 lore raw

Re: [PATCH 3/6] rust: io: provide Mmio relaxed ops through a wrapper type

Quoted 4 lines · Alexandre Courbot

Relaxed I/O accessors for Mmio are currently implemented as an extra set of methods that mirror the ones defined in Io, but with the _relaxed suffix.

Quoted 8 lines

This makes these methods impossible to use with generic code, which is a highly plausible proposition now that we have the Io trait.

Address this by adding a new RelaxedMmio wrapper type for Mmio that provides its own IoCapable implementations relying on the relaxed C accessors. This makes it possible to use relaxed operations on a Mmio simply by wrapping it, and to use RelaxedMmio in code generic against Io.

Hi Alex,

I think ultimately choice of order to use for each I/O access is local to the specific access, not a global property.

I know you can just do RelaxedMmio::from(io).access() for each single access too, but it feels quite verbose.

I guess one alternative design is explicit order on the access, e.g.

    io.read32(Relaxed)

Or

    io.read32(Full)

however this is verbose in some other ways... I'd like to hear how Boqun thinks on this one.

Quoted 43 lines
---
 rust/kernel/io.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 64 insertions(+), 2 deletions(-)
rust/kernel/io.rs +19 -2
index dc894a45bbcc..baa8d3baa20c 100644
@@ -556,9 +556,15 @@ fn io_addr_assert<U>(&self, offset: usize) -> usize {
 
 /// Implements [`IoCapable`] on `$mmio` for `$ty` using `$read_fn` and `$write_fn`.
 macro_rules! impl_mmio_io_capable {
-    ($mmio:ident, $(#[$attr:meta])* $ty:ty, $read_fn:ident, $write_fn:ident) => {
+    (
+        $mmio:ident $(< $($generics:tt),+ >)*,
+        $(#[$attr:meta])* $ty:ty,
+        $read_fn:ident, $write_fn:ident
+    ) => {
         $(#[$attr])*
-        impl<const SIZE: usize> IoCapable<$ty> for $mmio<SIZE> {
+        impl<$($($generics),+,)* const SIZE: usize> IoCapable<$ty>
+            for $mmio<$($($generics),+,)* SIZE>
+        {
             unsafe fn io_read(&self, address: usize) -> $ty {
                 // SAFETY: By the trait invariant `address` is a valid address for MMIO operations.
                 unsafe { bindings::$read_fn(address as *const c_void) }
@@ -695,3 +701,59 @@ pub unsafe fn from_raw(raw: &MmioRaw<SIZE>) -> &Self {
         call_mmio_write(writeq_relaxed) <- u64
     );
 }
+
+/// [`Mmio`] wrapper using relaxed accessors.
+///
+/// This provides an implementation of [`Io`] that uses relaxed I/O MMIO operands instead of the
+/// regular ones.
+///
+/// # Examples
+///
+/// ```no_run
+/// use kernel::io::{Io, Mmio, RelaxedMmio};
+///

rust/kernel/io.rs pub unsafe fn from_raw(raw: &MmioRaw<SIZE>) -> &Self { · line 724

Quoted 10 lines
rust/kernel/io.rs +10 -0
+/// fn do_io(io: &Mmio<0x100>) {
+///     let relaxed_io = RelaxedMmio::from(io);
+///
+///     // The access is performed using `readl_relaxed` instead of `readl`.
+///     let v = relaxed_io.read32(0x10);
+/// }
+///
+/// ```
+#[repr(transparent)]
+pub struct RelaxedMmio<'a, const SIZE: usize = 0>(&'a Mmio<SIZE>);

For a transparent wrapper, it should be

#[repr(transparent)]
pub struct RelaxedMmio<const SIZE: usize = 0>(Mmio<SIZE>);

Then the construction is

    fn from(value: &'a Mmio<SIZE>) -> &'a RelaxedMmio<SIZE> {
        unsafe { core::mem::transmute(value) }
    }

unfortunately this require unsafe (perhaps can be helped with macros that auto-generate this for transparent wrappers?), but this has the benefit that you get a reference and everything works without indirection (with your approach, I/O methods take &RelaxedMmio<'a, SIZE> and it double dereferencing). This also mean that you can copy the type or reborrow it.

Best,
Gary

Quoted 35 lines
rust/kernel/io.rs +35 -0
+
+impl<'a, const SIZE: usize> From<&'a Mmio<SIZE>> for RelaxedMmio<'a, SIZE> {
+    fn from(value: &'a Mmio<SIZE>) -> Self {
+        Self(value)
+    }
+}
+
+impl<'a, const SIZE: usize> Io for RelaxedMmio<'a, SIZE> {
+    #[inline]
+    fn addr(&self) -> usize {
+        self.0.addr()
+    }
+
+    #[inline]
+    fn maxsize(&self) -> usize {
+        self.0.maxsize()
+    }
+}
+
+impl<'a, const SIZE: usize> IoKnownSize for RelaxedMmio<'a, SIZE> {
+    const MIN_SIZE: usize = SIZE;
+}
+
+// MMIO regions support 8, 16, and 32-bit accesses.
+impl_mmio_io_capable!(RelaxedMmio<'a>, u8, readb_relaxed, writeb_relaxed);
+impl_mmio_io_capable!(RelaxedMmio<'a>, u16, readw_relaxed, writew_relaxed);
+impl_mmio_io_capable!(RelaxedMmio<'a>, u32, readl_relaxed, writel_relaxed);
+// MMIO regions on 64-bit systems also support 64-bit accesses.
+impl_mmio_io_capable!(
+    RelaxedMmio<'a>,
+    #[cfg(CONFIG_64BIT)]
+    u64,
+    readq_relaxed,
+    writeq_relaxed
+);
maintainer
#7 lore raw

Re: [PATCH 3/6] rust: io: provide Mmio relaxed ops through a wrapper type

Quoted 5 lines · Gary Guo

I think ultimately choice of order to use for each I/O access is local to the specific access, not a global property.

I know you can just do RelaxedMmio::from(io).access() for each single access too, but it feels quite verbose.

mmio.relaxed().access() would work as well.

Quoted 10 lines

I guess one alternative design is explicit order on the access, e.g.

    io.read32(Relaxed)

Or

    io.read32(Full)

however this is verbose in some other ways... I'd like to hear how Boqun thinks on this one.

This apprach would be misleading for a lot of other I/O backends. For instance, the I2C bus has no relaxed ordering.

maintainer
#8 lore raw

Re: [PATCH 3/6] rust: io: provide Mmio relaxed ops through a wrapper type

Quoted 15 lines · Danilo Krummrich
Quoted 5 lines · Gary Guo

I think ultimately choice of order to use for each I/O access is local to the specific access, not a global property.

I know you can just do RelaxedMmio::from(io).access() for each single access too, but it feels quite verbose.

mmio.relaxed().access() would work as well.

Quoted 6 lines

I guess one alternative design is explicit order on the access, e.g.

    io.read32(Relaxed)

Or

Quoted 7 lines
Quoted 4 lines
    io.read32(Full)

however this is verbose in some other ways... I'd like to hear how Boqun thinks on this one.

This apprach would be misleading for a lot of other I/O backends. For instance, the I2C bus has no relaxed ordering.

Forgot to mention, relaxed ordering accesses are far less common, hence this would become unnecessarily verbose.

reviewer
#9 lore raw

Re: [PATCH 3/6] rust: io: provide Mmio relaxed ops through a wrapper type

In reply to Danilo Krummrich
Quoted 10 lines · Danilo Krummrich
Quoted 9 lines · Gary Guo

I think ultimately choice of order to use for each I/O access is local to the specific access, not a global property.

I guess one alternative design is explicit order on the access, e.g.

    io.read32(Relaxed)

Or

Quoted 7 lines
Quoted 4 lines
    io.read32(Full)

however this is verbose in some other ways... I'd like to hear how Boqun thinks on this one.

This apprach would be misleading for a lot of other I/O backends. For instance, the I2C bus has no relaxed ordering.

This is a fair point.

Quoted 5 lines
Quoted 3 lines

I know you can just do RelaxedMmio::from(io).access() for each single access too, but it feels quite verbose.

mmio.relaxed().access() would work as well.

Indeed, this looks nice.

Best,
Gary

author reviewer
#10 lore raw

Re: [PATCH 3/6] rust: io: provide Mmio relaxed ops through a wrapper type

Quoted 22 lines · Gary Guo
Quoted 10 lines · Danilo Krummrich
Quoted 9 lines · Gary Guo

I think ultimately choice of order to use for each I/O access is local to the specific access, not a global property.

I guess one alternative design is explicit order on the access, e.g.

    io.read32(Relaxed)

Or

Quoted 7 lines
Quoted 4 lines
    io.read32(Full)

however this is verbose in some other ways... I'd like to hear how Boqun thinks on this one.

This apprach would be misleading for a lot of other I/O backends. For instance, the I2C bus has no relaxed ordering.

This is a fair point.

Quoted 1 line
Quoted 1 line
Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

I know you can just do RelaxedMmio::from(io).access() for each single access too, but it feels quite verbose.

mmio.relaxed().access() would work as well.

Indeed, this looks nice.

Yup, along with the proper wrapper layout that Gary mentioned that looks really nice and flows well within the code. I'll wait some more for more feedback and send v2 if there are no objections about the general direction of the patchset.

author reviewer
#11 lore raw

PATCH 4/6 rust: io: remove legacy relaxed accessors of Mmio

In reply to Alexandre Courbot

The relaxed access functionality is now provided by the RelaxedMmio wrapper type, and we don't have any user of the legacy methods left. Remove them.

---
 rust/kernel/io.rs | 40 ----------------------------------------
 1 file changed, 40 deletions(-)
rust/kernel/io.rs +0 -40
index baa8d3baa20c..e1094a237ff7 100644
@@ -660,46 +660,6 @@ pub unsafe fn from_raw(raw: &MmioRaw<SIZE>) -> &Self {
         // SAFETY: `Mmio` is a transparent wrapper around `MmioRaw`.
         unsafe { &*core::ptr::from_ref(raw).cast() }
     }
-
-    define_read!(infallible, pub read8_relaxed, call_mmio_read(readb_relaxed) -> u8);
-    define_read!(infallible, pub read16_relaxed, call_mmio_read(readw_relaxed) -> u16);
-    define_read!(infallible, pub read32_relaxed, call_mmio_read(readl_relaxed) -> u32);
-    define_read!(
-        infallible,
-        #[cfg(CONFIG_64BIT)]
-        pub read64_relaxed,
-        call_mmio_read(readq_relaxed) -> u64
-    );
-
-    define_read!(fallible, pub try_read8_relaxed, call_mmio_read(readb_relaxed) -> u8);
-    define_read!(fallible, pub try_read16_relaxed, call_mmio_read(readw_relaxed) -> u16);
-    define_read!(fallible, pub try_read32_relaxed, call_mmio_read(readl_relaxed) -> u32);
-    define_read!(
-        fallible,
-        #[cfg(CONFIG_64BIT)]
-        pub try_read64_relaxed,
-        call_mmio_read(readq_relaxed) -> u64
-    );
-
-    define_write!(infallible, pub write8_relaxed, call_mmio_write(writeb_relaxed) <- u8);
-    define_write!(infallible, pub write16_relaxed, call_mmio_write(writew_relaxed) <- u16);
-    define_write!(infallible, pub write32_relaxed, call_mmio_write(writel_relaxed) <- u32);
-    define_write!(
-        infallible,
-        #[cfg(CONFIG_64BIT)]
-        pub write64_relaxed,
-        call_mmio_write(writeq_relaxed) <- u64
-    );
-
-    define_write!(fallible, pub try_write8_relaxed, call_mmio_write(writeb_relaxed) <- u8);
-    define_write!(fallible, pub try_write16_relaxed, call_mmio_write(writew_relaxed) <- u16);
-    define_write!(fallible, pub try_write32_relaxed, call_mmio_write(writel_relaxed) <- u32);
-    define_write!(
-        fallible,
-        #[cfg(CONFIG_64BIT)]
-        pub try_write64_relaxed,
-        call_mmio_write(writeq_relaxed) <- u64
-    );
 }
 
 /// [`Mmio`] wrapper using relaxed accessors.
Signature · 1 line
2.52.0
maintainer Reviewed-by on v1 4/6
#12 lore raw

Re: [PATCH 4/6] rust: io: remove legacy relaxed accessors of Mmio

Quoted 69 lines · Alexandre Courbot

The relaxed access functionality is now provided by the RelaxedMmio wrapper type, and we don't have any user of the legacy methods left. Remove them.

---
rust/kernel/io.rs | 40 ----------------------------------------

1 file changed, 40 deletions(-)
rust/kernel/io.rs +0 -40
index baa8d3baa20c..e1094a237ff7 100644
@@ -660,46 +660,6 @@ pub unsafe fn from_raw(raw: &MmioRaw<SIZE>) -> &Self {
        // SAFETY: `Mmio` is a transparent wrapper around `MmioRaw`.
        unsafe { &*core::ptr::from_ref(raw).cast() }
    }
-
-    define_read!(infallible, pub read8_relaxed, call_mmio_read(readb_relaxed) -> u8);
-    define_read!(infallible, pub read16_relaxed, call_mmio_read(readw_relaxed) -> u16);
-    define_read!(infallible, pub read32_relaxed, call_mmio_read(readl_relaxed) -> u32);
-    define_read!(
-        infallible,
-        #[cfg(CONFIG_64BIT)]
-        pub read64_relaxed,
-        call_mmio_read(readq_relaxed) -> u64
-    );
-
-    define_read!(fallible, pub try_read8_relaxed, call_mmio_read(readb_relaxed) -> u8);
-    define_read!(fallible, pub try_read16_relaxed, call_mmio_read(readw_relaxed) -> u16);
-    define_read!(fallible, pub try_read32_relaxed, call_mmio_read(readl_relaxed) -> u32);
-    define_read!(
-        fallible,
-        #[cfg(CONFIG_64BIT)]
-        pub try_read64_relaxed,
-        call_mmio_read(readq_relaxed) -> u64
-    );
-
-    define_write!(infallible, pub write8_relaxed, call_mmio_write(writeb_relaxed) <- u8);
-    define_write!(infallible, pub write16_relaxed, call_mmio_write(writew_relaxed) <- u16);
-    define_write!(infallible, pub write32_relaxed, call_mmio_write(writel_relaxed) <- u32);
-    define_write!(
-        infallible,
-        #[cfg(CONFIG_64BIT)]
-        pub write64_relaxed,
-        call_mmio_write(writeq_relaxed) <- u64
-    );
-
-    define_write!(fallible, pub try_write8_relaxed, call_mmio_write(writeb_relaxed) <- u8);
-    define_write!(fallible, pub try_write16_relaxed, call_mmio_write(writew_relaxed) <- u16);
-    define_write!(fallible, pub try_write32_relaxed, call_mmio_write(writel_relaxed) <- u32);
-    define_write!(
-        fallible,
-        #[cfg(CONFIG_64BIT)]
-        pub try_write64_relaxed,
-        call_mmio_write(writeq_relaxed) <- u64
-    );
 }
 
 /// [`Mmio`] wrapper using relaxed accessors.
Signature · 2 lines
-- 
2.52.0
author reviewer
#13 lore raw

PATCH 5/6 rust: pci: io: remove overloaded Io methods of ConfigSpace

In reply to Alexandre Courbot

Since ConfigSpace now has the relevant implementations of IoCapable, the default methods of Io can be used in place of the overloaded ones. Remove them as well as the macros generating them.

---
 rust/kernel/io.rs     |  3 ---
 rust/kernel/pci/io.rs | 70 ---------------------------------------------------
 2 files changed, 73 deletions(-)
rust/kernel/io.rs +0 -3
index e1094a237ff7..0e8031dfe0f0 100644
@@ -226,8 +226,6 @@ macro_rules! define_read {
         }
     };
 }
-pub(crate) use define_read;
-
 macro_rules! define_write {
     (infallible, $(#[$attr:meta])* $vis:vis $name:ident, $call_macro:ident($c_fn:ident) <-
      $type_name:ty) => {
@@ -259,7 +257,6 @@ macro_rules! define_write {
         }
     };
 }
-pub(crate) use define_write;
 
 /// Checks whether an access of type `U` at the given `offset`
 /// is valid within this region.
rust/kernel/pci/io.rs +0 -70

88 lines not on this page · raw message

Signature · 1 line
2.52.0
maintainer Reviewed-by on v1 5/6
#14 lore raw

Re: [PATCH 5/6] rust: pci: io: remove overloaded Io methods of ConfigSpace

Quoted 135 lines · Alexandre Courbot

Since ConfigSpace now has the relevant implementations of IoCapable, the default methods of Io can be used in place of the overloaded ones. Remove them as well as the macros generating them.

---
rust/kernel/io.rs | 3 ---
rust/kernel/pci/io.rs | 70 ---------------------------------------------------

2 files changed, 73 deletions(-)
rust/kernel/io.rs +0 -3
index e1094a237ff7..0e8031dfe0f0 100644
@@ -226,8 +226,6 @@ macro_rules! define_read {
        }
    };
 }
-pub(crate) use define_read;
-
 macro_rules! define_write {
    (infallible, $(#[$attr:meta])* $vis:vis $name:ident, $call_macro:ident($c_fn:ident) <-
     $type_name:ty) => {
@@ -259,7 +257,6 @@ macro_rules! define_write {
        }
    };
 }
-pub(crate) use define_write;
 
 /// Checks whether an access of type `U` at the given `offset`
 /// is valid within this region.
rust/kernel/pci/io.rs +0 -70
index 8c8aab2e3f22..ae78676c927f 100644
@@ -8,8 +8,6 @@
    device,
    devres::Devres,
    io::{
-        define_read,
-        define_write,
        Io,
        IoCapable,
        IoKnownSize,
@@ -85,63 +83,6 @@ pub struct ConfigSpace<'a, S: ConfigSpaceKind = Extended> {
    _marker: PhantomData<S>,
 }
 
-/// Internal helper macros used to invoke C PCI configuration space read functions.
-///
-/// This macro is intended to be used by higher-level PCI configuration space access macros
-/// (define_read) and provides a unified expansion for infallible vs. fallible read semantics. It
-/// emits a direct call into the corresponding C helper and performs the required cast to the Rust
-/// return type.
-///
-/// # Parameters
-///
-/// * `$c_fn` – The C function performing the PCI configuration space write.
-/// * `$self` – The I/O backend object.
-/// * `$ty` – The type of the value to read.
-/// * `$addr` – The PCI configuration space offset to read.
-///
-/// This macro does not perform any validation; all invariants must be upheld by the higher-level
-/// abstraction invoking it.
-macro_rules! call_config_read {
-    (infallible, $c_fn:ident, $self:ident, $ty:ty, $addr:expr) => {{
-        let mut val: $ty = 0;
-        // SAFETY: By the type invariant `$self.pdev` is a valid address.
-        // CAST: The offset is cast to `i32` because the C functions expect a 32-bit signed offset
-        // parameter. PCI configuration space size is at most 4096 bytes, so the value always fits
-        // within `i32` without truncation or sign change.
-        // Return value from C function is ignored in infallible accessors.
-        let _ret = unsafe { bindings::$c_fn($self.pdev.as_raw(), $addr as i32, &mut val) };
-        val
-    }};
-}
-
-/// Internal helper macros used to invoke C PCI configuration space write functions.
-///
-/// This macro is intended to be used by higher-level PCI configuration space access macros
-/// (define_write) and provides a unified expansion for infallible vs. fallible read semantics. It
-/// emits a direct call into the corresponding C helper and performs the required cast to the Rust
-/// return type.
-///
-/// # Parameters
-///
-/// * `$c_fn` – The C function performing the PCI configuration space write.
-/// * `$self` – The I/O backend object.
-/// * `$ty` – The type of the written value.
-/// * `$addr` – The configuration space offset to write.
-/// * `$value` – The value to write.
-///
-/// This macro does not perform any validation; all invariants must be upheld by the higher-level
-/// abstraction invoking it.
-macro_rules! call_config_write {
-    (infallible, $c_fn:ident, $self:ident, $ty:ty, $addr:expr, $value:expr) => {
-        // SAFETY: By the type invariant `$self.pdev` is a valid address.
-        // CAST: The offset is cast to `i32` because the C functions expect a 32-bit signed offset
-        // parameter. PCI configuration space size is at most 4096 bytes, so the value always fits
-        // within `i32` without truncation or sign change.
-        // Return value from C function is ignored in infallible accessors.
-        let _ret = unsafe { bindings::$c_fn($self.pdev.as_raw(), $addr as i32, $value) };
-    };
-}
-
 /// Implements [`IoCapable`] on [`ConfigSpace`] for `$ty` using `$read_fn` and `$write_fn`.
 macro_rules! impl_config_space_io_capable {
    ($ty:ty, $read_fn:ident, $write_fn:ident) => {
@@ -190,17 +131,6 @@ fn addr(&self) -> usize {
    fn maxsize(&self) -> usize {
        self.pdev.cfg_size().into_raw()
    }
-
-    // PCI configuration space does not support fallible operations.
-    // The default implementations from the Io trait are not used.
-
-    define_read!(infallible, read8, call_config_read(pci_read_config_byte) -> u8);
-    define_read!(infallible, read16, call_config_read(pci_read_config_word) -> u16);
-    define_read!(infallible, read32, call_config_read(pci_read_config_dword) -> u32);
-
-    define_write!(infallible, write8, call_config_write(pci_write_config_byte) <- u8);
-    define_write!(infallible, write16, call_config_write(pci_write_config_word) <- u16);
-    define_write!(infallible, write32, call_config_write(pci_write_config_dword) <- u32);
 }
 
 impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> {
Signature · 2 lines
-- 
2.52.0
author reviewer
#15 lore raw

PATCH 6/6 rust: io: remove overloaded Io methods of Mmio

In reply to Alexandre Courbot

Since Mmio now has the relevant implementations of IoCapable, the default methods of Io can be used in place of the overloaded ones. Remove them as well as the macros generating them.

---
 rust/kernel/io.rs | 161 ------------------------------------------------------
 1 file changed, 161 deletions(-)
rust/kernel/io.rs +0 -161
index 0e8031dfe0f0..d2e498c9a0d5 100644
@@ -137,127 +137,6 @@ pub fn maxsize(&self) -> usize {
 #[repr(transparent)]
 pub struct Mmio<const SIZE: usize = 0>(MmioRaw<SIZE>);
 
-/// Internal helper macros used to invoke C MMIO read functions.
-///
-/// This macro is intended to be used by higher-level MMIO access macros (define_read) and provides
-/// a unified expansion for infallible vs. fallible read semantics. It emits a direct call into the
-/// corresponding C helper and performs the required cast to the Rust return type.
-///
-/// # Parameters
-///
-/// * `$c_fn` – The C function performing the MMIO read.
-/// * `$self` – The I/O backend object.
-/// * `$ty` – The type of the value to be read.
-/// * `$addr` – The MMIO address to read.
-///
-/// This macro does not perform any validation; all invariants must be upheld by the higher-level
-/// abstraction invoking it.
-macro_rules! call_mmio_read {
-    (infallible, $c_fn:ident, $self:ident, $type:ty, $addr:expr) => {
-        // SAFETY: By the type invariant `addr` is a valid address for MMIO operations.
-        unsafe { bindings::$c_fn($addr as *const c_void) as $type }
-    };
-
-    (fallible, $c_fn:ident, $self:ident, $type:ty, $addr:expr) => {{
-        // SAFETY: By the type invariant `addr` is a valid address for MMIO operations.
-        Ok(unsafe { bindings::$c_fn($addr as *const c_void) as $type })
-    }};
-}
-
-/// Internal helper macros used to invoke C MMIO write functions.
-///
-/// This macro is intended to be used by higher-level MMIO access macros (define_write) and provides
-/// a unified expansion for infallible vs. fallible write semantics. It emits a direct call into the
-/// corresponding C helper and performs the required cast to the Rust return type.
-///
-/// # Parameters
-///
-/// * `$c_fn` – The C function performing the MMIO write.
-/// * `$self` – The I/O backend object.
-/// * `$ty` – The type of the written value.
-/// * `$addr` – The MMIO address to write.
-/// * `$value` – The value to write.
-///
-/// This macro does not perform any validation; all invariants must be upheld by the higher-level
-/// abstraction invoking it.
-macro_rules! call_mmio_write {
-    (infallible, $c_fn:ident, $self:ident, $ty:ty, $addr:expr, $value:expr) => {
-        // SAFETY: By the type invariant `addr` is a valid address for MMIO operations.
-        unsafe { bindings::$c_fn($value, $addr as *mut c_void) }
-    };
-
-    (fallible, $c_fn:ident, $self:ident, $ty:ty, $addr:expr, $value:expr) => {{
-        // SAFETY: By the type invariant `addr` is a valid address for MMIO operations.
-        unsafe { bindings::$c_fn($value, $addr as *mut c_void) };
-        Ok(())
-    }};
-}
-
-macro_rules! define_read {
-    (infallible, $(#[$attr:meta])* $vis:vis $name:ident, $call_macro:ident($c_fn:ident) ->
-     $type_name:ty) => {
-        /// Read IO data from a given offset known at compile time.
-        ///
-        /// Bound checks are performed on compile time, hence if the offset is not known at compile
-        /// time, the build will fail.
-        $(#[$attr])*
-        // Always inline to optimize out error path of `io_addr_assert`.
-        #[inline(always)]
-        $vis fn $name(&self, offset: usize) -> $type_name {
-            let addr = self.io_addr_assert::<$type_name>(offset);
-
-            // SAFETY: By the type invariant `addr` is a valid address for IO operations.
-            $call_macro!(infallible, $c_fn, self, $type_name, addr)
-        }
-    };
-
-    (fallible, $(#[$attr:meta])* $vis:vis $try_name:ident, $call_macro:ident($c_fn:ident) ->
-     $type_name:ty) => {
-        /// Read IO data from a given offset.
-        ///
-        /// Bound checks are performed on runtime, it fails if the offset (plus the type size) is
-        /// out of bounds.
-        $(#[$attr])*
-        $vis fn $try_name(&self, offset: usize) -> Result<$type_name> {
-            let addr = self.io_addr::<$type_name>(offset)?;
-
-            // SAFETY: By the type invariant `addr` is a valid address for IO operations.
-            $call_macro!(fallible, $c_fn, self, $type_name, addr)
-        }
-    };
-}
-macro_rules! define_write {
-    (infallible, $(#[$attr:meta])* $vis:vis $name:ident, $call_macro:ident($c_fn:ident) <-
-     $type_name:ty) => {
-        /// Write IO data from a given offset known at compile time.
-        ///
-        /// Bound checks are performed on compile time, hence if the offset is not known at compile
-        /// time, the build will fail.
-        $(#[$attr])*
-        // Always inline to optimize out error path of `io_addr_assert`.
-        #[inline(always)]
-        $vis fn $name(&self, value: $type_name, offset: usize) {
-            let addr = self.io_addr_assert::<$type_name>(offset);
-
-            $call_macro!(infallible, $c_fn, self, $type_name, addr, value);
-        }
-    };
-
-    (fallible, $(#[$attr:meta])* $vis:vis $try_name:ident, $call_macro:ident($c_fn:ident) <-
-     $type_name:ty) => {
-        /// Write IO data from a given offset.
-        ///
-        /// Bound checks are performed on runtime, it fails if the offset (plus the type size) is
-        /// out of bounds.
-        $(#[$attr])*
-        $vis fn $try_name(&self, value: $type_name, offset: usize) -> Result {
-            let addr = self.io_addr::<$type_name>(offset)?;
-
-            $call_macro!(fallible, $c_fn, self, $type_name, addr, value)
-        }
-    };
-}
-
 /// Checks whether an access of type `U` at the given `offset`
 /// is valid within this region.
 #[inline]
@@ -600,46 +479,6 @@ fn addr(&self) -> usize {
     fn maxsize(&self) -> usize {
         self.0.maxsize()
     }
-
-    define_read!(fallible, try_read8, call_mmio_read(readb) -> u8);
-    define_read!(fallible, try_read16, call_mmio_read(readw) -> u16);
-    define_read!(fallible, try_read32, call_mmio_read(readl) -> u32);
-    define_read!(
-        fallible,
-        #[cfg(CONFIG_64BIT)]
-        try_read64,
-        call_mmio_read(readq) -> u64
-    );
-
-    define_write!(fallible, try_write8, call_mmio_write(writeb) <- u8);
-    define_write!(fallible, try_write16, call_mmio_write(writew) <- u16);
-    define_write!(fallible, try_write32, call_mmio_write(writel) <- u32);
-    define_write!(
-        fallible,
-        #[cfg(CONFIG_64BIT)]
-        try_write64,
-        call_mmio_write(writeq) <- u64
-    );
-
-    define_read!(infallible, read8, call_mmio_read(readb) -> u8);
-    define_read!(infallible, read16, call_mmio_read(readw) -> u16);
-    define_read!(infallible, read32, call_mmio_read(readl) -> u32);
-    define_read!(
-        infallible,
-        #[cfg(CONFIG_64BIT)]
-        read64,
-        call_mmio_read(readq) -> u64
-    );
-
-    define_write!(infallible, write8, call_mmio_write(writeb) <- u8);
-    define_write!(infallible, write16, call_mmio_write(writew) <- u16);
-    define_write!(infallible, write32, call_mmio_write(writel) <- u32);
-    define_write!(
-        infallible,
-        #[cfg(CONFIG_64BIT)]
-        write64,
-        call_mmio_write(writeq) <- u64
-    );
 }
 
 impl<const SIZE: usize> IoKnownSize for Mmio<SIZE> {
Signature · 1 line
2.52.0
maintainer Acked-by on the v1 series
#17 lore raw
In reply to Alexandre Courbot
Quoted 44 lines · Alexandre Courbot

IoCapable<T> is currently used as a marker trait to signal that the methods of the Io trait corresponding to T have been overridden by the implementor (the default implementations triggering a build-time error).

This goes against the DRY principle and separates the signaling of the capability from its implementation, making it possible to forget a step while implementing a new Io.

Another undesirable side-effect is that it makes the implementation of I/O backends boilerplate-y and convoluted: currently this is done using two levels of imbricated macros that generate unsafe code.

This patchset fixes these issues by turning IoCapable into a functional trait including the raw implementation of the I/O accessors for T using unsafe methods that work with an arbitrary address, and making the default methods of Io call into these implementations after checking the bounds.

This makes overriding these accessors on all I/O backends unneeded, resulting in a net -90 LoCs while avoiding a violation of the DRY principle and reducing (and simplifying) the use of macros generating unsafe code.

Patch 1 adds the io_read and io_write unsafe methods to IoCapable, provides the required implementations for Mmio and pci::ConfigSpace, and make the default I/O accessors of Io call into them instead of failing.

Patches 2 to 4 get rid of the _relaxed variants we had in Mmio, since these are not usable in code generic against Io and makes use of the macros we want to remove. They are replaced by a RelaxedMmio wrapper type that implements the required IoCapables and is thus usable in generic code.

Patches 5 and 6 remove the overloaded implementations of the Io methods for pci::ConfigSpace and Mmio, respectively, while also deleting the macros that have become unused.

There is more work coming on top of this patchset (notably the register! macro with proper I/O), but I wanted to send this work first as it stands on its own IMHO and is more digestible from a review perspective.

Quoted 7 lines

The base for this patchset is driver-core-testing.

Cc Zhi Wang <[email protected]>
Cc Lyude Paul <[email protected]>
Cc Eliot Courtney <[email protected]>

Overall looks great!

With the mmio.relaxed().write(_) syntax suggested in the thread on patch 3, this is acked by me.