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