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