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