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