kernel/pci.rs
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
7use 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};
25use core::{
26 marker::PhantomData,
27 mem::offset_of,
28 num::NonZero,
29 ptr::{
30 addr_of_mut,
31 NonNull, //
32 },
33};
34
35mod id;
36mod io;
37mod irq;
38
39pub use self::id::{
40 Class,
41 ClassMask,
42 Vendor, //
43};
44pub use self::io::{
45 Bar,
46 ConfigSpace,
47 ConfigSpaceSize,
48 DevresBar,
49 Extended,
50 Normal, //
51};
52pub use self::irq::{
53 IrqType,
54 IrqTypes,
55 IrqVector, //
56};
57
58/// An adapter for the registration of PCI drivers.
59pub 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`.
66unsafe 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.
74unsafe 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.0, 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
100impl<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]
158macro_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)]
169pub struct DeviceId(bindings::pci_device_id);
170
171impl 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`.
234unsafe 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.
239unsafe 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.
244pub 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]
248macro_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.
289pub 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)]
339pub struct Device<Ctx: device::DeviceContext = device::Normal>(
340 Opaque<bindings::pci_dev>,
341 PhantomData<Ctx>,
342);
343
344impl<Ctx: device::DeviceContext> Device<Ctx> {
345 #[inline]
346 fn as_raw(&self) -> *mut bindings::pci_dev {
347 self.0.get()
348 }
349}
350
351impl 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
449impl<'a> Device<device::Core<'a>> {
450 /// Returns the total number of VFs, or [`None`] if SR-IOV is not available.
451 #[inline]
452 pub fn sriov_get_totalvfs(&self) -> Option<NonZero<u16>> {
453 // SAFETY: `self.as_raw()` is a valid pointer to a `struct pci_dev`.
454 let total_vfs = unsafe { bindings::pci_sriov_get_totalvfs(self.as_raw()) };
455
456 // CAST: The C function returns `unsigned int`, but the value originates
457 // from TotalVFs/driver_max_VFs (which are defined as `u16`), so this cast
458 // cannot truncate.
459 NonZero::new(total_vfs as u16)
460 }
461
462 /// Enable memory resources for this device.
463 pub fn enable_device_mem(&self) -> Result {
464 // SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
465 to_result(unsafe { bindings::pci_enable_device_mem(self.as_raw()) })
466 }
467
468 /// Enable bus-mastering for this device.
469 #[inline]
470 pub fn set_master(&self) {
471 // SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
472 unsafe { bindings::pci_set_master(self.as_raw()) };
473 }
474}
475
476// SAFETY: `pci::Device` is a transparent wrapper of `struct pci_dev`.
477// The offset is guaranteed to point to a valid device field inside `pci::Device`.
478unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
479 const OFFSET: usize = offset_of!(bindings::pci_dev, dev);
480}
481
482// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
483// argument.
484kernel::impl_device_context_deref!(unsafe { Device });
485kernel::impl_device_context_into_aref!(Device);
486
487impl<'a> crate::dma::Device<'a> for Device<device::Core<'a>> {}
488
489// SAFETY: Instances of `Device` are always reference-counted.
490unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
491 #[inline]
492 fn inc_ref(&self) {
493 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
494 unsafe { bindings::pci_dev_get(self.as_raw()) };
495 }
496
497 #[inline]
498 unsafe fn dec_ref(obj: NonNull<Self>) {
499 // SAFETY: The safety requirements guarantee that the refcount is non-zero.
500 unsafe { bindings::pci_dev_put(obj.cast().as_ptr()) }
501 }
502}
503
504impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
505 fn as_ref(&self) -> &device::Device<Ctx> {
506 // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
507 // `struct pci_dev`.
508 let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
509
510 // SAFETY: `dev` points to a valid `struct device`.
511 unsafe { device::Device::from_raw(dev) }
512 }
513}
514
515impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
516 type Error = kernel::error::Error;
517
518 fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
519 // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
520 // `struct device`.
521 if !unsafe { bindings::dev_is_pci(dev.as_raw()) } {
522 return Err(EINVAL);
523 }
524
525 // SAFETY: We've just verified that the bus type of `dev` equals `bindings::pci_bus_type`,
526 // hence `dev` must be embedded in a valid `struct pci_dev` as guaranteed by the
527 // corresponding C code.
528 let pdev = unsafe { container_of!(dev.as_raw(), bindings::pci_dev, dev) };
529
530 // SAFETY: `pdev` is a valid pointer to a `struct pci_dev`.
531 Ok(unsafe { &*pdev.cast() })
532 }
533}
534
535// SAFETY: A `Device` is always reference-counted and can be released from any thread.
536unsafe impl Send for Device {}
537
538// SAFETY: `Device` can be shared among threads because all methods of `Device`
539// (i.e. `Device<Normal>) are thread safe.
540unsafe impl Sync for Device {}
541
542// SAFETY: Same as `Device<Normal>` -- the underlying `struct pci_dev` is the same;
543// `Bound` is a zero-sized type-state marker that does not affect thread safety.
544unsafe impl Sync for Device<device::Bound> {}