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