xref: /linux/rust/kernel/pci/io.rs (revision eb3dad518e4da48ab6c6df16aa8895b8b0bd6ecf)
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         define_read,
12         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 /// (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 /// (define_write) and provides a unified expansion for infallible vs. fallible read semantics. It
121 /// emits a direct call into the corresponding C helper and performs the required cast to the Rust
122 /// 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 // PCI configuration space supports 8, 16, and 32-bit accesses.
146 impl<'a, S: ConfigSpaceKind> IoCapable<u8> for ConfigSpace<'a, S> {}
147 impl<'a, S: ConfigSpaceKind> IoCapable<u16> for ConfigSpace<'a, S> {}
148 impl<'a, S: ConfigSpaceKind> IoCapable<u32> for ConfigSpace<'a, S> {}
149 
150 impl<'a, S: ConfigSpaceKind> Io for ConfigSpace<'a, S> {
151     const MIN_SIZE: usize = S::SIZE;
152 
153     /// Returns the base address of the I/O region. It is always 0 for configuration space.
154     #[inline]
155     fn addr(&self) -> usize {
156         0
157     }
158 
159     /// Returns the maximum size of the configuration space.
160     #[inline]
161     fn maxsize(&self) -> usize {
162         self.pdev.cfg_size().into_raw()
163     }
164 
165     // PCI configuration space does not support fallible operations.
166     // The default implementations from the Io trait are not used.
167 
168     define_read!(infallible, read8, call_config_read(pci_read_config_byte) -> u8);
169     define_read!(infallible, read16, call_config_read(pci_read_config_word) -> u16);
170     define_read!(infallible, read32, call_config_read(pci_read_config_dword) -> u32);
171 
172     define_write!(infallible, write8, call_config_write(pci_write_config_byte) <- u8);
173     define_write!(infallible, write16, call_config_write(pci_write_config_word) <- u16);
174     define_write!(infallible, write32, call_config_write(pci_write_config_dword) <- u32);
175 }
176 
177 /// Marker trait indicating ConfigSpace has a known size at compile time.
178 impl<'a, S: ConfigSpaceKind> IoKnownSize for ConfigSpace<'a, S> {}
179 
180 /// A PCI BAR to perform I/O-Operations on.
181 ///
182 /// I/O backend assumes that the device is little-endian and will automatically
183 /// convert from little-endian to CPU endianness.
184 ///
185 /// # Invariants
186 ///
187 /// `Bar` always holds an `IoRaw` instance that holds a valid pointer to the start of the I/O
188 /// memory mapped PCI BAR and its size.
189 pub struct Bar<const SIZE: usize = 0> {
190     pdev: ARef<Device>,
191     io: MmioRaw<SIZE>,
192     num: i32,
193 }
194 
195 impl<const SIZE: usize> Bar<SIZE> {
196     pub(super) fn new(pdev: &Device, num: u32, name: &CStr) -> Result<Self> {
197         let len = pdev.resource_len(num)?;
198         if len == 0 {
199             return Err(ENOMEM);
200         }
201 
202         // Convert to `i32`, since that's what all the C bindings use.
203         let num = i32::try_from(num)?;
204 
205         // SAFETY:
206         // `pdev` is valid by the invariants of `Device`.
207         // `num` is checked for validity by a previous call to `Device::resource_len`.
208         // `name` is always valid.
209         let ret = unsafe { bindings::pci_request_region(pdev.as_raw(), num, name.as_char_ptr()) };
210         if ret != 0 {
211             return Err(EBUSY);
212         }
213 
214         // SAFETY:
215         // `pdev` is valid by the invariants of `Device`.
216         // `num` is checked for validity by a previous call to `Device::resource_len`.
217         // `name` is always valid.
218         let ioptr: usize = unsafe { bindings::pci_iomap(pdev.as_raw(), num, 0) } as usize;
219         if ioptr == 0 {
220             // SAFETY:
221             // `pdev` is valid by the invariants of `Device`.
222             // `num` is checked for validity by a previous call to `Device::resource_len`.
223             unsafe { bindings::pci_release_region(pdev.as_raw(), num) };
224             return Err(ENOMEM);
225         }
226 
227         let io = match MmioRaw::new(ioptr, len as usize) {
228             Ok(io) => io,
229             Err(err) => {
230                 // SAFETY:
231                 // `pdev` is valid by the invariants of `Device`.
232                 // `ioptr` is guaranteed to be the start of a valid I/O mapped memory region.
233                 // `num` is checked for validity by a previous call to `Device::resource_len`.
234                 unsafe { Self::do_release(pdev, ioptr, num) };
235                 return Err(err);
236             }
237         };
238 
239         Ok(Bar {
240             pdev: pdev.into(),
241             io,
242             num,
243         })
244     }
245 
246     /// # Safety
247     ///
248     /// `ioptr` must be a valid pointer to the memory mapped PCI BAR number `num`.
249     unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) {
250         // SAFETY:
251         // `pdev` is valid by the invariants of `Device`.
252         // `ioptr` is valid by the safety requirements.
253         // `num` is valid by the safety requirements.
254         unsafe {
255             bindings::pci_iounmap(pdev.as_raw(), ioptr as *mut c_void);
256             bindings::pci_release_region(pdev.as_raw(), num);
257         }
258     }
259 
260     fn release(&self) {
261         // SAFETY: The safety requirements are guaranteed by the type invariant of `self.pdev`.
262         unsafe { Self::do_release(&self.pdev, self.io.addr(), self.num) };
263     }
264 }
265 
266 impl Bar {
267     #[inline]
268     pub(super) fn index_is_valid(index: u32) -> bool {
269         // A `struct pci_dev` owns an array of resources with at most `PCI_NUM_RESOURCES` entries.
270         index < bindings::PCI_NUM_RESOURCES
271     }
272 }
273 
274 impl<const SIZE: usize> Drop for Bar<SIZE> {
275     fn drop(&mut self) {
276         self.release();
277     }
278 }
279 
280 impl<const SIZE: usize> Deref for Bar<SIZE> {
281     type Target = Mmio<SIZE>;
282 
283     fn deref(&self) -> &Self::Target {
284         // SAFETY: By the type invariant of `Self`, the MMIO range in `self.io` is properly mapped.
285         unsafe { Mmio::from_raw(&self.io) }
286     }
287 }
288 
289 impl Device<device::Bound> {
290     /// Maps an entire PCI BAR after performing a region-request on it. I/O operation bound checks
291     /// can be performed on compile time for offsets (plus the requested type size) < SIZE.
292     pub fn iomap_region_sized<'a, const SIZE: usize>(
293         &'a self,
294         bar: u32,
295         name: &'a CStr,
296     ) -> impl PinInit<Devres<Bar<SIZE>>, Error> + 'a {
297         Devres::new(self.as_ref(), Bar::<SIZE>::new(self, bar, name))
298     }
299 
300     /// Maps an entire PCI BAR after performing a region-request on it.
301     pub fn iomap_region<'a>(
302         &'a self,
303         bar: u32,
304         name: &'a CStr,
305     ) -> impl PinInit<Devres<Bar>, Error> + 'a {
306         self.iomap_region_sized::<0>(bar, name)
307     }
308 
309     /// Returns the size of configuration space.
310     pub fn cfg_size(&self) -> ConfigSpaceSize {
311         // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
312         let size = unsafe { (*self.as_raw()).cfg_size };
313         match size {
314             256 => ConfigSpaceSize::Normal,
315             4096 => ConfigSpaceSize::Extended,
316             _ => {
317                 // PANIC: The PCI subsystem only ever reports the configuration space size as either
318                 // `ConfigSpaceSize::Normal` or `ConfigSpaceSize::Extended`.
319                 unreachable!();
320             }
321         }
322     }
323 
324     /// Return an initialized normal (256-byte) config space object.
325     pub fn config_space<'a>(&'a self) -> ConfigSpace<'a, Normal> {
326         ConfigSpace {
327             pdev: self,
328             _marker: PhantomData,
329         }
330     }
331 
332     /// Return an initialized extended (4096-byte) config space object.
333     pub fn config_space_extended<'a>(&'a self) -> Result<ConfigSpace<'a, Extended>> {
334         if self.cfg_size() != ConfigSpaceSize::Extended {
335             return Err(EINVAL);
336         }
337 
338         Ok(ConfigSpace {
339             pdev: self,
340             _marker: PhantomData,
341         })
342     }
343 }
344