1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Memory-mapped IO. 4 //! 5 //! C header: [`include/asm-generic/io.h`](srctree/include/asm-generic/io.h) 6 7 use crate::{ 8 bindings, 9 prelude::*, // 10 }; 11 12 pub mod mem; 13 pub mod poll; 14 pub mod resource; 15 16 pub use resource::Resource; 17 18 /// Resource Size type. 19 /// 20 /// This is a type alias to either `u32` or `u64` depending on the config option 21 /// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit architectures. 22 pub type ResourceSize = bindings::resource_size_t; 23 24 /// Raw representation of an MMIO region. 25 /// 26 /// By itself, the existence of an instance of this structure does not provide any guarantees that 27 /// the represented MMIO region does exist or is properly mapped. 28 /// 29 /// Instead, the bus specific MMIO implementation must convert this raw representation into an `Io` 30 /// instance providing the actual memory accessors. Only by the conversion into an `Io` structure 31 /// any guarantees are given. 32 pub struct IoRaw<const SIZE: usize = 0> { 33 addr: usize, 34 maxsize: usize, 35 } 36 37 impl<const SIZE: usize> IoRaw<SIZE> { 38 /// Returns a new `IoRaw` instance on success, an error otherwise. 39 pub fn new(addr: usize, maxsize: usize) -> Result<Self> { 40 if maxsize < SIZE { 41 return Err(EINVAL); 42 } 43 44 Ok(Self { addr, maxsize }) 45 } 46 47 /// Returns the base address of the MMIO region. 48 #[inline] 49 pub fn addr(&self) -> usize { 50 self.addr 51 } 52 53 /// Returns the maximum size of the MMIO region. 54 #[inline] 55 pub fn maxsize(&self) -> usize { 56 self.maxsize 57 } 58 } 59 60 /// IO-mapped memory region. 61 /// 62 /// The creator (usually a subsystem / bus such as PCI) is responsible for creating the 63 /// mapping, performing an additional region request etc. 64 /// 65 /// # Invariant 66 /// 67 /// `addr` is the start and `maxsize` the length of valid I/O mapped memory region of size 68 /// `maxsize`. 69 /// 70 /// # Examples 71 /// 72 /// ```no_run 73 /// # use kernel::{bindings, ffi::c_void, io::{Io, IoRaw}}; 74 /// # use core::ops::Deref; 75 /// 76 /// // See also [`pci::Bar`] for a real example. 77 /// struct IoMem<const SIZE: usize>(IoRaw<SIZE>); 78 /// 79 /// impl<const SIZE: usize> IoMem<SIZE> { 80 /// /// # Safety 81 /// /// 82 /// /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs 83 /// /// virtual address space. 84 /// unsafe fn new(paddr: usize) -> Result<Self>{ 85 /// // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is 86 /// // valid for `ioremap`. 87 /// let addr = unsafe { bindings::ioremap(paddr as bindings::phys_addr_t, SIZE) }; 88 /// if addr.is_null() { 89 /// return Err(ENOMEM); 90 /// } 91 /// 92 /// Ok(IoMem(IoRaw::new(addr as usize, SIZE)?)) 93 /// } 94 /// } 95 /// 96 /// impl<const SIZE: usize> Drop for IoMem<SIZE> { 97 /// fn drop(&mut self) { 98 /// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`. 99 /// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); }; 100 /// } 101 /// } 102 /// 103 /// impl<const SIZE: usize> Deref for IoMem<SIZE> { 104 /// type Target = Io<SIZE>; 105 /// 106 /// fn deref(&self) -> &Self::Target { 107 /// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`. 108 /// unsafe { Io::from_raw(&self.0) } 109 /// } 110 /// } 111 /// 112 ///# fn no_run() -> Result<(), Error> { 113 /// // SAFETY: Invalid usage for example purposes. 114 /// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? }; 115 /// iomem.write32(0x42, 0x0); 116 /// assert!(iomem.try_write32(0x42, 0x0).is_ok()); 117 /// assert!(iomem.try_write32(0x42, 0x4).is_err()); 118 /// # Ok(()) 119 /// # } 120 /// ``` 121 #[repr(transparent)] 122 pub struct Io<const SIZE: usize = 0>(IoRaw<SIZE>); 123 124 macro_rules! define_read { 125 ($(#[$attr:meta])* $name:ident, $try_name:ident, $c_fn:ident -> $type_name:ty) => { 126 /// Read IO data from a given offset known at compile time. 127 /// 128 /// Bound checks are performed on compile time, hence if the offset is not known at compile 129 /// time, the build will fail. 130 $(#[$attr])* 131 #[inline] 132 pub fn $name(&self, offset: usize) -> $type_name { 133 let addr = self.io_addr_assert::<$type_name>(offset); 134 135 // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. 136 unsafe { bindings::$c_fn(addr as *const c_void) } 137 } 138 139 /// Read IO data from a given offset. 140 /// 141 /// Bound checks are performed on runtime, it fails if the offset (plus the type size) is 142 /// out of bounds. 143 $(#[$attr])* 144 pub fn $try_name(&self, offset: usize) -> Result<$type_name> { 145 let addr = self.io_addr::<$type_name>(offset)?; 146 147 // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. 148 Ok(unsafe { bindings::$c_fn(addr as *const c_void) }) 149 } 150 }; 151 } 152 153 macro_rules! define_write { 154 ($(#[$attr:meta])* $name:ident, $try_name:ident, $c_fn:ident <- $type_name:ty) => { 155 /// Write IO data from a given offset known at compile time. 156 /// 157 /// Bound checks are performed on compile time, hence if the offset is not known at compile 158 /// time, the build will fail. 159 $(#[$attr])* 160 #[inline] 161 pub fn $name(&self, value: $type_name, offset: usize) { 162 let addr = self.io_addr_assert::<$type_name>(offset); 163 164 // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. 165 unsafe { bindings::$c_fn(value, addr as *mut c_void) } 166 } 167 168 /// Write IO data from a given offset. 169 /// 170 /// Bound checks are performed on runtime, it fails if the offset (plus the type size) is 171 /// out of bounds. 172 $(#[$attr])* 173 pub fn $try_name(&self, value: $type_name, offset: usize) -> Result { 174 let addr = self.io_addr::<$type_name>(offset)?; 175 176 // SAFETY: By the type invariant `addr` is a valid address for MMIO operations. 177 unsafe { bindings::$c_fn(value, addr as *mut c_void) } 178 Ok(()) 179 } 180 }; 181 } 182 183 impl<const SIZE: usize> Io<SIZE> { 184 /// Converts an `IoRaw` into an `Io` instance, providing the accessors to the MMIO mapping. 185 /// 186 /// # Safety 187 /// 188 /// Callers must ensure that `addr` is the start of a valid I/O mapped memory region of size 189 /// `maxsize`. 190 pub unsafe fn from_raw(raw: &IoRaw<SIZE>) -> &Self { 191 // SAFETY: `Io` is a transparent wrapper around `IoRaw`. 192 unsafe { &*core::ptr::from_ref(raw).cast() } 193 } 194 195 /// Returns the base address of this mapping. 196 #[inline] 197 pub fn addr(&self) -> usize { 198 self.0.addr() 199 } 200 201 /// Returns the maximum size of this mapping. 202 #[inline] 203 pub fn maxsize(&self) -> usize { 204 self.0.maxsize() 205 } 206 207 #[inline] 208 const fn offset_valid<U>(offset: usize, size: usize) -> bool { 209 let type_size = core::mem::size_of::<U>(); 210 if let Some(end) = offset.checked_add(type_size) { 211 end <= size && offset % type_size == 0 212 } else { 213 false 214 } 215 } 216 217 #[inline] 218 fn io_addr<U>(&self, offset: usize) -> Result<usize> { 219 if !Self::offset_valid::<U>(offset, self.maxsize()) { 220 return Err(EINVAL); 221 } 222 223 // Probably no need to check, since the safety requirements of `Self::new` guarantee that 224 // this can't overflow. 225 self.addr().checked_add(offset).ok_or(EINVAL) 226 } 227 228 #[inline] 229 fn io_addr_assert<U>(&self, offset: usize) -> usize { 230 build_assert!(Self::offset_valid::<U>(offset, SIZE)); 231 232 self.addr() + offset 233 } 234 235 define_read!(read8, try_read8, readb -> u8); 236 define_read!(read16, try_read16, readw -> u16); 237 define_read!(read32, try_read32, readl -> u32); 238 define_read!( 239 #[cfg(CONFIG_64BIT)] 240 read64, 241 try_read64, 242 readq -> u64 243 ); 244 245 define_read!(read8_relaxed, try_read8_relaxed, readb_relaxed -> u8); 246 define_read!(read16_relaxed, try_read16_relaxed, readw_relaxed -> u16); 247 define_read!(read32_relaxed, try_read32_relaxed, readl_relaxed -> u32); 248 define_read!( 249 #[cfg(CONFIG_64BIT)] 250 read64_relaxed, 251 try_read64_relaxed, 252 readq_relaxed -> u64 253 ); 254 255 define_write!(write8, try_write8, writeb <- u8); 256 define_write!(write16, try_write16, writew <- u16); 257 define_write!(write32, try_write32, writel <- u32); 258 define_write!( 259 #[cfg(CONFIG_64BIT)] 260 write64, 261 try_write64, 262 writeq <- u64 263 ); 264 265 define_write!(write8_relaxed, try_write8_relaxed, writeb_relaxed <- u8); 266 define_write!(write16_relaxed, try_write16_relaxed, writew_relaxed <- u16); 267 define_write!(write32_relaxed, try_write32_relaxed, writel_relaxed <- u32); 268 define_write!( 269 #[cfg(CONFIG_64BIT)] 270 write64_relaxed, 271 try_write64_relaxed, 272 writeq_relaxed <- u64 273 ); 274 } 275