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