xref: /linux/rust/kernel/pci.rs (revision e727d1c382a0cb2e10fd7aabef9217d1a37c80c7)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Abstractions for the PCI bus.
4 //!
5 //! C header: [`include/linux/pci.h`](srctree/include/linux/pci.h)
6 
7 use crate::{
8     bindings,
9     container_of,
10     device,
11     device_id::{
12         RawDeviceId,
13         RawDeviceIdIndex, //
14     },
15     driver,
16     error::{
17         from_result,
18         to_result, //
19     },
20     io::resource,
21     prelude::*,
22     str::CStr,
23     types::Opaque,
24     ThisModule, //
25 };
26 use core::{
27     marker::PhantomData,
28     mem::offset_of,
29     num::NonZero,
30     ptr::{
31         addr_of_mut,
32         NonNull, //
33     },
34 };
35 
36 mod id;
37 mod io;
38 mod irq;
39 
40 pub use self::id::{
41     Class,
42     ClassMask,
43     Vendor, //
44 };
45 pub use self::io::{
46     Bar,
47     ConfigSpace,
48     ConfigSpaceSize,
49     DevresBar,
50     Extended,
51     Normal, //
52 };
53 pub use self::irq::{
54     IrqType,
55     IrqTypes,
56     IrqVector,
57     IrqVectorRegistration, //
58 };
59 
60 /// An adapter for the registration of PCI drivers.
61 pub struct Adapter<T: Driver>(T);
62 
63 // SAFETY:
64 // - `bindings::pci_driver` is a C type declared as `repr(C)`.
65 // - `T::Data` is the type of the driver's device private data.
66 // - `struct pci_driver` embeds a `struct device_driver`.
67 // - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`.
68 unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> {
69     type DriverType = bindings::pci_driver;
70     type DriverData<'bound> = T::Data<'bound>;
71     const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver);
72 }
73 
74 // SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if
75 // a preceding call to `register` has been successful.
76 unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> {
77     unsafe fn register(
78         pdrv: &Opaque<Self::DriverType>,
79         name: &'static CStr,
80         module: &'static ThisModule,
81     ) -> Result {
82         // SAFETY: It's safe to set the fields of `struct pci_driver` on initialization.
83         unsafe {
84             (*pdrv.get()).name = name.as_char_ptr();
85             (*pdrv.get()).probe = Some(Self::probe_callback);
86             (*pdrv.get()).remove = Some(Self::remove_callback);
87             (*pdrv.get()).id_table = T::ID_TABLE.as_ptr();
88         }
89 
90         // SAFETY: `pdrv` is guaranteed to be a valid `DriverType`.
91         to_result(unsafe {
92             bindings::__pci_register_driver(pdrv.get(), module.as_ptr(), name.as_char_ptr())
93         })
94     }
95 
96     unsafe fn unregister(pdrv: &Opaque<Self::DriverType>) {
97         // SAFETY: `pdrv` is guaranteed to be a valid `DriverType`.
98         unsafe { bindings::pci_unregister_driver(pdrv.get()) }
99     }
100 }
101 
102 impl<T: Driver> Adapter<T> {
103     extern "C" fn probe_callback(
104         pdev: *mut bindings::pci_dev,
105         id: *const bindings::pci_device_id,
106     ) -> c_int {
107         // SAFETY: The PCI bus only ever calls the probe callback with a valid pointer to a
108         // `struct pci_dev`.
109         //
110         // INVARIANT: `pdev` is valid for the duration of `probe_callback()`.
111         let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal<'_>>>() };
112 
113         // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct pci_device_id` and
114         // does not add additional invariants, so it's safe to transmute.
115         let id = unsafe { &*id.cast::<DeviceId>() };
116 
117         // SAFETY: `id` comes from `T::ID_TABLE` which is of type `IdArray<_, T::IdInfo>` or
118         // `pci_device_id_any` which has 0 as driver_data. It can also come from dynamic IDs, which
119         // will ensure that `driver_data` exists in `T::ID_TABLE`.
120         let info = unsafe { id.info_unchecked_opt::<T::IdInfo>() };
121 
122         from_result(|| {
123             let data = T::probe(pdev, info);
124 
125             pdev.as_ref().set_drvdata(data)?;
126             Ok(0)
127         })
128     }
129 
130     extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) {
131         // SAFETY: The PCI bus only ever calls the remove callback with a valid pointer to a
132         // `struct pci_dev`.
133         //
134         // INVARIANT: `pdev` is valid for the duration of `remove_callback()`.
135         let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal<'_>>>() };
136 
137         // SAFETY: `remove_callback` is only ever called after a successful call to
138         // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called
139         // and stored a `Pin<KBox<T::Data<'_>>>`.
140         let data = unsafe { pdev.as_ref().drvdata_borrow::<T::Data<'_>>() };
141 
142         T::unbind(pdev, data);
143     }
144 }
145 
146 /// Declares a kernel module that exposes a single PCI driver.
147 ///
148 /// # Examples
149 ///
150 ///```ignore
151 /// kernel::module_pci_driver! {
152 ///     type: MyDriver,
153 ///     name: "Module name",
154 ///     authors: ["Author name"],
155 ///     description: "Description",
156 ///     license: "GPL v2",
157 /// }
158 ///```
159 #[macro_export]
160 macro_rules! module_pci_driver {
161 ($($f:tt)*) => {
162     $crate::module_driver!(<T>, $crate::pci::Adapter<T>, { $($f)* });
163 };
164 }
165 
166 /// Abstraction for the PCI device ID structure ([`struct pci_device_id`]).
167 ///
168 /// [`struct pci_device_id`]: https://docs.kernel.org/PCI/pci.html#c.pci_device_id
169 #[repr(transparent)]
170 #[derive(Clone, Copy)]
171 pub struct DeviceId(bindings::pci_device_id);
172 
173 impl DeviceId {
174     const PCI_ANY_ID: u32 = !0;
175 
176     /// Equivalent to C's `PCI_DEVICE` macro.
177     ///
178     /// Create a new `pci::DeviceId` from a vendor and device ID.
179     #[inline]
180     pub const fn from_id(vendor: Vendor, device: u32) -> Self {
181         Self(bindings::pci_device_id {
182             vendor: vendor.as_raw() as u32,
183             device,
184             subvendor: DeviceId::PCI_ANY_ID,
185             subdevice: DeviceId::PCI_ANY_ID,
186             class: 0,
187             class_mask: 0,
188             driver_data: 0,
189             override_only: 0,
190         })
191     }
192 
193     /// Equivalent to C's `PCI_DEVICE_CLASS` macro.
194     ///
195     /// Create a new `pci::DeviceId` from a class number and mask.
196     #[inline]
197     pub const fn from_class(class: u32, class_mask: u32) -> Self {
198         Self(bindings::pci_device_id {
199             vendor: DeviceId::PCI_ANY_ID,
200             device: DeviceId::PCI_ANY_ID,
201             subvendor: DeviceId::PCI_ANY_ID,
202             subdevice: DeviceId::PCI_ANY_ID,
203             class,
204             class_mask,
205             driver_data: 0,
206             override_only: 0,
207         })
208     }
209 
210     /// Create a new [`DeviceId`] from a class number, mask, and specific vendor.
211     ///
212     /// This is more targeted than [`DeviceId::from_class`]: in addition to matching by [`Vendor`],
213     /// it also matches the PCI [`Class`] (up to the entire 24 bits, depending on the
214     /// [`ClassMask`]).
215     #[inline]
216     pub const fn from_class_and_vendor(
217         class: Class,
218         class_mask: ClassMask,
219         vendor: Vendor,
220     ) -> Self {
221         Self(bindings::pci_device_id {
222             vendor: vendor.as_raw() as u32,
223             device: DeviceId::PCI_ANY_ID,
224             subvendor: DeviceId::PCI_ANY_ID,
225             subdevice: DeviceId::PCI_ANY_ID,
226             class: class.as_raw(),
227             class_mask: class_mask.as_raw(),
228             driver_data: 0,
229             override_only: 0,
230         })
231     }
232 }
233 
234 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `pci_device_id` and does not add
235 // additional invariants, so it's safe to transmute to `RawType`.
236 unsafe impl RawDeviceId for DeviceId {
237     type RawType = bindings::pci_device_id;
238 }
239 
240 // SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.
241 unsafe impl RawDeviceIdIndex for DeviceId {
242     const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::pci_device_id, driver_data);
243 }
244 
245 /// `IdTable` type for PCI.
246 pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;
247 
248 /// Create a PCI `IdTable` with its alias for modpost.
249 #[macro_export]
250 macro_rules! pci_device_table {
251     ($($tt:tt)*) => {
252         $crate::module_device_table!("pci", $crate::pci::DeviceId, $($tt)*);
253     };
254 }
255 
256 /// The PCI driver trait.
257 ///
258 /// # Examples
259 ///
260 ///```
261 /// # use kernel::{bindings, device::Core, pci};
262 ///
263 /// struct MyDriver;
264 ///
265 /// kernel::pci_device_table!(
266 ///     PCI_TABLE,
267 ///     <MyDriver as pci::Driver>::IdInfo,
268 ///     [
269 ///         (
270 ///             pci::DeviceId::from_id(pci::Vendor::REDHAT, bindings::PCI_ANY_ID as u32),
271 ///             (),
272 ///         )
273 ///     ]
274 /// );
275 ///
276 /// impl pci::Driver for MyDriver {
277 ///     type IdInfo = ();
278 ///     type Data<'bound> = Self;
279 ///     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
280 ///
281 ///     fn probe<'bound>(
282 ///         _pdev: &'bound pci::Device<Core<'_>>,
283 ///         _id_info: Option<&'bound Self::IdInfo>,
284 ///     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound {
285 ///         Err(ENODEV)
286 ///     }
287 /// }
288 ///```
289 /// Drivers must implement this trait in order to get a PCI driver registered. Please refer to the
290 /// `Adapter` documentation for an example.
291 pub trait Driver {
292     /// The type holding information about each device id supported by the driver.
293     // TODO: Use `associated_type_defaults` once stabilized:
294     //
295     // ```
296     // type IdInfo: 'static = ();
297     // ```
298     type IdInfo: 'static;
299 
300     /// The type of the driver's bus device private data.
301     type Data<'bound>: Send + 'bound;
302 
303     /// The table of device ids supported by the driver.
304     const ID_TABLE: IdTable<Self::IdInfo>;
305 
306     /// PCI driver probe.
307     ///
308     /// Called when a new pci device is added or discovered. Implementers should
309     /// attempt to initialize the device here.
310     fn probe<'bound>(
311         dev: &'bound Device<device::Core<'_>>,
312         id_info: Option<&'bound Self::IdInfo>,
313     ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound;
314 
315     /// PCI driver unbind.
316     ///
317     /// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback
318     /// is optional.
319     ///
320     /// This callback serves as a place for drivers to perform teardown operations that require a
321     /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O
322     /// operations to gracefully tear down the device.
323     ///
324     /// Otherwise, release operations for driver resources should be performed in `Drop`.
325     fn unbind<'bound>(dev: &'bound Device<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
326         let _ = (dev, this);
327     }
328 }
329 
330 /// The PCI device representation.
331 ///
332 /// This structure represents the Rust abstraction for a C `struct pci_dev`. The implementation
333 /// abstracts the usage of an already existing C `struct pci_dev` within Rust code that we get
334 /// passed from the C side.
335 ///
336 /// # Invariants
337 ///
338 /// A [`Device`] instance represents a valid `struct pci_dev` created by the C portion of the
339 /// kernel.
340 #[repr(transparent)]
341 pub struct Device<Ctx: device::DeviceContext = device::Normal>(
342     Opaque<bindings::pci_dev>,
343     PhantomData<Ctx>,
344 );
345 
346 impl<Ctx: device::DeviceContext> Device<Ctx> {
347     #[inline]
348     fn as_raw(&self) -> *mut bindings::pci_dev {
349         self.0.get()
350     }
351 }
352 
353 impl Device {
354     /// Returns the PCI vendor ID as [`Vendor`].
355     ///
356     /// # Examples
357     ///
358     /// ```
359     /// # use kernel::{device::Core, pci::{self, Vendor}, prelude::*};
360     /// fn log_device_info(pdev: &pci::Device<Core<'_>>) -> Result {
361     ///     // Get an instance of `Vendor`.
362     ///     let vendor = pdev.vendor_id();
363     ///     dev_info!(
364     ///         pdev,
365     ///         "Device: Vendor={}, Device=0x{:x}\n",
366     ///         vendor,
367     ///         pdev.device_id()
368     ///     );
369     ///     Ok(())
370     /// }
371     /// ```
372     #[inline]
373     pub fn vendor_id(&self) -> Vendor {
374         // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
375         let vendor_id = unsafe { (*self.as_raw()).vendor };
376         Vendor::from_raw(vendor_id)
377     }
378 
379     /// Returns the PCI device ID.
380     #[inline]
381     pub fn device_id(&self) -> u16 {
382         // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
383         // `struct pci_dev`.
384         unsafe { (*self.as_raw()).device }
385     }
386 
387     /// Returns the PCI revision ID.
388     #[inline]
389     pub fn revision_id(&self) -> u8 {
390         // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
391         // `struct pci_dev`.
392         unsafe { (*self.as_raw()).revision }
393     }
394 
395     /// Returns the PCI bus device/function.
396     #[inline]
397     pub fn dev_id(&self) -> u16 {
398         // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
399         // `struct pci_dev`.
400         unsafe { bindings::pci_dev_id(self.as_raw()) }
401     }
402 
403     /// Returns the PCI subsystem vendor ID.
404     #[inline]
405     pub fn subsystem_vendor_id(&self) -> u16 {
406         // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
407         // `struct pci_dev`.
408         unsafe { (*self.as_raw()).subsystem_vendor }
409     }
410 
411     /// Returns the PCI subsystem device ID.
412     #[inline]
413     pub fn subsystem_device_id(&self) -> u16 {
414         // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
415         // `struct pci_dev`.
416         unsafe { (*self.as_raw()).subsystem_device }
417     }
418 
419     /// Returns the start of the given PCI BAR resource.
420     pub fn resource_start(&self, bar: u32) -> Result<bindings::resource_size_t> {
421         if !Bar::index_is_valid(bar) {
422             return Err(EINVAL);
423         }
424 
425         // SAFETY:
426         // - `bar` is a valid bar number, as guaranteed by the above call to `Bar::index_is_valid`,
427         // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`.
428         Ok(unsafe { bindings::pci_resource_start(self.as_raw(), bar.try_into()?) })
429     }
430 
431     /// Returns the size of the given PCI BAR resource.
432     pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> {
433         if !Bar::index_is_valid(bar) {
434             return Err(EINVAL);
435         }
436 
437         // SAFETY:
438         // - `bar` is a valid bar number, as guaranteed by the above call to `Bar::index_is_valid`,
439         // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`.
440         Ok(unsafe { bindings::pci_resource_len(self.as_raw(), bar.try_into()?) })
441     }
442 
443     /// Returns the resource flags (`IORESOURCE_*`) of the given PCI BAR.
444     pub fn resource_flags(&self, bar: u32) -> Result<resource::Flags> {
445         if !Bar::index_is_valid(bar) {
446             return Err(EINVAL);
447         }
448 
449         // SAFETY:
450         // - `bar` is a valid bar number, as guaranteed by the above call to `Bar::index_is_valid`,
451         // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`.
452         let raw = unsafe { bindings::pci_resource_flags(self.as_raw(), bar.try_into()?) };
453         Ok(resource::Flags::from_raw(raw))
454     }
455 
456     /// Returns the PCI class as a `Class` struct.
457     #[inline]
458     pub fn pci_class(&self) -> Class {
459         // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
460         Class::from_raw(unsafe { (*self.as_raw()).class })
461     }
462 }
463 
464 impl<'a> Device<device::Core<'a>> {
465     /// Returns the total number of VFs, or [`None`] if SR-IOV is not available.
466     #[inline]
467     pub fn sriov_get_totalvfs(&self) -> Option<NonZero<u16>> {
468         // SAFETY: `self.as_raw()` is a valid pointer to a `struct pci_dev`.
469         let total_vfs = unsafe { bindings::pci_sriov_get_totalvfs(self.as_raw()) };
470 
471         // CAST: The C function returns `unsigned int`, but the value originates
472         // from TotalVFs/driver_max_VFs (which are defined as `u16`), so this cast
473         // cannot truncate.
474         NonZero::new(total_vfs as u16)
475     }
476 
477     /// Enable memory resources for this device.
478     pub fn enable_device_mem(&self) -> Result {
479         // SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
480         to_result(unsafe { bindings::pci_enable_device_mem(self.as_raw()) })
481     }
482 
483     /// Enable bus-mastering for this device.
484     #[inline]
485     pub fn set_master(&self) {
486         // SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
487         unsafe { bindings::pci_set_master(self.as_raw()) };
488     }
489 }
490 
491 // SAFETY: `pci::Device` is a transparent wrapper of `struct pci_dev`.
492 // The offset is guaranteed to point to a valid device field inside `pci::Device`.
493 unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
494     const OFFSET: usize = offset_of!(bindings::pci_dev, dev);
495 }
496 
497 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
498 // argument.
499 kernel::impl_device_context_deref!(unsafe { Device });
500 kernel::impl_device_context_into_aref!(Device);
501 
502 impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
503 
504 // SAFETY: Instances of `Device` are always reference-counted.
505 unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
506     #[inline]
507     fn inc_ref(&self) {
508         // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
509         unsafe { bindings::pci_dev_get(self.as_raw()) };
510     }
511 
512     #[inline]
513     unsafe fn dec_ref(obj: NonNull<Self>) {
514         // SAFETY: The safety requirements guarantee that the refcount is non-zero.
515         unsafe { bindings::pci_dev_put(obj.cast().as_ptr()) }
516     }
517 }
518 
519 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
520     fn as_ref(&self) -> &device::Device<Ctx> {
521         // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
522         // `struct pci_dev`.
523         let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
524 
525         // SAFETY: `dev` points to a valid `struct device`.
526         unsafe { device::Device::from_raw(dev) }
527     }
528 }
529 
530 impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
531     type Error = kernel::error::Error;
532 
533     fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
534         // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
535         // `struct device`.
536         if !unsafe { bindings::dev_is_pci(dev.as_raw()) } {
537             return Err(EINVAL);
538         }
539 
540         // SAFETY: We've just verified that the bus type of `dev` equals `bindings::pci_bus_type`,
541         // hence `dev` must be embedded in a valid `struct pci_dev` as guaranteed by the
542         // corresponding C code.
543         let pdev = unsafe { container_of!(dev.as_raw(), bindings::pci_dev, dev) };
544 
545         // SAFETY: `pdev` is a valid pointer to a `struct pci_dev`.
546         Ok(unsafe { &*pdev.cast() })
547     }
548 }
549 
550 // SAFETY: A `Device` is always reference-counted and can be released from any thread.
551 unsafe impl Send for Device {}
552 
553 // SAFETY: `Device` can be shared among threads because all methods of `Device`
554 // (i.e. `Device<Normal>) are thread safe.
555 unsafe impl Sync for Device {}
556 
557 // SAFETY: Same as `Device<Normal>` -- the underlying `struct pci_dev` is the same;
558 // `Bound` is a zero-sized type-state marker that does not affect thread safety.
559 unsafe impl Sync for Device<device::Bound> {}
560