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