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