Re: [PATCH v7 05/10] rust: io: add IoLoc and IoWrite types
From: Gary Guo
Date: Fri Feb 27 2026 - 13:14:11 EST
On Tue Feb 24, 2026 at 2:21 PM GMT, Alexandre Courbot wrote:
> I/O accesses are defined by the following properties:
>
> - For reads, a start address, a width, and a type to interpret the read
> value as,
> - For writes, the same as above, and a value to write.
>
> Introduce the `IoLoc` trait, which allows implementing types to specify
> the address a type expects to be accessed at, as well as the width of
> the access, and the user-facing type used to perform the access.
>
> This allows read operations to be made generic with the `read` method
> over an `IoLoc` argument.
>
> Write operations need a value to write on top of the `IoLoc`: fulfill
> that purpose with the `IoWrite` type, which is the combination of an
> `IoLoc` and a value of the type it expects. This allows write operations
> to be made generic with the `write` method over a single `IoWrite`
> argument.
>
> The main purpose of these new entities is to allow register types to be
> written using these generic `read` and `write` methods of `Io`.
>
> Co-developed-by: Gary Guo <gary@xxxxxxxxxxx>
> Signed-off-by: Alexandre Courbot <acourbot@xxxxxxxxxx>
> ---
> rust/kernel/io.rs | 241 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
> 1 file changed, 241 insertions(+)
>
> diff --git a/rust/kernel/io.rs b/rust/kernel/io.rs
> index b150743ffa4f..fdd2549d8e13 100644
> --- a/rust/kernel/io.rs
> +++ b/rust/kernel/io.rs
> @@ -173,6 +173,158 @@ pub trait IoCapable<T> {
> unsafe fn io_write(&self, value: T, address: usize);
> }
>
> +/// Describes a given I/O location: its offset, width, and return type.
> +///
> +/// This trait is the key abstraction allowing [`Io::read`], [`Io::write`], and [`Io::update`]
> +/// to work uniformly with both raw `usize` offsets (for primitive types like `u32`) and typed
> +/// ones.
> +///
> +/// An `IoLoc<T>` carries three pieces of information:
> +///
> +/// - The offset to access (returned by [`IoLoc::offset`]),
> +/// - The width of the access (determined by [`IoLoc::IoType`]),
> +/// - The type `T` in which data is returned or provided.
> +///
> +/// `T` and `IoType` may differ: for instance, a typed register has `T` = the register type with
> +/// its bitfields, and `IoType` = its backing primitive (e.g. `u32`), with `Into` conversions
> +/// between them.
> +///
> +/// An `IoLoc` can be passed directly to [`Io::read`] or [`Io::try_read`] to obtain a value, or
> +/// turned into an [`IoWrite`] via [`IoLoc::set`] to be passed to [`Io::write`] or
> +/// [`Io::try_write`].
> +pub trait IoLoc<T>: Copy
> +where
> + T: Into<Self::IoType>,
> + Self::IoType: Into<T>,
> +{
> + /// Size (`u8`, `u16`, etc) of the I/O performed on the returned [`offset`](IoLoc::offset).
> + type IoType;
> +
> + /// Returns the offset of this location.
> + fn offset(self) -> usize;
> +
> + /// Turns this location into an [`IoWrite`] with the initial `value`.
> + fn set(self, value: T) -> IoWrite<T, Self> {
> + IoWrite { value, loc: self }
> + }
> +
> + /// Turns this location into an [`IoWrite`] with the initial value `0`.
> + fn zeroed(self) -> IoWrite<T, Self>
> + where
> + T: Zeroable,
> + {
> + self.set(pin_init::zeroed())
> + }
> +
> + /// Turns this location into an [`IoWrite`] with the initial [`Default`] value of `T`.
> + fn default(self) -> IoWrite<T, Self>
> + where
> + T: Default,
> + {
> + self.set(Default::default())
> + }
> +
> + /// Turns this location into an [`IoWrite`] initialized from `0` and transformed by `f`.
> + ///
> + /// This is a shortcut for `self.zeroed().update(f)`.
> + fn init<F>(self, f: F) -> IoWrite<T, Self>
> + where
> + T: Zeroable,
> + F: FnOnce(T) -> T,
> + {
> + self.zeroed().update(f)
> + }
> +
> + /// Turns this location into an [`IoWrite`] initialized from `0` and transformed by `f`.
> + ///
> + /// `f` is expected to return a [`Result<T>`].
> + ///
> + /// This is a shortcut for `self.zeroed().try_update(f)`.
> + fn try_init<F, E>(self, f: F) -> Result<IoWrite<T, Self>, E>
> + where
> + T: Zeroable,
> + F: FnOnce(T) -> Result<T, E>,
> + {
> + self.zeroed().try_update(f)
> + }
> +
> + /// Turns this location into an [`IoWrite`] initialized from [`Default`] and transformed
> + /// by `f`.
> + ///
> + /// This is a shortcut for `self.default().update(f)`.
> + fn init_default<F>(self, f: F) -> IoWrite<T, Self>
> + where
> + T: Default,
> + F: FnOnce(T) -> T,
> + {
> + self.default().update(f)
> + }
> +
> + /// Turns this location into an [`IoWrite`] initialized from [`Default`] and transformed by
> + /// `f`.
> + ///
> + /// `f` is expected to return a [`Result<T>`].
> + ///
> + /// This is a shortcut for `self.default().try_update(f)`.
> + fn try_init_default<F, E>(self, f: F) -> Result<IoWrite<T, Self>, E>
> + where
> + T: Default,
> + F: FnOnce(T) -> Result<T, E>,
> + {
> + self.default().try_update(f)
> + }
> +}
> +
> +/// A pending I/O write operation, bundling a value with the [`IoLoc`] it should be written to.
> +///
> +/// Created by [`IoLoc::set`], [`IoLoc::zeroed`], [`IoLoc::default`], [`IoLoc::init`], or
> +/// [`IoLoc::init_default`], and consumed by [`Io::write`] or [`Io::try_write`] to perform the
> +/// actual write.
> +///
> +/// The value can be modified before writing using [`IoWrite::update`] or [`IoWrite::try_update`],
> +/// enabling a builder pattern:
> +///
> +/// ```ignore
> +/// io.write(REGISTER.init(|v| v.with_field(x)));
> +/// ```
Thinking about this again, I think we might still want to write
io.write(REGISTER, value)
Granted, this does mean that we will write `REGISTER` twice in some cases:
io.write(REGISTER, REGISTER::default().with_field(foo));
But, we have no redundancy for the update case:
io.update(REGISTER, |v| v.with_field(foo));
The reason for this thought is that conceptually, the type of a register is not
necessarily coupled with the register itself. This is the case currently for
register arrays, but also the case when we think in the long term where
bitfields become decoupled from `register!`. People also might just want to
define a register of u32 without any bitfields at all, and in this case writing
io.write(REGISTER, u32_value)
looks nicer than
io.write(REGISTER.set(u32_value))
Spelling out the "offset" explictly, arguably, is also more natural for a C
programmer, and also simpler on the implementation side (all the helper methods
on `IoLoc` would go away).
Best,
Gary
> +pub struct IoWrite<T, R>
> +where
> + R: IoLoc<T>,
> + T: Into<R::IoType>,
> +{
> + value: T,
> + loc: R,
> +}
> +
> +impl<R, T> IoWrite<T, R>
> +where
> + R: IoLoc<T>,
> + T: Into<R::IoType>,
> +{
> + /// Transforms the value to be written by applying `f`, returning the modified [`IoWrite`].
> + #[inline(always)]
> + pub fn update<F>(mut self, f: F) -> Self
> + where
> + F: FnOnce(T) -> T,
> + {
> + self.value = f(self.value);
> +
> + self
> + }
> +
> + /// Transforms the value to be written by applying `f`, returning the modified [`IoWrite`] on
> + /// success.
> + #[inline(always)]
> + pub fn try_update<F, E>(mut self, f: F) -> Result<Self, E>
> + where
> + F: FnOnce(T) -> Result<T, E>,
> + {
> + self.value = f(self.value)?;
> +
> + Ok(self)
> + }
> +}
> +
> /// Types implementing this trait (e.g. MMIO BARs or PCI config regions)
> /// can perform I/O operations on regions of memory.
> ///
> @@ -406,6 +558,95 @@ fn write64(&self, value: u64, offset: usize)
> // SAFETY: `address` has been validated by `io_addr_assert`.
> unsafe { self.io_write(value, address) }
> }
> +
> + /// Generic fallible read with runtime bounds check.
> + #[inline(always)]
> + fn try_read<T, R>(&self, r: R) -> Result<T>
> + where
> + R: IoLoc<T>,
> + T: Into<R::IoType>,
> + Self: IoCapable<R::IoType>,
> + {
> + let address = self.io_addr::<R::IoType>(r.offset())?;
> +
> + // SAFETY: `address` has been validated by `io_addr`.
> + Ok(unsafe { self.io_read(address) }.into())
> + }
> +
> + /// Generic fallible write with runtime bounds check.
> + #[inline(always)]
> + fn try_write<T, R>(&self, op: IoWrite<T, R>) -> Result
> + where
> + R: IoLoc<T>,
> + T: Into<R::IoType>,
> + Self: IoCapable<R::IoType>,
> + {
> + let address = self.io_addr::<R::IoType>(op.loc.offset())?;
> +
> + // SAFETY: `address` has been validated by `io_addr`.
> + unsafe { self.io_write(op.value.into(), address) };
> + Ok(())
> + }
> +
> + /// Generic fallible update with runtime bounds check.
> + ///
> + /// Caution: this does not perform any synchronization. Race conditions can occur in case of
> + /// concurrent access.
> + #[inline(always)]
> + fn try_update<T, R, F>(&self, r: R, f: F) -> Result
> + where
> + R: IoLoc<T>,
> + T: Into<R::IoType>,
> + Self: IoCapable<R::IoType>,
> + F: FnOnce(T) -> T,
> + {
> + let v = self.try_read(r)?;
> + self.try_write(r.set(f(v)))
> + }
> +
> + /// Generic infallible read with compile-time bounds check.
> + #[inline(always)]
> + fn read<T, R>(&self, r: R) -> T
> + where
> + R: IoLoc<T>,
> + T: Into<R::IoType>,
> + Self: IoKnownSize + IoCapable<R::IoType>,
> + {
> + let address = self.io_addr_assert::<R::IoType>(r.offset());
> +
> + // SAFETY: `address` has been validated by `io_addr_assert`.
> + unsafe { self.io_read(address) }.into()
> + }
> +
> + /// Generic infallible write with compile-time bounds check.
> + #[inline(always)]
> + fn write<T, R>(&self, op: IoWrite<T, R>)
> + where
> + R: IoLoc<T>,
> + T: Into<R::IoType>,
> + Self: IoKnownSize + IoCapable<R::IoType>,
> + {
> + let address = self.io_addr_assert::<R::IoType>(op.loc.offset());
> +
> + // SAFETY: `address` has been validated by `io_addr_assert`.
> + unsafe { self.io_write(op.value.into(), address) }
> + }
> +
> + /// Generic infallible update with compile-time bounds check.
> + ///
> + /// Caution: this does not perform any synchronization. Race conditions can occur in case of
> + /// concurrent access.
> + #[inline(always)]
> + fn update<T, R, F>(&self, r: R, f: F)
> + where
> + R: IoLoc<T>,
> + T: Into<R::IoType>,
> + Self: IoKnownSize + IoCapable<R::IoType> + Sized,
> + F: FnOnce(T) -> T,
> + {
> + let v = self.read(r);
> + self.write(r.set(f(v)));
> + }
> }
>
> /// Trait for types with a known size at compile time.