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