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