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    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};
20use core::{
21    marker::PhantomData,
22    ops::Deref,
23    ptr::{addr_of_mut, NonNull},
24};
25use kernel::prelude::*;
26use safety_macro::safety;
27mod id;
28
29pub use self::id::{Class, ClassMask, Vendor};
30
31/// An adapter for the registration of PCI drivers.
32pub 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.
36unsafe 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
64impl<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]
118macro_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)]
129pub struct DeviceId(bindings::pci_device_id);
130
131impl 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.
137    #[inline]
138    pub const fn from_id(vendor: Vendor, device: u32) -> Self {
139        Self(bindings::pci_device_id {
140            vendor: vendor.as_raw() as u32,
141            device,
142            subvendor: DeviceId::PCI_ANY_ID,
143            subdevice: DeviceId::PCI_ANY_ID,
144            class: 0,
145            class_mask: 0,
146            driver_data: 0,
147            override_only: 0,
148        })
149    }
150
151    /// Equivalent to C's `PCI_DEVICE_CLASS` macro.
152    ///
153    /// Create a new `pci::DeviceId` from a class number and mask.
154    #[inline]
155    pub const fn from_class(class: u32, class_mask: u32) -> Self {
156        Self(bindings::pci_device_id {
157            vendor: DeviceId::PCI_ANY_ID,
158            device: DeviceId::PCI_ANY_ID,
159            subvendor: DeviceId::PCI_ANY_ID,
160            subdevice: DeviceId::PCI_ANY_ID,
161            class,
162            class_mask,
163            driver_data: 0,
164            override_only: 0,
165        })
166    }
167
168    /// Create a new [`DeviceId`] from a class number, mask, and specific vendor.
169    ///
170    /// This is more targeted than [`DeviceId::from_class`]: in addition to matching by [`Vendor`],
171    /// it also matches the PCI [`Class`] (up to the entire 24 bits, depending on the
172    /// [`ClassMask`]).
173    #[inline]
174    pub const fn from_class_and_vendor(
175        class: Class,
176        class_mask: ClassMask,
177        vendor: Vendor,
178    ) -> Self {
179        Self(bindings::pci_device_id {
180            vendor: vendor.as_raw() as u32,
181            device: DeviceId::PCI_ANY_ID,
182            subvendor: DeviceId::PCI_ANY_ID,
183            subdevice: DeviceId::PCI_ANY_ID,
184            class: class.as_raw(),
185            class_mask: class_mask.as_raw(),
186            driver_data: 0,
187            override_only: 0,
188        })
189    }
190}
191
192// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `pci_device_id` and does not add
193// additional invariants, so it's safe to transmute to `RawType`.
194unsafe impl RawDeviceId for DeviceId {
195    type RawType = bindings::pci_device_id;
196}
197
198// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field.
199unsafe impl RawDeviceIdIndex for DeviceId {
200    const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::pci_device_id, driver_data);
201
202    fn index(&self) -> usize {
203        self.0.driver_data
204    }
205}
206
207/// `IdTable` type for PCI.
208pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>;
209
210/// Create a PCI `IdTable` with its alias for modpost.
211#[macro_export]
212macro_rules! pci_device_table {
213    ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => {
214        const $table_name: $crate::device_id::IdArray<
215            $crate::pci::DeviceId,
216            $id_info_type,
217            { $table_data.len() },
218        > = $crate::device_id::IdArray::new($table_data);
219
220        $crate::module_device_table!("pci", $module_table_name, $table_name);
221    };
222}
223
224/// The PCI driver trait.
225///
226/// # Examples
227///
228///```
229/// # use kernel::{bindings, device::Core, pci};
230///
231/// struct MyDriver;
232///
233/// kernel::pci_device_table!(
234///     PCI_TABLE,
235///     MODULE_PCI_TABLE,
236///     <MyDriver as pci::Driver>::IdInfo,
237///     [
238///         (
239///             pci::DeviceId::from_id(pci::Vendor::REDHAT, bindings::PCI_ANY_ID as u32),
240///             (),
241///         )
242///     ]
243/// );
244///
245/// impl pci::Driver for MyDriver {
246///     type IdInfo = ();
247///     const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE;
248///
249///     fn probe(
250///         _pdev: &pci::Device<Core>,
251///         _id_info: &Self::IdInfo,
252///     ) -> Result<Pin<KBox<Self>>> {
253///         Err(ENODEV)
254///     }
255/// }
256///```
257/// Drivers must implement this trait in order to get a PCI driver registered. Please refer to the
258/// `Adapter` documentation for an example.
259pub trait Driver: Send {
260    /// The type holding information about each device id supported by the driver.
261    // TODO: Use `associated_type_defaults` once stabilized:
262    //
263    // ```
264    // type IdInfo: 'static = ();
265    // ```
266    type IdInfo: 'static;
267
268    /// The table of device ids supported by the driver.
269    const ID_TABLE: IdTable<Self::IdInfo>;
270
271    /// PCI driver probe.
272    ///
273    /// Called when a new pci device is added or discovered. Implementers should
274    /// attempt to initialize the device here.
275    fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo) -> Result<Pin<KBox<Self>>>;
276
277    /// PCI driver unbind.
278    ///
279    /// Called when a [`Device`] is unbound from its bound [`Driver`]. Implementing this callback
280    /// is optional.
281    ///
282    /// This callback serves as a place for drivers to perform teardown operations that require a
283    /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O
284    /// operations to gracefully tear down the device.
285    ///
286    /// Otherwise, release operations for driver resources should be performed in `Self::drop`.
287    fn unbind(dev: &Device<device::Core>, this: Pin<&Self>) {
288        let _ = (dev, this);
289    }
290}
291
292/// The PCI device representation.
293///
294/// This structure represents the Rust abstraction for a C `struct pci_dev`. The implementation
295/// abstracts the usage of an already existing C `struct pci_dev` within Rust code that we get
296/// passed from the C side.
297///
298/// # Invariants
299///
300/// A [`Device`] instance represents a valid `struct pci_dev` created by the C portion of the
301/// kernel.
302#[repr(transparent)]
303pub struct Device<Ctx: device::DeviceContext = device::Normal>(
304    Opaque<bindings::pci_dev>,
305    PhantomData<Ctx>,
306);
307
308/// A PCI BAR to perform I/O-Operations on.
309///
310/// # Invariants
311///
312/// `Bar` always holds an `IoRaw` inststance that holds a valid pointer to the start of the I/O
313/// memory mapped PCI bar and its size.
314pub struct Bar<const SIZE: usize = 0> {
315    pdev: ARef<Device>,
316    io: IoRaw<SIZE>,
317    num: i32,
318}
319
320impl<const SIZE: usize> Bar<SIZE> {
321    fn new(pdev: &Device, num: u32, name: &CStr) -> Result<Self> {
322        let len = pdev.resource_len(num)?;
323        if len == 0 {
324            return Err(ENOMEM);
325        }
326
327        // Convert to `i32`, since that's what all the C bindings use.
328        let num = i32::try_from(num)?;
329
330        // SAFETY:
331        // `pdev` is valid by the invariants of `Device`.
332        // `num` is checked for validity by a previous call to `Device::resource_len`.
333        // `name` is always valid.
334        let ret = unsafe { bindings::pci_request_region(pdev.as_raw(), num, name.as_char_ptr()) };
335        if ret != 0 {
336            return Err(EBUSY);
337        }
338
339        // SAFETY:
340        // `pdev` is valid by the invariants of `Device`.
341        // `num` is checked for validity by a previous call to `Device::resource_len`.
342        // `name` is always valid.
343        let ioptr: usize = unsafe { bindings::pci_iomap(pdev.as_raw(), num, 0) } as usize;
344        if ioptr == 0 {
345            // SAFETY:
346            // `pdev` valid by the invariants of `Device`.
347            // `num` is checked for validity by a previous call to `Device::resource_len`.
348            unsafe { bindings::pci_release_region(pdev.as_raw(), num) };
349            return Err(ENOMEM);
350        }
351
352        let io = match IoRaw::new(ioptr, len as usize) {
353            Ok(io) => io,
354            Err(err) => {
355                // SAFETY:
356                // `pdev` is valid by the invariants of `Device`.
357                // `ioptr` is guaranteed to be the start of a valid I/O mapped memory region.
358                // `num` is checked for validity by a previous call to `Device::resource_len`.
359                unsafe { Self::do_release(pdev, ioptr, num) };
360                return Err(err);
361            }
362        };
363
364        Ok(Bar {
365            pdev: pdev.into(),
366            io,
367            num,
368        })
369    }
370
371    /// # Safety
372    ///
373    /// `ioptr` must be a valid pointer to the memory mapped PCI bar number `num`.
374    #[safety{ValidPtr}]
375    unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) {
376        // SAFETY:
377        // `pdev` is valid by the invariants of `Device`.
378        // `ioptr` is valid by the safety requirements.
379        // `num` is valid by the safety requirements.
380        unsafe {
381            bindings::pci_iounmap(pdev.as_raw(), ioptr as *mut c_void);
382            bindings::pci_release_region(pdev.as_raw(), num);
383        }
384    }
385
386    fn release(&self) {
387        // SAFETY: The safety requirements are guaranteed by the type invariant of `self.pdev`.
388        unsafe { Self::do_release(&self.pdev, self.io.addr(), self.num) };
389    }
390}
391
392impl Bar {
393    #[inline]
394    fn index_is_valid(index: u32) -> bool {
395        // A `struct pci_dev` owns an array of resources with at most `PCI_NUM_RESOURCES` entries.
396        index < bindings::PCI_NUM_RESOURCES
397    }
398}
399
400impl<const SIZE: usize> Drop for Bar<SIZE> {
401    fn drop(&mut self) {
402        self.release();
403    }
404}
405
406impl<const SIZE: usize> Deref for Bar<SIZE> {
407    type Target = Io<SIZE>;
408
409    fn deref(&self) -> &Self::Target {
410        // SAFETY: By the type invariant of `Self`, the MMIO range in `self.io` is properly mapped.
411        unsafe { Io::from_raw(&self.io) }
412    }
413}
414
415impl<Ctx: device::DeviceContext> Device<Ctx> {
416    #[inline]
417    fn as_raw(&self) -> *mut bindings::pci_dev {
418        self.0.get()
419    }
420}
421
422impl Device {
423    /// Returns the PCI vendor ID as [`Vendor`].
424    ///
425    /// # Examples
426    ///
427    /// ```
428    /// # use kernel::{device::Core, pci::{self, Vendor}, prelude::*};
429    /// fn log_device_info(pdev: &pci::Device<Core>) -> Result {
430    ///     // Get an instance of `Vendor`.
431    ///     let vendor = pdev.vendor_id();
432    ///     dev_info!(
433    ///         pdev.as_ref(),
434    ///         "Device: Vendor={}, Device=0x{:x}\n",
435    ///         vendor,
436    ///         pdev.device_id()
437    ///     );
438    ///     Ok(())
439    /// }
440    /// ```
441    #[inline]
442    pub fn vendor_id(&self) -> Vendor {
443        // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
444        let vendor_id = unsafe { (*self.as_raw()).vendor };
445        Vendor::from_raw(vendor_id)
446    }
447
448    /// Returns the PCI device ID.
449    #[inline]
450    pub fn device_id(&self) -> u16 {
451        // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
452        // `struct pci_dev`.
453        unsafe { (*self.as_raw()).device }
454    }
455
456    /// Returns the PCI revision ID.
457    #[inline]
458    pub fn revision_id(&self) -> u8 {
459        // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
460        // `struct pci_dev`.
461        unsafe { (*self.as_raw()).revision }
462    }
463
464    /// Returns the PCI bus device/function.
465    #[inline]
466    pub fn dev_id(&self) -> u16 {
467        // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
468        // `struct pci_dev`.
469        unsafe { bindings::pci_dev_id(self.as_raw()) }
470    }
471
472    /// Returns the PCI subsystem vendor ID.
473    #[inline]
474    pub fn subsystem_vendor_id(&self) -> u16 {
475        // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
476        // `struct pci_dev`.
477        unsafe { (*self.as_raw()).subsystem_vendor }
478    }
479
480    /// Returns the PCI subsystem device ID.
481    #[inline]
482    pub fn subsystem_device_id(&self) -> u16 {
483        // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a
484        // `struct pci_dev`.
485        unsafe { (*self.as_raw()).subsystem_device }
486    }
487
488    /// Returns the start of the given PCI bar resource.
489    pub fn resource_start(&self, bar: u32) -> Result<bindings::resource_size_t> {
490        if !Bar::index_is_valid(bar) {
491            return Err(EINVAL);
492        }
493
494        // SAFETY:
495        // - `bar` is a valid bar number, as guaranteed by the above call to `Bar::index_is_valid`,
496        // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`.
497        Ok(unsafe { bindings::pci_resource_start(self.as_raw(), bar.try_into()?) })
498    }
499
500    /// Returns the size of the given PCI bar resource.
501    pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> {
502        if !Bar::index_is_valid(bar) {
503            return Err(EINVAL);
504        }
505
506        // SAFETY:
507        // - `bar` is a valid bar number, as guaranteed by the above call to `Bar::index_is_valid`,
508        // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`.
509        Ok(unsafe { bindings::pci_resource_len(self.as_raw(), bar.try_into()?) })
510    }
511
512    /// Returns the PCI class as a `Class` struct.
513    #[inline]
514    pub fn pci_class(&self) -> Class {
515        // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
516        Class::from_raw(unsafe { (*self.as_raw()).class })
517    }
518}
519
520impl Device<device::Bound> {
521    /// Mapps an entire PCI-BAR after performing a region-request on it. I/O operation bound checks
522    /// can be performed on compile time for offsets (plus the requested type size) < SIZE.
523    pub fn iomap_region_sized<'a, const SIZE: usize>(
524        &'a self,
525        bar: u32,
526        name: &'a CStr,
527    ) -> impl PinInit<Devres<Bar<SIZE>>, Error> + 'a {
528        Devres::new(self.as_ref(), Bar::<SIZE>::new(self, bar, name))
529    }
530
531    /// Mapps an entire PCI-BAR after performing a region-request on it.
532    pub fn iomap_region<'a>(
533        &'a self,
534        bar: u32,
535        name: &'a CStr,
536    ) -> impl PinInit<Devres<Bar>, Error> + 'a {
537        self.iomap_region_sized::<0>(bar, name)
538    }
539
540    /// Returns an [`IrqRequest`] for the IRQ vector at the given index, if any.
541    pub fn irq_vector(&self, index: u32) -> Result<IrqRequest<'_>> {
542        // SAFETY: `self.as_raw` returns a valid pointer to a `struct pci_dev`.
543        let irq = unsafe { crate::bindings::pci_irq_vector(self.as_raw(), index) };
544        if irq < 0 {
545            return Err(crate::error::Error::from_errno(irq));
546        }
547        // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`.
548        Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) })
549    }
550
551    /// Returns a [`kernel::irq::Registration`] for the IRQ vector at the given
552    /// index.
553    pub fn request_irq<'a, T: crate::irq::Handler + 'static>(
554        &'a self,
555        index: u32,
556        flags: irq::Flags,
557        name: &'static CStr,
558        handler: impl PinInit<T, Error> + 'a,
559    ) -> Result<impl PinInit<irq::Registration<T>, Error> + 'a> {
560        let request = self.irq_vector(index)?;
561
562        Ok(irq::Registration::<T>::new(request, flags, name, handler))
563    }
564
565    /// Returns a [`kernel::irq::ThreadedRegistration`] for the IRQ vector at
566    /// the given index.
567    pub fn request_threaded_irq<'a, T: crate::irq::ThreadedHandler + 'static>(
568        &'a self,
569        index: u32,
570        flags: irq::Flags,
571        name: &'static CStr,
572        handler: impl PinInit<T, Error> + 'a,
573    ) -> Result<impl PinInit<irq::ThreadedRegistration<T>, Error> + 'a> {
574        let request = self.irq_vector(index)?;
575
576        Ok(irq::ThreadedRegistration::<T>::new(
577            request, flags, name, handler,
578        ))
579    }
580}
581
582impl Device<device::Core> {
583    /// Enable memory resources for this device.
584    pub fn enable_device_mem(&self) -> Result {
585        // SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
586        to_result(unsafe { bindings::pci_enable_device_mem(self.as_raw()) })
587    }
588
589    /// Enable bus-mastering for this device.
590    #[inline]
591    pub fn set_master(&self) {
592        // SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
593        unsafe { bindings::pci_set_master(self.as_raw()) };
594    }
595}
596
597// SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic
598// argument.
599kernel::impl_device_context_deref!(unsafe { Device });
600kernel::impl_device_context_into_aref!(Device);
601
602impl crate::dma::Device for Device<device::Core> {}
603
604// SAFETY: Instances of `Device` are always reference-counted.
605unsafe impl crate::sync::aref::AlwaysRefCounted for Device {
606    fn inc_ref(&self) {
607        // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero.
608        unsafe { bindings::pci_dev_get(self.as_raw()) };
609    }
610
611    unsafe fn dec_ref(obj: NonNull<Self>) {
612        // SAFETY: The safety requirements guarantee that the refcount is non-zero.
613        unsafe { bindings::pci_dev_put(obj.cast().as_ptr()) }
614    }
615}
616
617impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
618    fn as_ref(&self) -> &device::Device<Ctx> {
619        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
620        // `struct pci_dev`.
621        let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) };
622
623        // SAFETY: `dev` points to a valid `struct device`.
624        unsafe { device::Device::from_raw(dev) }
625    }
626}
627
628impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> {
629    type Error = kernel::error::Error;
630
631    fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> {
632        // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a
633        // `struct device`.
634        if !unsafe { bindings::dev_is_pci(dev.as_raw()) } {
635            return Err(EINVAL);
636        }
637
638        // SAFETY: We've just verified that the bus type of `dev` equals `bindings::pci_bus_type`,
639        // hence `dev` must be embedded in a valid `struct pci_dev` as guaranteed by the
640        // corresponding C code.
641        let pdev = unsafe { container_of!(dev.as_raw(), bindings::pci_dev, dev) };
642
643        // SAFETY: `pdev` is a valid pointer to a `struct pci_dev`.
644        Ok(unsafe { &*pdev.cast() })
645    }
646}
647
648// SAFETY: A `Device` is always reference-counted and can be released from any thread.
649unsafe impl Send for Device {}
650
651// SAFETY: `Device` can be shared among threads because all methods of `Device`
652// (i.e. `Device<Normal>) are thread safe.
653unsafe impl Sync for Device {}