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