rust: add support for port io
Subsystems (8)
v2 cover rust: add support for port io
currently the rust Io type maps to the c read{b, w, l, q}/write{b, w, l, q} functions and have no support for port io. this can be a problem for pci::Bar because the pointer returned by pci_iomap can be either PIO or MMIO [0].
this patch series splits the Io type into Io, and MMIo. Io can be used to access PIO or MMIO. MMIo can only access memory mapped IO but might, depending on the arch, be faster than Io. and updates pci::Bar, so that it is generic over Io and, a user can optionally give a compile time hint about the type of io.
changes in v2:
- remove PortIo
- typo fixes
- squash "fixup" patches so that patches will not introduce build fails
- move some changes across patches so that build will not fail
- changes macro define in rust/helpers/io.c to use full rust name
- specialize io_backend for the x86 case
- do not modify lib/iomap.c
- rebased on v6.15-rc6
Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]/
Andrew Ballance (3):
rust: io: add new Io type
rust: io: add from_raw_cookie functions
rust: pci: make Bar generic over Io
Fiona Behrens (3):
rust: helpers: io: use macro to generate io accessor functions
rust: io: make Io use IoAccess trait
rust: io: implement Debug for IoRaw and add some doctests
drivers/gpu/nova-core/driver.rs | 4 +- drivers/gpu/nova-core/regs.rs | 1 + rust/helpers/io.c | 112 ++---- rust/kernel/devres.rs | 4 +- rust/kernel/io.rs | 645 +++++++++++++++++++++++--------- rust/kernel/pci.rs | 101 +++-- samples/rust/rust_driver_pci.rs | 6 +- 7 files changed, 595 insertions(+), 278 deletions(-)
base-commit: 82f2b0b97b36ee3fcddf0f0780a9a0825d52fec3
Signature · 1 line
2.49.0
PATCH v2 1/6 rust: helpers: io: use macro to generate io accessor functions
From: Fiona Behrens <[email protected]>
Generate the rust_helper_read{b,w,l,q}, rust_helper_write{b,w,l,q} and the relaxed version using a C macro.
This removes a lot of redundant code and is in preparation for pio functions which uses a similar C macro.
--- rust/helpers/io.c | 105 +++++++++++++--------------------------------- 1 file changed, 29 insertions(+), 76 deletions(-)
rust/helpers/io.c +29 -76
@@ -12,90 +12,43 @@ void rust_helper_iounmap(void __iomem *addr)iounmap (addr); } -u8 rust_helper_readb (const void __iomem *addr) -{ -return readb (addr); -} - -u16 rust_helper_readw (const void __iomem *addr) -{ -return readw (addr); -} - -u32 rust_helper_readl (const void __iomem *addr) -{ -return readl (addr); -} - +#define define_rust_io_read_helper (rust_name, name, type) \ + type rust_name(void __iomem *addr) \ + { \ + return name(addr); \ + } + +#define define_rust_io_write_helper (rust_name, name, type) \ + void rust_name(type value, void __iomem *addr) \ + { \ + name(value, addr); \ + } + +define_rust_io_read_helper (rust_helper_readb, readb, u8); +define_rust_io_read_helper (rust_helper_readw, readw, u16); +define_rust_io_read_helper (rust_helper_readl, readl, u32);#ifdef CONFIG_64BIT -u64 rust_helper_readq (const void __iomem *addr) -{ -return readq (addr); -} +define_rust_io_read_helper (rust_helper_readq, readq, u64);#endif -void rust_helper_writeb (u8 value,void __iomem *addr) -{ -writeb (value, addr); -} - -void rust_helper_writew (u16 value,void __iomem *addr) -{ -writew (value, addr); -} - -void rust_helper_writel (u32 value,void __iomem *addr) -{ -writel (value, addr); -} - +define_rust_io_write_helper (rust_helper_writeb, writeb, u8); +define_rust_io_write_helper (rust_helper_writew, writew, u16); +define_rust_io_write_helper (rust_helper_writel, writel, u32);#ifdef CONFIG_64BIT -void rust_helper_writeq (u64 value,void __iomem *addr) -{ -writeq (value, addr); -} +define_rust_io_write_helper (rust_helper_writeq, writeq, u64);#endif -u8 rust_helper_readb_relaxed (const void __iomem *addr) -{ -return readb_relaxed (addr); -} - -u16 rust_helper_readw_relaxed (const void __iomem *addr) -{ -return readw_relaxed (addr); -} - -u32 rust_helper_readl_relaxed (const void __iomem *addr) -{ -return readl_relaxed (addr); -} - +define_rust_io_read_helper (rust_helper_readb_relaxed, readb_relaxed, u8); +define_rust_io_read_helper (rust_helper_readw_relaxed, readw_relaxed, u16); +define_rust_io_read_helper (rust_helper_readl_relaxed, readl_relaxed, u32);#ifdef CONFIG_64BIT -u64 rust_helper_readq_relaxed (const void __iomem *addr) -{ -return readq_relaxed (addr); -} +define_rust_io_read_helper (rust_helper_readq_relaxed, readq_relaxed, u64);#endif -void rust_helper_writeb_relaxed (u8 value,void __iomem *addr) -{ -writeb_relaxed (value, addr); -} - -void rust_helper_writew_relaxed (u16 value,void __iomem *addr) -{ -writew_relaxed (value, addr); -} - -void rust_helper_writel_relaxed (u32 value,void __iomem *addr) -{ -writel_relaxed (value, addr); -} - +define_rust_io_write_helper (rust_helper_writeb_relaxed, writeb_relaxed, u8); +define_rust_io_write_helper (rust_helper_writew_relaxed, writew_relaxed, u16); +define_rust_io_write_helper (rust_helper_writel_relaxed, writel_relaxed, u32);#ifdef CONFIG_64BIT -void rust_helper_writeq_relaxed (u64 value,void __iomem *addr) -{ -writeq_relaxed (value, addr); -} +define_rust_io_write_helper (rust_helper_writeq_relaxed, writeq_relaxed, u64);#endif +
Signature · 1 line
2.49.0
PATCH v2 2/6 rust: io: make Io use IoAccess trait
In reply to Andrew BallanceFrom: Fiona Behrens <[email protected]>
makes the Io struct use the new traits (IoAccess, IoAccess64,
IoAccessRelaxed and IoAccess64Relaxed) to perform io.
This allows to later implement a generic Io framework.
update pci,rust_driver_pci.rs, nova-core and a devres doc test to use the new io api.
--- drivers/gpu/nova-core/regs.rs | 1 + rust/kernel/devres.rs | 4 +- rust/kernel/io.rs | 438 +++++++++++++++++++------------- rust/kernel/pci.rs | 2 +- samples/rust/rust_driver_pci.rs | 4 +- 5 files changed, 263 insertions(+), 186 deletions(-)
drivers/gpu/nova-core/regs.rs +1 -0
@@ -1,6 +1,7 @@// SPDX-License-Identifier: GPL-2.0 use crate ::driver::Bar0 ; +use kernel::io::IoAccess ;// TODO //
rust/kernel/devres.rs +2 -2
@@ -45,7 +45,7 @@ struct DevresInner<T> {/// # Example /// /// ```no_run -/// # use kernel::{bindings, c_str, device::Device, devres::Devres, io::{Io, IoRaw}}; +/// # use kernel::{bindings, c_str, device::Device, devres::Devres, io::{Io, IoRaw, IoAccess}}; /// # use core::ops::Deref; /// /// // See also [`pci::Bar`] for a real example.
@@ -80,7 +80,7 @@ struct DevresInner<T> {/// /// fn deref(&self) -> &Self::Target { /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`. -/// unsafe { Io::from_raw(&self.0) } +/// unsafe { Io::from_raw_ref(&self.0) } /// } /// } /// # fn no_run() -> Result<(), Error> {
rust/kernel/io.rs +256 -182
480 lines not on this page · raw message
rust/kernel/pci.rs +1 -1
@@ -356,7 +356,7 @@ impl<const SIZE: usize> Deref for Bar<SIZE> {fn deref (&self) -> &Self ::Target {// SAFETY: By the type invariant of `Self`, the MMIO range in `self.io` is properly mapped. -unsafe {Io ::from_raw (&self.io) } +unsafe {Io ::from_raw_ref (&self.io) } } }
samples/rust/rust_driver_pci.rs +3 -1
@@ -4,7 +4,9 @@//! //! To make this driver probe, QEMU must be run with `-device pci-testdev`. -use kernel::{bindings, c_str, device::Core , devres::Devres , pci, prelude::*, types::ARef }; +use kernel::{ + bindings, c_str, device::Core , devres::Devres , io::IoAccess , pci, prelude::*, types::ARef , +};struct Regs ;
Signature · 1 line
2.49.0
PATCH v2 3/6 rust: io: add new Io type
In reply to Andrew Ballanceadds a new Io type that uses the C ioread/iowrite family of functions and implements the IoAccess trait for it and renames the old Io to MMIo.
--- rust/helpers/io.c | 7 ++++ rust/kernel/io.rs | 97 ++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 98 insertions(+), 6 deletions(-)
rust/helpers/io.c +7 -0
@@ -52,3 +52,10 @@ define_rust_io_write_helper(rust_helper_writel_relaxed, writel_relaxed, u32);define_rust_io_write_helper (rust_helper_writeq_relaxed, writeq_relaxed, u64);#endif +define_rust_io_read_helper (rust_helper_ioread8, ioread8, u8); +define_rust_io_read_helper (rust_helper_ioread16, ioread16, u16); +define_rust_io_read_helper (rust_helper_ioread32, ioread32, u32); + +define_rust_io_write_helper (rust_helper_iowrite8, iowrite8, u8); +define_rust_io_write_helper (rust_helper_iowrite16, iowrite16, u16); +define_rust_io_write_helper (rust_helper_iowrite32, iowrite32, u32);
rust/kernel/io.rs +91 -6
128 lines not on this page · raw message
Signature · 1 line
2.49.0
PATCH v2 4/6 rust: io: implement Debug for IoRaw and add some doctests
In reply to Andrew BallanceFrom: Fiona Behrens <[email protected]>
Implement Debug for kernel::io::IoRaw which also outputs the const generic SIZE as a field.
Add some doctests to IoRaw::new and MMIo::from_raw(_ref).
--- rust/kernel/io.rs | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+)
rust/kernel/io.rs +63 -0
@@ -226,6 +226,33 @@ pub struct IoRaw<const SIZE: usize = 0> {impl <const SIZE :usize >IoRaw <SIZE > {/// Returns a new `IoRaw` instance on success, an error otherwise. +/// +/// # Examples +/// +/// Const generic size 0, only allowing runtime checks: +/// ``` +/// use kernel::io::IoRaw; +/// +/// let raw: IoRaw<0> = IoRaw::new(0xDEADBEEFC0DE, 8).unwrap(); +/// # assert_eq!(raw.addr(), 0xDEADBEEFC0DE); +/// # assert_eq!(raw.maxsize(), 8); +/// ``` +/// +/// Const generic size equals maxsize: +/// ``` +/// use kernel::io::IoRaw; +/// +/// let raw: IoRaw<8> = IoRaw::new(0xDEADBEEFC0DE, 8).unwrap(); +/// # assert_eq!(raw.addr(), 0xDEADBEEFC0DE); +/// # assert_eq!(raw.maxsize(), 8); +/// ``` +/// +/// Const generic size bigger then maxsize: +/// ``` +/// use kernel::io::IoRaw; +/// +/// IoRaw::<16>::new(0xDEADBEEFC0DE, 8).unwrap_err(); +/// ``` pub fn new (addr:usize , maxsize:usize ) ->Result <Self > {if maxsize <SIZE {return Err (EINVAL );
@@ -247,6 +274,16 @@ pub fn maxsize(&self) -> usize { } } +impl <const SIZE :usize > core::fmt::Debug for IoRaw <SIZE > { +fn fmt (&self, f: &mut core::fmt::Formatter <'_>) -> core::fmt::Result { + f.debug_struct ("IoRaw" ) + .field ("SIZE" , &SIZE ) + .field ("addr" , &self.addr) + .field ("maxsize" , &self.maxsize) + .finish () + } +} +/// IO-mapped memory, starting at the base address [`addr`] and spanning [`maxsize`] bytes. /// /// The creator (usually a subsystem / bus such as PCI) is responsible for creating the
@@ -263,6 +300,7 @@ pub fn maxsize(&self) -> usize {/// [`maxsize`]: IoAccess::maxsize /// [`read`]: https://docs.kernel.org/driver-api/device-io.html#differences-between-i-o-access-functions /// [`write`]: https://docs.kernel.org/driver-api/device-io.html#differences-between-i-o-access-functions +#[derive( Debug )] #[repr(transparent)] pub struct MMIo <const SIZE :usize =0 >(IoRaw <SIZE >);
@@ -273,6 +311,18 @@ impl<const SIZE: usize> MMIo<SIZE> {/// /// Callers must ensure that `addr` is the start of a valid I/O mapped memory region of /// size `maxsize`. +/// +/// # Examples +/// +/// ``` +/// use kernel::io::{IoRaw, MMIo, IoAccess}; +/// +/// let raw = IoRaw::<2>::new(0xDEADBEEFC0DE, 2).unwrap(); +/// // SAFETY: test, value is not actually written to. +/// let mmio: MMIo<2> = unsafe { MMIo::from_raw(raw) }; +/// # assert_eq!(0xDEADBEEFC0DE, mmio.addr()); +/// # assert_eq!(2, mmio.maxsize()); +/// ``` #[inline] pub unsafe fn from_raw (raw:IoRaw <SIZE >) ->Self {Self (raw)
@@ -285,6 +335,18 @@ pub unsafe fn from_raw(raw: IoRaw<SIZE>) -> Self {/// /// Callers must ensure that `addr` is the start of a valid I/O mapped memory region of /// size `maxsize`. +/// +/// # Examples +/// +/// ``` +/// use kernel::io::{IoRaw, MMIo, IoAccess}; +/// +/// let raw = IoRaw::<2>::new(0xDEADBEEFC0DE, 2).unwrap(); +/// // SAFETY: test, value is not actually written to. +/// let mmio: &MMIo<2> = unsafe { MMIo::from_raw_ref(&raw) }; +/// # assert_eq!(raw.addr(), mmio.addr()); +/// # assert_eq!(raw.maxsize(), mmio.maxsize()); +/// ``` #[inline] pub unsafe fn from_raw_ref (raw: &IoRaw <SIZE >) -> &Self {// SAFETY: `MMIo` is a transparent wrapper around `IoRaw`.
@@ -349,6 +411,7 @@ impl<const SIZE: usize> IoAccess64Relaxed<SIZE> for MMIo<SIZE> {/// [`maxsize`]: IoAccess::maxsize /// [`ioread`]: https://docs.kernel.org/driver-api/device-io.html#differences-between-i-o-access-functions /// [`iowrite`]: https://docs.kernel.org/driver-api/device-io.html#differences-between-i-o-access-functions +#[derive( Debug )] #[repr(transparent)] pub struct Io <const SIZE :usize =0 >(IoRaw <SIZE >);
Signature · 1 line
2.49.0
PATCH v2 5/6 rust: io: add from_raw_cookie functions
In reply to Andrew Ballanceadds a from_raw_cookie function to the IoAccess trait.
from_raw_cookie attempts to convert a iomem address that can be accessed by the ioread/iowrite family of C functions into either a Io or MMIo.
This is done so that devices that know what type of Io they are at compile time can give a hint about their type.
--- rust/kernel/io.rs | 73 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+)
rust/kernel/io.rs +73 -0
@@ -6,6 +6,47 @@use crate ::error::{code::EINVAL ,Result };use crate ::{bindings, build_assert}; +use io_backend::*; + +/// `io_backend` is private and implements the config specific logic for +/// `IoAccess::from_raw_cookie`. +#[cfg(all( CONFIG_X86 , CONFIG_GENERIC_IOMAP ))] +mod io_backend { +// if on x86, generic_iomap is enabled so copy the logic +// from IO_COND in `lib/iomap.c` + +// values copied from `lib/iomap.c` +const PIO_OFFSET :usize =0x10000 ; +const PIO_RESERVED :usize =0x40000 ; + +#[inline] +pub (super )fn is_mmio (addr:usize ) ->bool { + addr >=PIO_RESERVED + } + +#[inline] +pub (super )fn is_portio (addr:usize ) ->bool { + !is_mmio (addr) && addr >PIO_OFFSET + } +} +#[cfg(not( CONFIG_GENERIC_IOMAP ))] +mod io_backend { +// for everyone who does not use generic iomap +// except for alpha and parisc, neither of which has a rust compiler, +// ioread/iowrite is defined in `include/asm-generic/io.h`. +// +// for these ioread/iowrite, maps to read/write. +// so allow any io to be converted because they use the same backend +#[inline] +pub (super )fn is_mmio (_addr:usize ) ->bool { +true + } + +#[inline] +pub (super )fn is_portio (_addr:usize ) ->bool { +false + } +}/// Private macro to define the [`IoAccess`] functions. macro_rules! define_io_access_function {
@@ -162,6 +203,14 @@ pub unsafe trait IoAccess<const SIZE: usize = 0> {/// Returns the base address of the accessed IO area. fn addr (&self) ->usize ; +/// Attempts to create a `Self` from a [`IoRaw`]. +/// +/// # Safety +/// `raw` should be a io cookie that can be accessed by the C `ioread`/`iowrite` functions +unsafe fn from_raw_cookie (raw:IoRaw <SIZE >) ->Result <Self > +where +Self :Sized ; +define_io_access_function! (@read read8_unchecked, read8, try_read8,u8 ; read16_unchecked, read16, try_read16,u16 ;
@@ -366,6 +415,18 @@ fn addr(&self) -> usize { self.0 .addr () } +unsafe fn from_raw_cookie (raw:IoRaw <SIZE >) ->Result <Self > +where +Self :Sized , + { +if is_mmio (raw.addr ()) { +// INVARIANT: `addr` is checked so it should be ok to access with read/write +Ok (Self (raw)) + }else { +Err (EINVAL ) + } + } +impl_accessor_fn! ( read8_unchecked, readb, write8_unchecked, writeb,u8 ; read16_unchecked, readw, write16_unchecked, writew,u16 ;
@@ -474,6 +535,18 @@ fn maxsize(&self) -> usize { self.0 .maxsize () } +unsafe fn from_raw_cookie (raw:IoRaw <SIZE >) ->Result <Self > +where +Self :Sized , + { +if is_mmio (raw.addr ()) ||is_portio (raw.addr ()) { +// INVARIANT: `addr` is not touched so it should be able to be read with ioread/iowrite +Ok (Self (raw)) + }else { +Err (EINVAL ) + } + } +impl_accessor_fn! ( read8_unchecked, ioread8, write8_unchecked, iowrite8,u8 ; read16_unchecked, ioread16, write16_unchecked, iowrite16,u16 ;
Signature · 1 line
2.49.0
PATCH v2 6/6 rust: pci: make Bar generic over Io
In reply to Andrew Ballancerenames Bar to RawBar and makes it generic over IoAccess. a user can give a compile time suggestion when mapping a bar so that the type of io can be known.
updates nova-core and rust_driver_pci to use new bar api.
--- drivers/gpu/nova-core/driver.rs | 4 +- rust/kernel/pci.rs | 101 +++++++++++++++++++++++++------- samples/rust/rust_driver_pci.rs | 2 +- 3 files changed, 83 insertions(+), 24 deletions(-)
drivers/gpu/nova-core/driver.rs +2 -2
@@ -11,7 +11,7 @@ pub(crate) struct NovaCore { }const BAR0_SIZE :usize =8 ; -pub (crate )type Bar0 = pci::Bar <BAR0_SIZE >; +pub (crate )type Bar0 = pci::MMIoBar <BAR0_SIZE >; kernel::pci_device_table!(PCI_TABLE ,
@@ -33,7 +33,7 @@ fn probe(pdev: &pci::Device<Core>, _info: &Self::IdInfo) -> Result<Pin<KBox<Self pdev.enable_device_mem ()?; pdev.set_master (); -let bar = pdev.iomap_region_sized ::<BAR0_SIZE >(0 ,c_str! ("nova-core/bar0" ))?; +let bar = pdev.iomap_region_sized_mmio ::<BAR0_SIZE >(0 ,c_str! ("nova-core/bar0" ))?; let this = KBox::pin_init( try_pin_init!(Self {
rust/kernel/pci.rs +80 -21
171 lines not on this page · raw message
samples/rust/rust_driver_pci.rs +1 -1
@@ -18,7 +18,7 @@ impl Regs {const END :usize =0x10 ; } -type Bar0 = pci::Bar <{Regs ::END }>; +type Bar0 = pci::IoBar <{Regs ::END }>;#[derive( Debug )] struct TestIndex (u8 );
Signature · 1 line
2.49.0
Alice Ryhl
maintainerQuoted 5 lines · Andrew Ballance
currently the rust
Iotype maps to the c read{b, w, l, q}/write{b, w, l, q} functions and have no support for port io. this can be a problem forpci::Barbecause the pointer returned bypci_iomapcan be either PIO or MMIO [0].
Quoted 7 lines
this patch series splits the
Iotype intoIo, andMMIo.Iocan be used to access PIO or MMIO.MMIocan only access memory mapped IO but might, depending on the arch, be faster thanIo. and updatespci::Bar, so that it is generic over Io and, a user can optionally give a compile time hint about the type of io.
This series seems to try and solve parts of the same problems as Daniel's patchset:
https://lore.kernel.org/rust-for-linux/20250603-topics-tyr-platform_iomem-v9-0-a27e04157e3e@collabora.com/#r
We should probably align these two patchsets so that they do not add incompatible abstractions for the same thing.
Alice
Danilo Krummrich
maintainerQuoted 13 lines · Alice Ryhl
Quoted 11 lines · Andrew Ballance
currently the rust
Iotype maps to the c read{b, w, l, q}/write{b, w, l, q} functions and have no support for port io. this can be a problem forpci::Barbecause the pointer returned bypci_iomapcan be either PIO or MMIO [0].this patch series splits the
Iotype intoIo, andMMIo.Iocan be used to access PIO or MMIO.MMIocan only access memory mapped IO but might, depending on the arch, be faster thanIo. and updatespci::Bar, so that it is generic over Io and, a user can optionally give a compile time hint about the type of io.
Quoted 8 lines
Quoted 1 line
This series seems to try and solve parts of the same problems as Daniel's patchset:
https://lore.kernel.org/rust-for-linux/20250603-topics-tyr-platform_iomem-v9-0-a27e04157e3e@collabora.com/#rWe should probably align these two patchsets so that they do not add incompatible abstractions for the same thing.
AFAICS, they solve different problems, i.e.
1) Add Port I/O support to the generic I/O abstractions.
2) Add an abstraction for generic ioremap() used to map a struct resource obtained from a platform device.
The patch series will conflict though, I think it would be best to rebase this one onto Daniel's patch series, since it is close to land.