xref: /linux/rust/kernel/pci/io.rs (revision e2d599021c843d97ee38ba351cb0117eb984e038)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! PCI memory-mapped I/O infrastructure.
4 
5 use super::Device;
6 use crate::{
7     bindings,
8     device,
9     devres::Devres,
10     io::{
11         io_define_read,
12         io_define_write,
13         Io,
14         IoCapable,
15         IoKnownSize,
16         Mmio,
17         MmioRaw, //
18     },
19     prelude::*,
20     sync::aref::ARef, //
21 };
22 use core::{
23     marker::PhantomData,
24     ops::Deref, //
25 };
26 
27 /// Represents the size of a PCI configuration space.
28 ///
29 /// PCI devices can have either a *normal* (legacy) configuration space of 256 bytes,
30 /// or an *extended* configuration space of 4096 bytes as defined in the PCI Express
31 /// specification.
32 #[repr(usize)]
33 #[derive(Eq, PartialEq)]
34 pub enum ConfigSpaceSize {
35     /// 256-byte legacy PCI configuration space.
36     Normal = 256,
37 
38     /// 4096-byte PCIe extended configuration space.
39     Extended = 4096,
40 }
41 
42 impl ConfigSpaceSize {
43     /// Get the raw value of this enum.
44     #[inline(always)]
45     pub const fn into_raw(self) -> usize {
46         // CAST: PCI configuration space size is at most 4096 bytes, so the value always fits
47         // within `usize` without truncation or sign change.
48         self as usize
49     }
50 }
51 
52 /// Marker type for normal (256-byte) PCI configuration space.
53 pub struct Normal;
54 
55 /// Marker type for extended (4096-byte) PCIe configuration space.
56 pub struct Extended;
57 
58 /// Trait for PCI configuration space size markers.
59 ///
60 /// This trait is implemented by [`Normal`] and [`Extended`] to provide
61 /// compile-time knowledge of the configuration space size.
62 pub trait ConfigSpaceKind {
63     /// The size of this configuration space in bytes.
64     const SIZE: usize;
65 }
66 
67 impl ConfigSpaceKind for Normal {
68     const SIZE: usize = 256;
69 }
70 
71 impl ConfigSpaceKind for Extended {
72     const SIZE: usize = 4096;
73 }
74 
75 /// The PCI configuration space of a device.
76 ///
77 /// Provides typed read and write accessors for configuration registers
78 /// using the standard `pci_read_config_*` and `pci_write_config_*` helpers.
79 ///
80 /// The generic parameter `S` indicates the maximum size of the configuration space.
81 /// Use [`Normal`] for 256-byte legacy configuration space or [`Extended`] for
82 /// 4096-byte PCIe extended configuration space (default).
83 pub struct ConfigSpace<'a, S: ConfigSpaceKind = Extended> {
84     pub(crate) pdev: &'a Device<device::Bound>,
85     _marker: PhantomData<S>,
86 }
87 
88 /// Internal helper macros used to invoke C PCI configuration space read functions.
89 ///
90 /// This macro is intended to be used by higher-level PCI configuration space access macros
91 /// (io_define_read) and provides a unified expansion for infallible vs. fallible read semantics. It
92 /// emits a direct call into the corresponding C helper and performs the required cast to the Rust
93 /// return type.
94 ///
95 /// # Parameters
96 ///
97 /// * `$c_fn` – The C function performing the PCI configuration space write.
98 /// * `$self` – The I/O backend object.
99 /// * `$ty` – The type of the value to read.
100 /// * `$addr` – The PCI configuration space offset to read.
101 ///
102 /// This macro does not perform any validation; all invariants must be upheld by the higher-level
103 /// abstraction invoking it.
104 macro_rules! call_config_read {
105     (infallible, $c_fn:ident, $self:ident, $ty:ty, $addr:expr) => {{
106         let mut val: $ty = 0;
107         // SAFETY: By the type invariant `$self.pdev` is a valid address.
108         // CAST: The offset is cast to `i32` because the C functions expect a 32-bit signed offset
109         // parameter. PCI configuration space size is at most 4096 bytes, so the value always fits
110         // within `i32` without truncation or sign change.
111         // Return value from C function is ignored in infallible accessors.
112         let _ret = unsafe { bindings::$c_fn($self.pdev.as_raw(), $addr as i32, &mut val) };
113         val
114     }};
115 }
116 
117 /// Internal helper macros used to invoke C PCI configuration space write functions.
118 ///
119 /// This macro is intended to be used by higher-level PCI configuration space access macros
120 /// (io_define_write) and provides a unified expansion for infallible vs. fallible read semantics.
121 /// It emits a direct call into the corresponding C helper and performs the required cast to the
122 /// Rust return type.
123 ///
124 /// # Parameters
125 ///
126 /// * `$c_fn` – The C function performing the PCI configuration space write.
127 /// * `$self` – The I/O backend object.
128 /// * `$ty` – The type of the written value.
129 /// * `$addr` – The configuration space offset to write.
130 /// * `$value` – The value to write.
131 ///
132 /// This macro does not perform any validation; all invariants must be upheld by the higher-level
133 /// abstraction invoking it.
134 macro_rules! call_config_write {
135     (infallible, $c_fn:ident, $self:ident, $ty:ty, $addr:expr, $value:expr) => {
136         // SAFETY: By the type invariant `$self.pdev` is a valid address.
137         // CAST: The offset is cast to `i32` because the C functions expect a 32-bit signed offset
138         // parameter. PCI configuration space size is at most 4096 bytes, so the value always fits
139         // within `i32` without truncation or sign change.
140         // Return value from C function is ignored in infallible accessors.
141         let _ret = unsafe { bindings::$c_fn($self.pdev.as_raw(), $addr as i32, $value) };
142     };
143 }
144 
145 /// Implements [`IoCapable`] on [`ConfigSpace`] for `$ty` using `$read_fn` and `$write_fn`.
146 macro_rules! impl_config_space_io_capable {
147     ($ty:ty, $read_fn:ident, $write_fn:ident) => {
148         impl<'a, S: ConfigSpaceKind> IoCapable<$ty> for ConfigSpace<'a, S> {
149             unsafe fn io_read(&self, address: usize) -> $ty {
150                 let mut val: $ty = 0;
151 
152                 // Return value from C function is ignored in infallible accessors.
153                 let _ret =
154                     // SAFETY: By the type invariant `self.pdev` is a valid address.
155                     // CAST: The offset is cast to `i32` because the C functions expect a 32-bit
156                     // signed offset parameter. PCI configuration space size is at most 4096 bytes,
157                     // so the value always fits within `i32` without truncation or sign change.
158                     unsafe { bindings::$read_fn(self.pdev.as_raw(), address as i32, &mut val) };
159 
160                 val
161             }
162 
163             unsafe fn io_write(&self, value: $ty, address: usize) {
164                 // Return value from C function is ignored in infallible accessors.
165                 let _ret =
166                     // SAFETY: By the type invariant `self.pdev` is a valid address.
167                     // CAST: The offset is cast to `i32` because the C functions expect a 32-bit
168                     // signed offset parameter. PCI configuration space size is at most 4096 bytes,
169                     // so the value always fits within `i32` without truncation or sign change.
170                     unsafe { bindings::$write_fn(self.pdev.as_raw(), address as i32, value) };
171             }
172         }
173     };
174 }
175 
176 // PCI configuration space supports 8, 16, and 32-bit accesses.
177 impl_config_space_io_capable!(u8, pci_read_config_byte, pci_write_config_byte);
178 impl_config_space_io_capable!(u16, pci_read_config_word, pci_write_config_word);
179 impl_config_space_io_capable!(u32, pci_read_config_dword, pci_write_config_dword);
180 
181 impl<'a, S: ConfigSpaceKind> Io for ConfigSpace<'a, S> {
182     /// Returns the base address of the I/O region. It is always 0 for configuration space.
183     #[inline]
184     fn addr(&self) -> usize {
185         0
186     }
187 
188     /// Returns the maximum size of the configuration space.
189     #[inline]
190     fn maxsize(&self) -> usize {
191         self.pdev.cfg_size().into_raw()
192     }
193 
194     // PCI configuration space does not support fallible operations.
195     // The default implementations from the Io trait are not used.
196 
197     io_define_read!(infallible, read8, call_config_read(pci_read_config_byte) -> u8);
198     io_define_read!(infallible, read16, call_config_read(pci_read_config_word) -> u16);
199     io_define_read!(infallible, read32, call_config_read(pci_read_config_dword) -> u32);
200 
201     io_define_write!(infallible, write8, call_config_write(pci_write_config_byte) <- u8);
202     io_define_write!(infallible, write16, call_config_write(pci_write_config_word) <- u16);
203     io_define_write!(infallible, write32, call_config_write(pci_write_config_dword) <- u32);
204 }
205 
206 impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> {
207     const MIN_SIZE: usize = S::SIZE;
208 }
209 
210 /// A PCI BAR to perform I/O-Operations on.
211 ///
212 /// I/O backend assumes that the device is little-endian and will automatically
213 /// convert from little-endian to CPU endianness.
214 ///
215 /// # Invariants
216 ///
217 /// `Bar` always holds an `IoRaw` instance that holds a valid pointer to the start of the I/O
218 /// memory mapped PCI BAR and its size.
219 pub struct Bar<const SIZE: usize = 0> {
220     pdev: ARef<Device>,
221     io: MmioRaw<SIZE>,
222     num: i32,
223 }
224 
225 impl<const SIZE: usize> Bar<SIZE> {
226     pub(super) fn new(pdev: &Device, num: u32, name: &CStr) -> Result<Self> {
227         let len = pdev.resource_len(num)?;
228         if len == 0 {
229             return Err(ENOMEM);
230         }
231 
232         // Convert to `i32`, since that's what all the C bindings use.
233         let num = i32::try_from(num)?;
234 
235         // SAFETY:
236         // `pdev` is valid by the invariants of `Device`.
237         // `num` is checked for validity by a previous call to `Device::resource_len`.
238         // `name` is always valid.
239         let ret = unsafe { bindings::pci_request_region(pdev.as_raw(), num, name.as_char_ptr()) };
240         if ret != 0 {
241             return Err(EBUSY);
242         }
243 
244         // SAFETY:
245         // `pdev` is valid by the invariants of `Device`.
246         // `num` is checked for validity by a previous call to `Device::resource_len`.
247         // `name` is always valid.
248         let ioptr: usize = unsafe { bindings::pci_iomap(pdev.as_raw(), num, 0) } as usize;
249         if ioptr == 0 {
250             // SAFETY:
251             // `pdev` is valid by the invariants of `Device`.
252             // `num` is checked for validity by a previous call to `Device::resource_len`.
253             unsafe { bindings::pci_release_region(pdev.as_raw(), num) };
254             return Err(ENOMEM);
255         }
256 
257         let io = match MmioRaw::new(ioptr, len as usize) {
258             Ok(io) => io,
259             Err(err) => {
260                 // SAFETY:
261                 // `pdev` is valid by the invariants of `Device`.
262                 // `ioptr` is guaranteed to be the start of a valid I/O mapped memory region.
263                 // `num` is checked for validity by a previous call to `Device::resource_len`.
264                 unsafe { Self::do_release(pdev, ioptr, num) };
265                 return Err(err);
266             }
267         };
268 
269         Ok(Bar {
270             pdev: pdev.into(),
271             io,
272             num,
273         })
274     }
275 
276     /// # Safety
277     ///
278     /// `ioptr` must be a valid pointer to the memory mapped PCI BAR number `num`.
279     unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) {
280         // SAFETY:
281         // `pdev` is valid by the invariants of `Device`.
282         // `ioptr` is valid by the safety requirements.
283         // `num` is valid by the safety requirements.
284         unsafe {
285             bindings::pci_iounmap(pdev.as_raw(), ioptr as *mut c_void);
286             bindings::pci_release_region(pdev.as_raw(), num);
287         }
288     }
289 
290     fn release(&self) {
291         // SAFETY: The safety requirements are guaranteed by the type invariant of `self.pdev`.
292         unsafe { Self::do_release(&self.pdev, self.io.addr(), self.num) };
293     }
294 }
295 
296 impl Bar {
297     #[inline]
298     pub(super) fn index_is_valid(index: u32) -> bool {
299         // A `struct pci_dev` owns an array of resources with at most `PCI_NUM_RESOURCES` entries.
300         index < bindings::PCI_NUM_RESOURCES
301     }
302 }
303 
304 impl<const SIZE: usize> Drop for Bar<SIZE> {
305     fn drop(&mut self) {
306         self.release();
307     }
308 }
309 
310 impl<const SIZE: usize> Deref for Bar<SIZE> {
311     type Target = Mmio<SIZE>;
312 
313     fn deref(&self) -> &Self::Target {
314         // SAFETY: By the type invariant of `Self`, the MMIO range in `self.io` is properly mapped.
315         unsafe { Mmio::from_raw(&self.io) }
316     }
317 }
318 
319 impl Device<device::Bound> {
320     /// Maps an entire PCI BAR after performing a region-request on it. I/O operation bound checks
321     /// can be performed on compile time for offsets (plus the requested type size) < SIZE.
322     pub fn iomap_region_sized<'a, const SIZE: usize>(
323         &'a self,
324         bar: u32,
325         name: &'a CStr,
326     ) -> impl PinInit<Devres<Bar<SIZE>>, Error> + 'a {
327         Devres::new(self.as_ref(), Bar::<SIZE>::new(self, bar, name))
328     }
329 
330     /// Maps an entire PCI BAR after performing a region-request on it.
331     pub fn iomap_region<'a>(
332         &'a self,
333         bar: u32,
334         name: &'a CStr,
335     ) -> impl PinInit<Devres<Bar>, Error> + 'a {
336         self.iomap_region_sized::<0>(bar, name)
337     }
338 
339     /// Returns the size of configuration space.
340     pub fn cfg_size(&self) -> ConfigSpaceSize {
341         // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
342         let size = unsafe { (*self.as_raw()).cfg_size };
343         match size {
344             256 => ConfigSpaceSize::Normal,
345             4096 => ConfigSpaceSize::Extended,
346             _ => {
347                 // PANIC: The PCI subsystem only ever reports the configuration space size as either
348                 // `ConfigSpaceSize::Normal` or `ConfigSpaceSize::Extended`.
349                 unreachable!();
350             }
351         }
352     }
353 
354     /// Return an initialized normal (256-byte) config space object.
355     pub fn config_space<'a>(&'a self) -> ConfigSpace<'a, Normal> {
356         ConfigSpace {
357             pdev: self,
358             _marker: PhantomData,
359         }
360     }
361 
362     /// Return an initialized extended (4096-byte) config space object.
363     pub fn config_space_extended<'a>(&'a self) -> Result<ConfigSpace<'a, Extended>> {
364         if self.cfg_size() != ConfigSpaceSize::Extended {
365             return Err(EINVAL);
366         }
367 
368         Ok(ConfigSpace {
369             pdev: self,
370             _marker: PhantomData,
371         })
372     }
373 }
374