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