// SPDX-License-Identifier: GPL-2.012//! Memory-mapped IO.3//!4//! C header: [`include/asm-generic/io.h`](srctree/include/asm-generic/io.h)56use crate::{7bindings,8prelude::*, //9};1011pub mod mem;12pub mod poll;13pub mod resource;1415pub use resource::Resource;1617/// Physical address type.18///19/// This is a type alias to either `u32` or `u64` depending on the config option20/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit architectures.21pub type PhysAddr = bindings::phys_addr_t;2223/// Resource Size type.24///25/// This is a type alias to either `u32` or `u64` depending on the config option26/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit architectures.27pub type ResourceSize = bindings::resource_size_t;2829/// Raw representation of an MMIO region.30///31/// By itself, the existence of an instance of this structure does not provide any guarantees that32/// the represented MMIO region does exist or is properly mapped.33///34/// Instead, the bus specific MMIO implementation must convert this raw representation into an `Io`35/// instance providing the actual memory accessors. Only by the conversion into an `Io` structure36/// any guarantees are given.37pub struct IoRaw<const SIZE: usize = 0> {38addr: usize,39maxsize: usize,40}4142impl<const SIZE: usize> IoRaw<SIZE> {43/// Returns a new `IoRaw` instance on success, an error otherwise.44pub fn new(addr: usize, maxsize: usize) -> Result<Self> {45if maxsize < SIZE {46return Err(EINVAL);47}4849Ok(Self { addr, maxsize })50}5152/// Returns the base address of the MMIO region.53#[inline]54pub fn addr(&self) -> usize {55self.addr56}5758/// Returns the maximum size of the MMIO region.59#[inline]60pub fn maxsize(&self) -> usize {61self.maxsize62}63}6465/// IO-mapped memory region.66///67/// The creator (usually a subsystem / bus such as PCI) is responsible for creating the68/// mapping, performing an additional region request etc.69///70/// # Invariant71///72/// `addr` is the start and `maxsize` the length of valid I/O mapped memory region of size73/// `maxsize`.74///75/// # Examples76///77/// ```no_run78/// use kernel::{79/// bindings,80/// ffi::c_void,81/// io::{82/// Io,83/// IoRaw,84/// PhysAddr,85/// },86/// };87/// use core::ops::Deref;88///89/// // See also [`pci::Bar`] for a real example.90/// struct IoMem<const SIZE: usize>(IoRaw<SIZE>);91///92/// impl<const SIZE: usize> IoMem<SIZE> {93/// /// # Safety94/// ///95/// /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs96/// /// virtual address space.97/// unsafe fn new(paddr: usize) -> Result<Self>{98/// // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is99/// // valid for `ioremap`.100/// let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };101/// if addr.is_null() {102/// return Err(ENOMEM);103/// }104///105/// Ok(IoMem(IoRaw::new(addr as usize, SIZE)?))106/// }107/// }108///109/// impl<const SIZE: usize> Drop for IoMem<SIZE> {110/// fn drop(&mut self) {111/// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`.112/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); };113/// }114/// }115///116/// impl<const SIZE: usize> Deref for IoMem<SIZE> {117/// type Target = Io<SIZE>;118///119/// fn deref(&self) -> &Self::Target {120/// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.121/// unsafe { Io::from_raw(&self.0) }122/// }123/// }124///125///# fn no_run() -> Result<(), Error> {126/// // SAFETY: Invalid usage for example purposes.127/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };128/// iomem.write32(0x42, 0x0);129/// assert!(iomem.try_write32(0x42, 0x0).is_ok());130/// assert!(iomem.try_write32(0x42, 0x4).is_err());131/// # Ok(())132/// # }133/// ```134#[repr(transparent)]135pub struct Io<const SIZE: usize = 0>(IoRaw<SIZE>);136137macro_rules! define_read {138($(#[$attr:meta])* $name:ident, $try_name:ident, $c_fn:ident -> $type_name:ty) => {139/// Read IO data from a given offset known at compile time.140///141/// Bound checks are performed on compile time, hence if the offset is not known at compile142/// time, the build will fail.143$(#[$attr])*144// Always inline to optimize out error path of `io_addr_assert`.145#[inline(always)]146pub fn $name(&self, offset: usize) -> $type_name {147let addr = self.io_addr_assert::<$type_name>(offset);148149// SAFETY: By the type invariant `addr` is a valid address for MMIO operations.150unsafe { bindings::$c_fn(addr as *const c_void) }151}152153/// Read IO data from a given offset.154///155/// Bound checks are performed on runtime, it fails if the offset (plus the type size) is156/// out of bounds.157$(#[$attr])*158pub fn $try_name(&self, offset: usize) -> Result<$type_name> {159let addr = self.io_addr::<$type_name>(offset)?;160161// SAFETY: By the type invariant `addr` is a valid address for MMIO operations.162Ok(unsafe { bindings::$c_fn(addr as *const c_void) })163}164};165}166167macro_rules! define_write {168($(#[$attr:meta])* $name:ident, $try_name:ident, $c_fn:ident <- $type_name:ty) => {169/// Write IO data from a given offset known at compile time.170///171/// Bound checks are performed on compile time, hence if the offset is not known at compile172/// time, the build will fail.173$(#[$attr])*174// Always inline to optimize out error path of `io_addr_assert`.175#[inline(always)]176pub fn $name(&self, value: $type_name, offset: usize) {177let addr = self.io_addr_assert::<$type_name>(offset);178179// SAFETY: By the type invariant `addr` is a valid address for MMIO operations.180unsafe { bindings::$c_fn(value, addr as *mut c_void) }181}182183/// Write IO data from a given offset.184///185/// Bound checks are performed on runtime, it fails if the offset (plus the type size) is186/// out of bounds.187$(#[$attr])*188pub fn $try_name(&self, value: $type_name, offset: usize) -> Result {189let addr = self.io_addr::<$type_name>(offset)?;190191// SAFETY: By the type invariant `addr` is a valid address for MMIO operations.192unsafe { bindings::$c_fn(value, addr as *mut c_void) }193Ok(())194}195};196}197198impl<const SIZE: usize> Io<SIZE> {199/// Converts an `IoRaw` into an `Io` instance, providing the accessors to the MMIO mapping.200///201/// # Safety202///203/// Callers must ensure that `addr` is the start of a valid I/O mapped memory region of size204/// `maxsize`.205pub unsafe fn from_raw(raw: &IoRaw<SIZE>) -> &Self {206// SAFETY: `Io` is a transparent wrapper around `IoRaw`.207unsafe { &*core::ptr::from_ref(raw).cast() }208}209210/// Returns the base address of this mapping.211#[inline]212pub fn addr(&self) -> usize {213self.0.addr()214}215216/// Returns the maximum size of this mapping.217#[inline]218pub fn maxsize(&self) -> usize {219self.0.maxsize()220}221222#[inline]223const fn offset_valid<U>(offset: usize, size: usize) -> bool {224let type_size = core::mem::size_of::<U>();225if let Some(end) = offset.checked_add(type_size) {226end <= size && offset % type_size == 0227} else {228false229}230}231232#[inline]233fn io_addr<U>(&self, offset: usize) -> Result<usize> {234if !Self::offset_valid::<U>(offset, self.maxsize()) {235return Err(EINVAL);236}237238// Probably no need to check, since the safety requirements of `Self::new` guarantee that239// this can't overflow.240self.addr().checked_add(offset).ok_or(EINVAL)241}242243// Always inline to optimize out error path of `build_assert`.244#[inline(always)]245fn io_addr_assert<U>(&self, offset: usize) -> usize {246build_assert!(Self::offset_valid::<U>(offset, SIZE));247248self.addr() + offset249}250251define_read!(read8, try_read8, readb -> u8);252define_read!(read16, try_read16, readw -> u16);253define_read!(read32, try_read32, readl -> u32);254define_read!(255#[cfg(CONFIG_64BIT)]256read64,257try_read64,258readq -> u64259);260261define_read!(read8_relaxed, try_read8_relaxed, readb_relaxed -> u8);262define_read!(read16_relaxed, try_read16_relaxed, readw_relaxed -> u16);263define_read!(read32_relaxed, try_read32_relaxed, readl_relaxed -> u32);264define_read!(265#[cfg(CONFIG_64BIT)]266read64_relaxed,267try_read64_relaxed,268readq_relaxed -> u64269);270271define_write!(write8, try_write8, writeb <- u8);272define_write!(write16, try_write16, writew <- u16);273define_write!(write32, try_write32, writel <- u32);274define_write!(275#[cfg(CONFIG_64BIT)]276write64,277try_write64,278writeq <- u64279);280281define_write!(write8_relaxed, try_write8_relaxed, writeb_relaxed <- u8);282define_write!(write16_relaxed, try_write16_relaxed, writew_relaxed <- u16);283define_write!(write32_relaxed, try_write32_relaxed, writel_relaxed <- u32);284define_write!(285#[cfg(CONFIG_64BIT)]286write64_relaxed,287try_write64_relaxed,288writeq_relaxed <- u64289);290}291292293