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, Vendor}; 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. 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`. 194 unsafe 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. 199 unsafe 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. 208 pub 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] 212 macro_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. 259 pub 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)] 303 pub 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. 314 pub struct Bar<const SIZE: usize = 0> { 315 pdev: ARef<Device>, 316 io: IoRaw<SIZE>, 317 num: i32, 318 } 319 320 impl<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 unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) { 375 // SAFETY: 376 // `pdev` is valid by the invariants of `Device`. 377 // `ioptr` is valid by the safety requirements. 378 // `num` is valid by the safety requirements. 379 unsafe { 380 bindings::pci_iounmap(pdev.as_raw(), ioptr as *mut c_void); 381 bindings::pci_release_region(pdev.as_raw(), num); 382 } 383 } 384 385 fn release(&self) { 386 // SAFETY: The safety requirements are guaranteed by the type invariant of `self.pdev`. 387 unsafe { Self::do_release(&self.pdev, self.io.addr(), self.num) }; 388 } 389 } 390 391 impl Bar { 392 #[inline] 393 fn index_is_valid(index: u32) -> bool { 394 // A `struct pci_dev` owns an array of resources with at most `PCI_NUM_RESOURCES` entries. 395 index < bindings::PCI_NUM_RESOURCES 396 } 397 } 398 399 impl<const SIZE: usize> Drop for Bar<SIZE> { 400 fn drop(&mut self) { 401 self.release(); 402 } 403 } 404 405 impl<const SIZE: usize> Deref for Bar<SIZE> { 406 type Target = Io<SIZE>; 407 408 fn deref(&self) -> &Self::Target { 409 // SAFETY: By the type invariant of `Self`, the MMIO range in `self.io` is properly mapped. 410 unsafe { Io::from_raw(&self.io) } 411 } 412 } 413 414 impl<Ctx: device::DeviceContext> Device<Ctx> { 415 #[inline] 416 fn as_raw(&self) -> *mut bindings::pci_dev { 417 self.0.get() 418 } 419 } 420 421 impl Device { 422 /// Returns the PCI vendor ID as [`Vendor`]. 423 /// 424 /// # Examples 425 /// 426 /// ``` 427 /// # use kernel::{device::Core, pci::{self, Vendor}, prelude::*}; 428 /// fn log_device_info(pdev: &pci::Device<Core>) -> Result { 429 /// // Get an instance of `Vendor`. 430 /// let vendor = pdev.vendor_id(); 431 /// dev_info!( 432 /// pdev.as_ref(), 433 /// "Device: Vendor={}, Device=0x{:x}\n", 434 /// vendor, 435 /// pdev.device_id() 436 /// ); 437 /// Ok(()) 438 /// } 439 /// ``` 440 #[inline] 441 pub fn vendor_id(&self) -> Vendor { 442 // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`. 443 let vendor_id = unsafe { (*self.as_raw()).vendor }; 444 Vendor::from_raw(vendor_id) 445 } 446 447 /// Returns the PCI device ID. 448 #[inline] 449 pub fn device_id(&self) -> u16 { 450 // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a 451 // `struct pci_dev`. 452 unsafe { (*self.as_raw()).device } 453 } 454 455 /// Returns the PCI revision ID. 456 #[inline] 457 pub fn revision_id(&self) -> u8 { 458 // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a 459 // `struct pci_dev`. 460 unsafe { (*self.as_raw()).revision } 461 } 462 463 /// Returns the PCI bus device/function. 464 #[inline] 465 pub fn dev_id(&self) -> u16 { 466 // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a 467 // `struct pci_dev`. 468 unsafe { bindings::pci_dev_id(self.as_raw()) } 469 } 470 471 /// Returns the PCI subsystem vendor ID. 472 #[inline] 473 pub fn subsystem_vendor_id(&self) -> u16 { 474 // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a 475 // `struct pci_dev`. 476 unsafe { (*self.as_raw()).subsystem_vendor } 477 } 478 479 /// Returns the PCI subsystem device ID. 480 #[inline] 481 pub fn subsystem_device_id(&self) -> u16 { 482 // SAFETY: By its type invariant `self.as_raw` is always a valid pointer to a 483 // `struct pci_dev`. 484 unsafe { (*self.as_raw()).subsystem_device } 485 } 486 487 /// Returns the start of the given PCI bar resource. 488 pub fn resource_start(&self, bar: u32) -> Result<bindings::resource_size_t> { 489 if !Bar::index_is_valid(bar) { 490 return Err(EINVAL); 491 } 492 493 // SAFETY: 494 // - `bar` is a valid bar number, as guaranteed by the above call to `Bar::index_is_valid`, 495 // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`. 496 Ok(unsafe { bindings::pci_resource_start(self.as_raw(), bar.try_into()?) }) 497 } 498 499 /// Returns the size of the given PCI bar resource. 500 pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> { 501 if !Bar::index_is_valid(bar) { 502 return Err(EINVAL); 503 } 504 505 // SAFETY: 506 // - `bar` is a valid bar number, as guaranteed by the above call to `Bar::index_is_valid`, 507 // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`. 508 Ok(unsafe { bindings::pci_resource_len(self.as_raw(), bar.try_into()?) }) 509 } 510 511 /// Returns the PCI class as a `Class` struct. 512 #[inline] 513 pub fn pci_class(&self) -> Class { 514 // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`. 515 Class::from_raw(unsafe { (*self.as_raw()).class }) 516 } 517 } 518 519 impl Device<device::Bound> { 520 /// Mapps an entire PCI-BAR after performing a region-request on it. I/O operation bound checks 521 /// can be performed on compile time for offsets (plus the requested type size) < SIZE. 522 pub fn iomap_region_sized<'a, const SIZE: usize>( 523 &'a self, 524 bar: u32, 525 name: &'a CStr, 526 ) -> impl PinInit<Devres<Bar<SIZE>>, Error> + 'a { 527 Devres::new(self.as_ref(), Bar::<SIZE>::new(self, bar, name)) 528 } 529 530 /// Mapps an entire PCI-BAR after performing a region-request on it. 531 pub fn iomap_region<'a>( 532 &'a self, 533 bar: u32, 534 name: &'a CStr, 535 ) -> impl PinInit<Devres<Bar>, Error> + 'a { 536 self.iomap_region_sized::<0>(bar, name) 537 } 538 539 /// Returns an [`IrqRequest`] for the IRQ vector at the given index, if any. 540 pub fn irq_vector(&self, index: u32) -> Result<IrqRequest<'_>> { 541 // SAFETY: `self.as_raw` returns a valid pointer to a `struct pci_dev`. 542 let irq = unsafe { crate::bindings::pci_irq_vector(self.as_raw(), index) }; 543 if irq < 0 { 544 return Err(crate::error::Error::from_errno(irq)); 545 } 546 // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self`. 547 Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) }) 548 } 549 550 /// Returns a [`kernel::irq::Registration`] for the IRQ vector at the given 551 /// index. 552 pub fn request_irq<'a, T: crate::irq::Handler + 'static>( 553 &'a self, 554 index: u32, 555 flags: irq::Flags, 556 name: &'static CStr, 557 handler: impl PinInit<T, Error> + 'a, 558 ) -> Result<impl PinInit<irq::Registration<T>, Error> + 'a> { 559 let request = self.irq_vector(index)?; 560 561 Ok(irq::Registration::<T>::new(request, flags, name, handler)) 562 } 563 564 /// Returns a [`kernel::irq::ThreadedRegistration`] for the IRQ vector at 565 /// the given index. 566 pub fn request_threaded_irq<'a, T: crate::irq::ThreadedHandler + 'static>( 567 &'a self, 568 index: u32, 569 flags: irq::Flags, 570 name: &'static CStr, 571 handler: impl PinInit<T, Error> + 'a, 572 ) -> Result<impl PinInit<irq::ThreadedRegistration<T>, Error> + 'a> { 573 let request = self.irq_vector(index)?; 574 575 Ok(irq::ThreadedRegistration::<T>::new( 576 request, flags, name, handler, 577 )) 578 } 579 } 580 581 impl Device<device::Core> { 582 /// Enable memory resources for this device. 583 pub fn enable_device_mem(&self) -> Result { 584 // SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`. 585 to_result(unsafe { bindings::pci_enable_device_mem(self.as_raw()) }) 586 } 587 588 /// Enable bus-mastering for this device. 589 #[inline] 590 pub fn set_master(&self) { 591 // SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`. 592 unsafe { bindings::pci_set_master(self.as_raw()) }; 593 } 594 } 595 596 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic 597 // argument. 598 kernel::impl_device_context_deref!(unsafe { Device }); 599 kernel::impl_device_context_into_aref!(Device); 600 601 impl crate::dma::Device for Device<device::Core> {} 602 603 // SAFETY: Instances of `Device` are always reference-counted. 604 unsafe impl crate::sync::aref::AlwaysRefCounted for Device { 605 fn inc_ref(&self) { 606 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. 607 unsafe { bindings::pci_dev_get(self.as_raw()) }; 608 } 609 610 unsafe fn dec_ref(obj: NonNull<Self>) { 611 // SAFETY: The safety requirements guarantee that the refcount is non-zero. 612 unsafe { bindings::pci_dev_put(obj.cast().as_ptr()) } 613 } 614 } 615 616 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> { 617 fn as_ref(&self) -> &device::Device<Ctx> { 618 // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid 619 // `struct pci_dev`. 620 let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) }; 621 622 // SAFETY: `dev` points to a valid `struct device`. 623 unsafe { device::Device::from_raw(dev) } 624 } 625 } 626 627 impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> { 628 type Error = kernel::error::Error; 629 630 fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> { 631 // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a 632 // `struct device`. 633 if !unsafe { bindings::dev_is_pci(dev.as_raw()) } { 634 return Err(EINVAL); 635 } 636 637 // SAFETY: We've just verified that the bus type of `dev` equals `bindings::pci_bus_type`, 638 // hence `dev` must be embedded in a valid `struct pci_dev` as guaranteed by the 639 // corresponding C code. 640 let pdev = unsafe { container_of!(dev.as_raw(), bindings::pci_dev, dev) }; 641 642 // SAFETY: `pdev` is a valid pointer to a `struct pci_dev`. 643 Ok(unsafe { &*pdev.cast() }) 644 } 645 } 646 647 // SAFETY: A `Device` is always reference-counted and can be released from any thread. 648 unsafe impl Send for Device {} 649 650 // SAFETY: `Device` can be shared among threads because all methods of `Device` 651 // (i.e. `Device<Normal>) are thread safe. 652 unsafe impl Sync for Device {} 653