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