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