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