kernel/io.rs
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
7use crate::{
8 bindings,
9 prelude::*, //
10};
11
12pub mod mem;
13pub mod poll;
14pub mod resource;
15
16pub use resource::Resource;
17
18/// Physical address 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.
22pub type PhysAddr = bindings::phys_addr_t;
23
24/// Resource Size type.
25///
26/// This is a type alias to either `u32` or `u64` depending on the config option
27/// `CONFIG_PHYS_ADDR_T_64BIT`, and it can be a u64 even on 32-bit architectures.
28pub type ResourceSize = bindings::resource_size_t;
29
30/// Raw representation of an MMIO region.
31///
32/// By itself, the existence of an instance of this structure does not provide any guarantees that
33/// the represented MMIO region does exist or is properly mapped.
34///
35/// Instead, the bus specific MMIO implementation must convert this raw representation into an
36/// `Mmio` instance providing the actual memory accessors. Only by the conversion into an `Mmio`
37/// structure any guarantees are given.
38pub struct MmioRaw<const SIZE: usize = 0> {
39 addr: usize,
40 maxsize: usize,
41}
42
43impl<const SIZE: usize> MmioRaw<SIZE> {
44 /// Returns a new `MmioRaw` instance on success, an error otherwise.
45 pub fn new(addr: usize, maxsize: usize) -> Result<Self> {
46 if maxsize < SIZE {
47 return Err(EINVAL);
48 }
49
50 Ok(Self { addr, maxsize })
51 }
52
53 /// Returns the base address of the MMIO region.
54 #[inline]
55 pub fn addr(&self) -> usize {
56 self.addr
57 }
58
59 /// Returns the maximum size of the MMIO region.
60 #[inline]
61 pub fn maxsize(&self) -> usize {
62 self.maxsize
63 }
64}
65
66/// IO-mapped memory region.
67///
68/// The creator (usually a subsystem / bus such as PCI) is responsible for creating the
69/// mapping, performing an additional region request etc.
70///
71/// # Invariant
72///
73/// `addr` is the start and `maxsize` the length of valid I/O mapped memory region of size
74/// `maxsize`.
75///
76/// # Examples
77///
78/// ```no_run
79/// use kernel::{
80/// bindings,
81/// ffi::c_void,
82/// io::{
83/// Io,
84/// IoKnownSize,
85/// Mmio,
86/// MmioRaw,
87/// PhysAddr,
88/// },
89/// };
90/// use core::ops::Deref;
91///
92/// // See also `pci::Bar` for a real example.
93/// struct IoMem<const SIZE: usize>(MmioRaw<SIZE>);
94///
95/// impl<const SIZE: usize> IoMem<SIZE> {
96/// /// # Safety
97/// ///
98/// /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
99/// /// virtual address space.
100/// unsafe fn new(paddr: usize) -> Result<Self>{
101/// // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
102/// // valid for `ioremap`.
103/// let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };
104/// if addr.is_null() {
105/// return Err(ENOMEM);
106/// }
107///
108/// Ok(IoMem(MmioRaw::new(addr as usize, SIZE)?))
109/// }
110/// }
111///
112/// impl<const SIZE: usize> Drop for IoMem<SIZE> {
113/// fn drop(&mut self) {
114/// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`.
115/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); };
116/// }
117/// }
118///
119/// impl<const SIZE: usize> Deref for IoMem<SIZE> {
120/// type Target = Mmio<SIZE>;
121///
122/// fn deref(&self) -> &Self::Target {
123/// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.
124/// unsafe { Mmio::from_raw(&self.0) }
125/// }
126/// }
127///
128///# fn no_run() -> Result<(), Error> {
129/// // SAFETY: Invalid usage for example purposes.
130/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
131/// iomem.write32(0x42, 0x0);
132/// assert!(iomem.try_write32(0x42, 0x0).is_ok());
133/// assert!(iomem.try_write32(0x42, 0x4).is_err());
134/// # Ok(())
135/// # }
136/// ```
137#[repr(transparent)]
138pub struct Mmio<const SIZE: usize = 0>(MmioRaw<SIZE>);
139
140/// Internal helper macros used to invoke C MMIO read functions.
141///
142/// This macro is intended to be used by higher-level MMIO access macros (define_read) and provides
143/// a unified expansion for infallible vs. fallible read semantics. It emits a direct call into the
144/// corresponding C helper and performs the required cast to the Rust return type.
145///
146/// # Parameters
147///
148/// * `$c_fn` – The C function performing the MMIO read.
149/// * `$self` – The I/O backend object.
150/// * `$ty` – The type of the value to be read.
151/// * `$addr` – The MMIO address to read.
152///
153/// This macro does not perform any validation; all invariants must be upheld by the higher-level
154/// abstraction invoking it.
155macro_rules! call_mmio_read {
156 (infallible, $c_fn:ident, $self:ident, $type:ty, $addr:expr) => {
157 // SAFETY: By the type invariant `addr` is a valid address for MMIO operations.
158 unsafe { bindings::$c_fn($addr as *const c_void) as $type }
159 };
160
161 (fallible, $c_fn:ident, $self:ident, $type:ty, $addr:expr) => {{
162 // SAFETY: By the type invariant `addr` is a valid address for MMIO operations.
163 Ok(unsafe { bindings::$c_fn($addr as *const c_void) as $type })
164 }};
165}
166
167/// Internal helper macros used to invoke C MMIO write functions.
168///
169/// This macro is intended to be used by higher-level MMIO access macros (define_write) and provides
170/// a unified expansion for infallible vs. fallible write semantics. It emits a direct call into the
171/// corresponding C helper and performs the required cast to the Rust return type.
172///
173/// # Parameters
174///
175/// * `$c_fn` – The C function performing the MMIO write.
176/// * `$self` – The I/O backend object.
177/// * `$ty` – The type of the written value.
178/// * `$addr` – The MMIO address to write.
179/// * `$value` – The value to write.
180///
181/// This macro does not perform any validation; all invariants must be upheld by the higher-level
182/// abstraction invoking it.
183macro_rules! call_mmio_write {
184 (infallible, $c_fn:ident, $self:ident, $ty:ty, $addr:expr, $value:expr) => {
185 // SAFETY: By the type invariant `addr` is a valid address for MMIO operations.
186 unsafe { bindings::$c_fn($value, $addr as *mut c_void) }
187 };
188
189 (fallible, $c_fn:ident, $self:ident, $ty:ty, $addr:expr, $value:expr) => {{
190 // SAFETY: By the type invariant `addr` is a valid address for MMIO operations.
191 unsafe { bindings::$c_fn($value, $addr as *mut c_void) };
192 Ok(())
193 }};
194}
195
196macro_rules! define_read {
197 (infallible, $(#[$attr:meta])* $vis:vis $name:ident, $call_macro:ident($c_fn:ident) ->
198 $type_name:ty) => {
199 /// Read IO data from a given offset known at compile time.
200 ///
201 /// Bound checks are performed on compile time, hence if the offset is not known at compile
202 /// time, the build will fail.
203 $(#[$attr])*
204 // Always inline to optimize out error path of `io_addr_assert`.
205 #[inline(always)]
206 $vis fn $name(&self, offset: usize) -> $type_name {
207 let addr = self.io_addr_assert::<$type_name>(offset);
208
209 // SAFETY: By the type invariant `addr` is a valid address for IO operations.
210 $call_macro!(infallible, $c_fn, self, $type_name, addr)
211 }
212 };
213
214 (fallible, $(#[$attr:meta])* $vis:vis $try_name:ident, $call_macro:ident($c_fn:ident) ->
215 $type_name:ty) => {
216 /// Read IO data from a given offset.
217 ///
218 /// Bound checks are performed on runtime, it fails if the offset (plus the type size) is
219 /// out of bounds.
220 $(#[$attr])*
221 $vis fn $try_name(&self, offset: usize) -> Result<$type_name> {
222 let addr = self.io_addr::<$type_name>(offset)?;
223
224 // SAFETY: By the type invariant `addr` is a valid address for IO operations.
225 $call_macro!(fallible, $c_fn, self, $type_name, addr)
226 }
227 };
228}
229pub(crate) use define_read;
230
231macro_rules! define_write {
232 (infallible, $(#[$attr:meta])* $vis:vis $name:ident, $call_macro:ident($c_fn:ident) <-
233 $type_name:ty) => {
234 /// Write IO data from a given offset known at compile time.
235 ///
236 /// Bound checks are performed on compile time, hence if the offset is not known at compile
237 /// time, the build will fail.
238 $(#[$attr])*
239 // Always inline to optimize out error path of `io_addr_assert`.
240 #[inline(always)]
241 $vis fn $name(&self, value: $type_name, offset: usize) {
242 let addr = self.io_addr_assert::<$type_name>(offset);
243
244 $call_macro!(infallible, $c_fn, self, $type_name, addr, value);
245 }
246 };
247
248 (fallible, $(#[$attr:meta])* $vis:vis $try_name:ident, $call_macro:ident($c_fn:ident) <-
249 $type_name:ty) => {
250 /// Write IO data from a given offset.
251 ///
252 /// Bound checks are performed on runtime, it fails if the offset (plus the type size) is
253 /// out of bounds.
254 $(#[$attr])*
255 $vis fn $try_name(&self, value: $type_name, offset: usize) -> Result {
256 let addr = self.io_addr::<$type_name>(offset)?;
257
258 $call_macro!(fallible, $c_fn, self, $type_name, addr, value)
259 }
260 };
261}
262pub(crate) use define_write;
263
264/// Checks whether an access of type `U` at the given `offset`
265/// is valid within this region.
266#[inline]
267const fn offset_valid<U>(offset: usize, size: usize) -> bool {
268 let type_size = core::mem::size_of::<U>();
269 if let Some(end) = offset.checked_add(type_size) {
270 end <= size && offset % type_size == 0
271 } else {
272 false
273 }
274}
275
276/// Marker trait indicating that an I/O backend supports operations of a certain type.
277///
278/// Different I/O backends can implement this trait to expose only the operations they support.
279///
280/// For example, a PCI configuration space may implement `IoCapable<u8>`, `IoCapable<u16>`,
281/// and `IoCapable<u32>`, but not `IoCapable<u64>`, while an MMIO region on a 64-bit
282/// system might implement all four.
283pub trait IoCapable<T> {}
284
285/// Types implementing this trait (e.g. MMIO BARs or PCI config regions)
286/// can perform I/O operations on regions of memory.
287///
288/// This is an abstract representation to be implemented by arbitrary I/O
289/// backends (e.g. MMIO, PCI config space, etc.).
290///
291/// The [`Io`] trait provides:
292/// - Base address and size information
293/// - Helper methods for offset validation and address calculation
294/// - Fallible (runtime checked) accessors for different data widths
295///
296/// Which I/O methods are available depends on which [`IoCapable<T>`] traits
297/// are implemented for the type.
298///
299/// # Examples
300///
301/// For MMIO regions, all widths (u8, u16, u32, and u64 on 64-bit systems) are typically
302/// supported. For PCI configuration space, u8, u16, and u32 are supported but u64 is not.
303pub trait Io {
304 /// Returns the base address of this mapping.
305 fn addr(&self) -> usize;
306
307 /// Returns the maximum size of this mapping.
308 fn maxsize(&self) -> usize;
309
310 /// Returns the absolute I/O address for a given `offset`,
311 /// performing runtime bound checks.
312 #[inline]
313 fn io_addr<U>(&self, offset: usize) -> Result<usize> {
314 if !offset_valid::<U>(offset, self.maxsize()) {
315 return Err(EINVAL);
316 }
317
318 // Probably no need to check, since the safety requirements of `Self::new` guarantee that
319 // this can't overflow.
320 self.addr().checked_add(offset).ok_or(EINVAL)
321 }
322
323 /// Fallible 8-bit read with runtime bounds check.
324 #[inline(always)]
325 fn try_read8(&self, _offset: usize) -> Result<u8>
326 where
327 Self: IoCapable<u8>,
328 {
329 build_error!("Backend does not support fallible 8-bit read")
330 }
331
332 /// Fallible 16-bit read with runtime bounds check.
333 #[inline(always)]
334 fn try_read16(&self, _offset: usize) -> Result<u16>
335 where
336 Self: IoCapable<u16>,
337 {
338 build_error!("Backend does not support fallible 16-bit read")
339 }
340
341 /// Fallible 32-bit read with runtime bounds check.
342 #[inline(always)]
343 fn try_read32(&self, _offset: usize) -> Result<u32>
344 where
345 Self: IoCapable<u32>,
346 {
347 build_error!("Backend does not support fallible 32-bit read")
348 }
349
350 /// Fallible 64-bit read with runtime bounds check.
351 #[inline(always)]
352 fn try_read64(&self, _offset: usize) -> Result<u64>
353 where
354 Self: IoCapable<u64>,
355 {
356 build_error!("Backend does not support fallible 64-bit read")
357 }
358
359 /// Fallible 8-bit write with runtime bounds check.
360 #[inline(always)]
361 fn try_write8(&self, _value: u8, _offset: usize) -> Result
362 where
363 Self: IoCapable<u8>,
364 {
365 build_error!("Backend does not support fallible 8-bit write")
366 }
367
368 /// Fallible 16-bit write with runtime bounds check.
369 #[inline(always)]
370 fn try_write16(&self, _value: u16, _offset: usize) -> Result
371 where
372 Self: IoCapable<u16>,
373 {
374 build_error!("Backend does not support fallible 16-bit write")
375 }
376
377 /// Fallible 32-bit write with runtime bounds check.
378 #[inline(always)]
379 fn try_write32(&self, _value: u32, _offset: usize) -> Result
380 where
381 Self: IoCapable<u32>,
382 {
383 build_error!("Backend does not support fallible 32-bit write")
384 }
385
386 /// Fallible 64-bit write with runtime bounds check.
387 #[inline(always)]
388 fn try_write64(&self, _value: u64, _offset: usize) -> Result
389 where
390 Self: IoCapable<u64>,
391 {
392 build_error!("Backend does not support fallible 64-bit write")
393 }
394
395 /// Infallible 8-bit read with compile-time bounds check.
396 #[inline(always)]
397 fn read8(&self, _offset: usize) -> u8
398 where
399 Self: IoKnownSize + IoCapable<u8>,
400 {
401 build_error!("Backend does not support infallible 8-bit read")
402 }
403
404 /// Infallible 16-bit read with compile-time bounds check.
405 #[inline(always)]
406 fn read16(&self, _offset: usize) -> u16
407 where
408 Self: IoKnownSize + IoCapable<u16>,
409 {
410 build_error!("Backend does not support infallible 16-bit read")
411 }
412
413 /// Infallible 32-bit read with compile-time bounds check.
414 #[inline(always)]
415 fn read32(&self, _offset: usize) -> u32
416 where
417 Self: IoKnownSize + IoCapable<u32>,
418 {
419 build_error!("Backend does not support infallible 32-bit read")
420 }
421
422 /// Infallible 64-bit read with compile-time bounds check.
423 #[inline(always)]
424 fn read64(&self, _offset: usize) -> u64
425 where
426 Self: IoKnownSize + IoCapable<u64>,
427 {
428 build_error!("Backend does not support infallible 64-bit read")
429 }
430
431 /// Infallible 8-bit write with compile-time bounds check.
432 #[inline(always)]
433 fn write8(&self, _value: u8, _offset: usize)
434 where
435 Self: IoKnownSize + IoCapable<u8>,
436 {
437 build_error!("Backend does not support infallible 8-bit write")
438 }
439
440 /// Infallible 16-bit write with compile-time bounds check.
441 #[inline(always)]
442 fn write16(&self, _value: u16, _offset: usize)
443 where
444 Self: IoKnownSize + IoCapable<u16>,
445 {
446 build_error!("Backend does not support infallible 16-bit write")
447 }
448
449 /// Infallible 32-bit write with compile-time bounds check.
450 #[inline(always)]
451 fn write32(&self, _value: u32, _offset: usize)
452 where
453 Self: IoKnownSize + IoCapable<u32>,
454 {
455 build_error!("Backend does not support infallible 32-bit write")
456 }
457
458 /// Infallible 64-bit write with compile-time bounds check.
459 #[inline(always)]
460 fn write64(&self, _value: u64, _offset: usize)
461 where
462 Self: IoKnownSize + IoCapable<u64>,
463 {
464 build_error!("Backend does not support infallible 64-bit write")
465 }
466}
467
468/// Trait for types with a known size at compile time.
469///
470/// This trait is implemented by I/O backends that have a compile-time known size,
471/// enabling the use of infallible I/O accessors with compile-time bounds checking.
472///
473/// Types implementing this trait can use the infallible methods in [`Io`] trait
474/// (e.g., `read8`, `write32`), which require `Self: IoKnownSize` bound.
475pub trait IoKnownSize: Io {
476 /// Minimum usable size of this region.
477 const MIN_SIZE: usize;
478
479 /// Returns the absolute I/O address for a given `offset`,
480 /// performing compile-time bound checks.
481 // Always inline to optimize out error path of `build_assert`.
482 #[inline(always)]
483 fn io_addr_assert<U>(&self, offset: usize) -> usize {
484 build_assert!(offset_valid::<U>(offset, Self::MIN_SIZE));
485
486 self.addr() + offset
487 }
488}
489
490// MMIO regions support 8, 16, and 32-bit accesses.
491impl<const SIZE: usize> IoCapable<u8> for Mmio<SIZE> {}
492impl<const SIZE: usize> IoCapable<u16> for Mmio<SIZE> {}
493impl<const SIZE: usize> IoCapable<u32> for Mmio<SIZE> {}
494
495// MMIO regions on 64-bit systems also support 64-bit accesses.
496#[cfg(CONFIG_64BIT)]
497impl<const SIZE: usize> IoCapable<u64> for Mmio<SIZE> {}
498
499impl<const SIZE: usize> Io for Mmio<SIZE> {
500 /// Returns the base address of this mapping.
501 #[inline]
502 fn addr(&self) -> usize {
503 self.0.addr()
504 }
505
506 /// Returns the maximum size of this mapping.
507 #[inline]
508 fn maxsize(&self) -> usize {
509 self.0.maxsize()
510 }
511
512 define_read!(fallible, try_read8, call_mmio_read(readb) -> u8);
513 define_read!(fallible, try_read16, call_mmio_read(readw) -> u16);
514 define_read!(fallible, try_read32, call_mmio_read(readl) -> u32);
515 define_read!(
516 fallible,
517 #[cfg(CONFIG_64BIT)]
518 try_read64,
519 call_mmio_read(readq) -> u64
520 );
521
522 define_write!(fallible, try_write8, call_mmio_write(writeb) <- u8);
523 define_write!(fallible, try_write16, call_mmio_write(writew) <- u16);
524 define_write!(fallible, try_write32, call_mmio_write(writel) <- u32);
525 define_write!(
526 fallible,
527 #[cfg(CONFIG_64BIT)]
528 try_write64,
529 call_mmio_write(writeq) <- u64
530 );
531
532 define_read!(infallible, read8, call_mmio_read(readb) -> u8);
533 define_read!(infallible, read16, call_mmio_read(readw) -> u16);
534 define_read!(infallible, read32, call_mmio_read(readl) -> u32);
535 define_read!(
536 infallible,
537 #[cfg(CONFIG_64BIT)]
538 read64,
539 call_mmio_read(readq) -> u64
540 );
541
542 define_write!(infallible, write8, call_mmio_write(writeb) <- u8);
543 define_write!(infallible, write16, call_mmio_write(writew) <- u16);
544 define_write!(infallible, write32, call_mmio_write(writel) <- u32);
545 define_write!(
546 infallible,
547 #[cfg(CONFIG_64BIT)]
548 write64,
549 call_mmio_write(writeq) <- u64
550 );
551}
552
553impl<const SIZE: usize> IoKnownSize for Mmio<SIZE> {
554 const MIN_SIZE: usize = SIZE;
555}
556
557impl<const SIZE: usize> Mmio<SIZE> {
558 /// Converts an `MmioRaw` into an `Mmio` instance, providing the accessors to the MMIO mapping.
559 ///
560 /// # Safety
561 ///
562 /// Callers must ensure that `addr` is the start of a valid I/O mapped memory region of size
563 /// `maxsize`.
564 pub unsafe fn from_raw(raw: &MmioRaw<SIZE>) -> &Self {
565 // SAFETY: `Mmio` is a transparent wrapper around `MmioRaw`.
566 unsafe { &*core::ptr::from_ref(raw).cast() }
567 }
568
569 define_read!(infallible, pub read8_relaxed, call_mmio_read(readb_relaxed) -> u8);
570 define_read!(infallible, pub read16_relaxed, call_mmio_read(readw_relaxed) -> u16);
571 define_read!(infallible, pub read32_relaxed, call_mmio_read(readl_relaxed) -> u32);
572 define_read!(
573 infallible,
574 #[cfg(CONFIG_64BIT)]
575 pub read64_relaxed,
576 call_mmio_read(readq_relaxed) -> u64
577 );
578
579 define_read!(fallible, pub try_read8_relaxed, call_mmio_read(readb_relaxed) -> u8);
580 define_read!(fallible, pub try_read16_relaxed, call_mmio_read(readw_relaxed) -> u16);
581 define_read!(fallible, pub try_read32_relaxed, call_mmio_read(readl_relaxed) -> u32);
582 define_read!(
583 fallible,
584 #[cfg(CONFIG_64BIT)]
585 pub try_read64_relaxed,
586 call_mmio_read(readq_relaxed) -> u64
587 );
588
589 define_write!(infallible, pub write8_relaxed, call_mmio_write(writeb_relaxed) <- u8);
590 define_write!(infallible, pub write16_relaxed, call_mmio_write(writew_relaxed) <- u16);
591 define_write!(infallible, pub write32_relaxed, call_mmio_write(writel_relaxed) <- u32);
592 define_write!(
593 infallible,
594 #[cfg(CONFIG_64BIT)]
595 pub write64_relaxed,
596 call_mmio_write(writeq_relaxed) <- u64
597 );
598
599 define_write!(fallible, pub try_write8_relaxed, call_mmio_write(writeb_relaxed) <- u8);
600 define_write!(fallible, pub try_write16_relaxed, call_mmio_write(writew_relaxed) <- u16);
601 define_write!(fallible, pub try_write32_relaxed, call_mmio_write(writel_relaxed) <- u32);
602 define_write!(
603 fallible,
604 #[cfg(CONFIG_64BIT)]
605 pub try_write64_relaxed,
606 call_mmio_write(writeq_relaxed) <- u64
607 );
608}