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