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, 10 devres::Devres, 11 driver, 12 error::{from_result, to_result, Result}, 13 io::Io, 14 io::IoRaw, 15 str::CStr, 16 types::{ARef, Opaque}, 17 ThisModule, 18 }; 19 use core::{ 20 marker::PhantomData, 21 ops::Deref, 22 ptr::{addr_of_mut, NonNull}, 23 }; 24 use kernel::prelude::*; 25 26 /// An adapter for the registration of PCI drivers. 27 pub struct Adapter<T: Driver>(T); 28 29 // SAFETY: A call to `unregister` for a given instance of `RegType` is guaranteed to be valid if 30 // a preceding call to `register` has been successful. 31 unsafe impl<T: Driver + 'static> driver::RegistrationOps for Adapter<T> { 32 type RegType = bindings::pci_driver; 33 34 unsafe fn register( 35 pdrv: &Opaque<Self::RegType>, 36 name: &'static CStr, 37 module: &'static ThisModule, 38 ) -> Result { 39 // SAFETY: It's safe to set the fields of `struct pci_driver` on initialization. 40 unsafe { 41 (*pdrv.get()).name = name.as_char_ptr(); 42 (*pdrv.get()).probe = Some(Self::probe_callback); 43 (*pdrv.get()).remove = Some(Self::remove_callback); 44 (*pdrv.get()).id_table = T::ID_TABLE.as_ptr(); 45 } 46 47 // SAFETY: `pdrv` is guaranteed to be a valid `RegType`. 48 to_result(unsafe { 49 bindings::__pci_register_driver(pdrv.get(), module.0, name.as_char_ptr()) 50 }) 51 } 52 53 unsafe fn unregister(pdrv: &Opaque<Self::RegType>) { 54 // SAFETY: `pdrv` is guaranteed to be a valid `RegType`. 55 unsafe { bindings::pci_unregister_driver(pdrv.get()) } 56 } 57 } 58 59 impl<T: Driver + 'static> Adapter<T> { 60 extern "C" fn probe_callback( 61 pdev: *mut bindings::pci_dev, 62 id: *const bindings::pci_device_id, 63 ) -> kernel::ffi::c_int { 64 // SAFETY: The PCI bus only ever calls the probe callback with a valid pointer to a 65 // `struct pci_dev`. 66 // 67 // INVARIANT: `pdev` is valid for the duration of `probe_callback()`. 68 let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal>>() }; 69 70 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `struct pci_device_id` and 71 // does not add additional invariants, so it's safe to transmute. 72 let id = unsafe { &*id.cast::<DeviceId>() }; 73 let info = T::ID_TABLE.info(id.index()); 74 75 from_result(|| { 76 let data = T::probe(pdev, info)?; 77 78 pdev.as_ref().set_drvdata(data); 79 Ok(0) 80 }) 81 } 82 83 extern "C" fn remove_callback(pdev: *mut bindings::pci_dev) { 84 // SAFETY: The PCI bus only ever calls the remove callback with a valid pointer to a 85 // `struct pci_dev`. 86 // 87 // INVARIANT: `pdev` is valid for the duration of `remove_callback()`. 88 let pdev = unsafe { &*pdev.cast::<Device<device::CoreInternal>>() }; 89 90 // SAFETY: `remove_callback` is only ever called after a successful call to 91 // `probe_callback`, hence it's guaranteed that `Device::set_drvdata()` has been called 92 // and stored a `Pin<KBox<T>>`. 93 let _ = unsafe { pdev.as_ref().drvdata_obtain::<Pin<KBox<T>>>() }; 94 } 95 } 96 97 /// Declares a kernel module that exposes a single PCI driver. 98 /// 99 /// # Example 100 /// 101 ///```ignore 102 /// kernel::module_pci_driver! { 103 /// type: MyDriver, 104 /// name: "Module name", 105 /// authors: ["Author name"], 106 /// description: "Description", 107 /// license: "GPL v2", 108 /// } 109 ///``` 110 #[macro_export] 111 macro_rules! module_pci_driver { 112 ($($f:tt)*) => { 113 $crate::module_driver!(<T>, $crate::pci::Adapter<T>, { $($f)* }); 114 }; 115 } 116 117 /// Abstraction for the PCI device ID structure ([`struct pci_device_id`]). 118 /// 119 /// [`struct pci_device_id`]: https://docs.kernel.org/PCI/pci.html#c.pci_device_id 120 #[repr(transparent)] 121 #[derive(Clone, Copy)] 122 pub struct DeviceId(bindings::pci_device_id); 123 124 impl DeviceId { 125 const PCI_ANY_ID: u32 = !0; 126 127 /// Equivalent to C's `PCI_DEVICE` macro. 128 /// 129 /// Create a new `pci::DeviceId` from a vendor and device ID number. 130 pub const fn from_id(vendor: u32, device: u32) -> Self { 131 Self(bindings::pci_device_id { 132 vendor, 133 device, 134 subvendor: DeviceId::PCI_ANY_ID, 135 subdevice: DeviceId::PCI_ANY_ID, 136 class: 0, 137 class_mask: 0, 138 driver_data: 0, 139 override_only: 0, 140 }) 141 } 142 143 /// Equivalent to C's `PCI_DEVICE_CLASS` macro. 144 /// 145 /// Create a new `pci::DeviceId` from a class number and mask. 146 pub const fn from_class(class: u32, class_mask: u32) -> Self { 147 Self(bindings::pci_device_id { 148 vendor: DeviceId::PCI_ANY_ID, 149 device: DeviceId::PCI_ANY_ID, 150 subvendor: DeviceId::PCI_ANY_ID, 151 subdevice: DeviceId::PCI_ANY_ID, 152 class, 153 class_mask, 154 driver_data: 0, 155 override_only: 0, 156 }) 157 } 158 } 159 160 // SAFETY: 161 // * `DeviceId` is a `#[repr(transparent)]` wrapper of `pci_device_id` and does not add 162 // additional invariants, so it's safe to transmute to `RawType`. 163 // * `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field. 164 unsafe impl RawDeviceId for DeviceId { 165 type RawType = bindings::pci_device_id; 166 167 const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::pci_device_id, driver_data); 168 169 fn index(&self) -> usize { 170 self.0.driver_data as _ 171 } 172 } 173 174 /// `IdTable` type for PCI. 175 pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>; 176 177 /// Create a PCI `IdTable` with its alias for modpost. 178 #[macro_export] 179 macro_rules! pci_device_table { 180 ($table_name:ident, $module_table_name:ident, $id_info_type: ty, $table_data: expr) => { 181 const $table_name: $crate::device_id::IdArray< 182 $crate::pci::DeviceId, 183 $id_info_type, 184 { $table_data.len() }, 185 > = $crate::device_id::IdArray::new($table_data); 186 187 $crate::module_device_table!("pci", $module_table_name, $table_name); 188 }; 189 } 190 191 /// The PCI driver trait. 192 /// 193 /// # Example 194 /// 195 ///``` 196 /// # use kernel::{bindings, device::Core, pci}; 197 /// 198 /// struct MyDriver; 199 /// 200 /// kernel::pci_device_table!( 201 /// PCI_TABLE, 202 /// MODULE_PCI_TABLE, 203 /// <MyDriver as pci::Driver>::IdInfo, 204 /// [ 205 /// (pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, bindings::PCI_ANY_ID as _), ()) 206 /// ] 207 /// ); 208 /// 209 /// impl pci::Driver for MyDriver { 210 /// type IdInfo = (); 211 /// const ID_TABLE: pci::IdTable<Self::IdInfo> = &PCI_TABLE; 212 /// 213 /// fn probe( 214 /// _pdev: &pci::Device<Core>, 215 /// _id_info: &Self::IdInfo, 216 /// ) -> Result<Pin<KBox<Self>>> { 217 /// Err(ENODEV) 218 /// } 219 /// } 220 ///``` 221 /// Drivers must implement this trait in order to get a PCI driver registered. Please refer to the 222 /// `Adapter` documentation for an example. 223 pub trait Driver: Send { 224 /// The type holding information about each device id supported by the driver. 225 // TODO: Use `associated_type_defaults` once stabilized: 226 // 227 // ``` 228 // type IdInfo: 'static = (); 229 // ``` 230 type IdInfo: 'static; 231 232 /// The table of device ids supported by the driver. 233 const ID_TABLE: IdTable<Self::IdInfo>; 234 235 /// PCI driver probe. 236 /// 237 /// Called when a new platform device is added or discovered. 238 /// Implementers should attempt to initialize the device here. 239 fn probe(dev: &Device<device::Core>, id_info: &Self::IdInfo) -> Result<Pin<KBox<Self>>>; 240 } 241 242 /// The PCI device representation. 243 /// 244 /// This structure represents the Rust abstraction for a C `struct pci_dev`. The implementation 245 /// abstracts the usage of an already existing C `struct pci_dev` within Rust code that we get 246 /// passed from the C side. 247 /// 248 /// # Invariants 249 /// 250 /// A [`Device`] instance represents a valid `struct pci_dev` created by the C portion of the 251 /// kernel. 252 #[repr(transparent)] 253 pub struct Device<Ctx: device::DeviceContext = device::Normal>( 254 Opaque<bindings::pci_dev>, 255 PhantomData<Ctx>, 256 ); 257 258 /// A PCI BAR to perform I/O-Operations on. 259 /// 260 /// # Invariants 261 /// 262 /// `Bar` always holds an `IoRaw` inststance that holds a valid pointer to the start of the I/O 263 /// memory mapped PCI bar and its size. 264 pub struct Bar<const SIZE: usize = 0> { 265 pdev: ARef<Device>, 266 io: IoRaw<SIZE>, 267 num: i32, 268 } 269 270 impl<const SIZE: usize> Bar<SIZE> { 271 fn new(pdev: &Device, num: u32, name: &CStr) -> Result<Self> { 272 let len = pdev.resource_len(num)?; 273 if len == 0 { 274 return Err(ENOMEM); 275 } 276 277 // Convert to `i32`, since that's what all the C bindings use. 278 let num = i32::try_from(num)?; 279 280 // SAFETY: 281 // `pdev` is valid by the invariants of `Device`. 282 // `num` is checked for validity by a previous call to `Device::resource_len`. 283 // `name` is always valid. 284 let ret = unsafe { bindings::pci_request_region(pdev.as_raw(), num, name.as_char_ptr()) }; 285 if ret != 0 { 286 return Err(EBUSY); 287 } 288 289 // SAFETY: 290 // `pdev` is valid by the invariants of `Device`. 291 // `num` is checked for validity by a previous call to `Device::resource_len`. 292 // `name` is always valid. 293 let ioptr: usize = unsafe { bindings::pci_iomap(pdev.as_raw(), num, 0) } as usize; 294 if ioptr == 0 { 295 // SAFETY: 296 // `pdev` valid by the invariants of `Device`. 297 // `num` is checked for validity by a previous call to `Device::resource_len`. 298 unsafe { bindings::pci_release_region(pdev.as_raw(), num) }; 299 return Err(ENOMEM); 300 } 301 302 let io = match IoRaw::new(ioptr, len as usize) { 303 Ok(io) => io, 304 Err(err) => { 305 // SAFETY: 306 // `pdev` is valid by the invariants of `Device`. 307 // `ioptr` is guaranteed to be the start of a valid I/O mapped memory region. 308 // `num` is checked for validity by a previous call to `Device::resource_len`. 309 unsafe { Self::do_release(pdev, ioptr, num) }; 310 return Err(err); 311 } 312 }; 313 314 Ok(Bar { 315 pdev: pdev.into(), 316 io, 317 num, 318 }) 319 } 320 321 /// # Safety 322 /// 323 /// `ioptr` must be a valid pointer to the memory mapped PCI bar number `num`. 324 unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) { 325 // SAFETY: 326 // `pdev` is valid by the invariants of `Device`. 327 // `ioptr` is valid by the safety requirements. 328 // `num` is valid by the safety requirements. 329 unsafe { 330 bindings::pci_iounmap(pdev.as_raw(), ioptr as _); 331 bindings::pci_release_region(pdev.as_raw(), num); 332 } 333 } 334 335 fn release(&self) { 336 // SAFETY: The safety requirements are guaranteed by the type invariant of `self.pdev`. 337 unsafe { Self::do_release(&self.pdev, self.io.addr(), self.num) }; 338 } 339 } 340 341 impl Bar { 342 fn index_is_valid(index: u32) -> bool { 343 // A `struct pci_dev` owns an array of resources with at most `PCI_NUM_RESOURCES` entries. 344 index < bindings::PCI_NUM_RESOURCES 345 } 346 } 347 348 impl<const SIZE: usize> Drop for Bar<SIZE> { 349 fn drop(&mut self) { 350 self.release(); 351 } 352 } 353 354 impl<const SIZE: usize> Deref for Bar<SIZE> { 355 type Target = Io<SIZE>; 356 357 fn deref(&self) -> &Self::Target { 358 // SAFETY: By the type invariant of `Self`, the MMIO range in `self.io` is properly mapped. 359 unsafe { Io::from_raw(&self.io) } 360 } 361 } 362 363 impl<Ctx: device::DeviceContext> Device<Ctx> { 364 fn as_raw(&self) -> *mut bindings::pci_dev { 365 self.0.get() 366 } 367 } 368 369 impl Device { 370 /// Returns the PCI vendor ID. 371 pub fn vendor_id(&self) -> u16 { 372 // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`. 373 unsafe { (*self.as_raw()).vendor } 374 } 375 376 /// Returns the PCI device ID. 377 pub fn device_id(&self) -> u16 { 378 // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`. 379 unsafe { (*self.as_raw()).device } 380 } 381 382 /// Returns the size of the given PCI bar resource. 383 pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> { 384 if !Bar::index_is_valid(bar) { 385 return Err(EINVAL); 386 } 387 388 // SAFETY: 389 // - `bar` is a valid bar number, as guaranteed by the above call to `Bar::index_is_valid`, 390 // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`. 391 Ok(unsafe { bindings::pci_resource_len(self.as_raw(), bar.try_into()?) }) 392 } 393 } 394 395 impl Device<device::Bound> { 396 /// Mapps an entire PCI-BAR after performing a region-request on it. I/O operation bound checks 397 /// can be performed on compile time for offsets (plus the requested type size) < SIZE. 398 pub fn iomap_region_sized<'a, const SIZE: usize>( 399 &'a self, 400 bar: u32, 401 name: &'a CStr, 402 ) -> impl PinInit<Devres<Bar<SIZE>>, Error> + 'a { 403 Devres::new(self.as_ref(), Bar::<SIZE>::new(self, bar, name)) 404 } 405 406 /// Mapps an entire PCI-BAR after performing a region-request on it. 407 pub fn iomap_region<'a>( 408 &'a self, 409 bar: u32, 410 name: &'a CStr, 411 ) -> impl PinInit<Devres<Bar>, Error> + 'a { 412 self.iomap_region_sized::<0>(bar, name) 413 } 414 } 415 416 impl Device<device::Core> { 417 /// Enable memory resources for this device. 418 pub fn enable_device_mem(&self) -> Result { 419 // SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`. 420 to_result(unsafe { bindings::pci_enable_device_mem(self.as_raw()) }) 421 } 422 423 /// Enable bus-mastering for this device. 424 pub fn set_master(&self) { 425 // SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`. 426 unsafe { bindings::pci_set_master(self.as_raw()) }; 427 } 428 } 429 430 // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend on `Device`'s generic 431 // argument. 432 kernel::impl_device_context_deref!(unsafe { Device }); 433 kernel::impl_device_context_into_aref!(Device); 434 435 // SAFETY: Instances of `Device` are always reference-counted. 436 unsafe impl crate::types::AlwaysRefCounted for Device { 437 fn inc_ref(&self) { 438 // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. 439 unsafe { bindings::pci_dev_get(self.as_raw()) }; 440 } 441 442 unsafe fn dec_ref(obj: NonNull<Self>) { 443 // SAFETY: The safety requirements guarantee that the refcount is non-zero. 444 unsafe { bindings::pci_dev_put(obj.cast().as_ptr()) } 445 } 446 } 447 448 impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> { 449 fn as_ref(&self) -> &device::Device<Ctx> { 450 // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid 451 // `struct pci_dev`. 452 let dev = unsafe { addr_of_mut!((*self.as_raw()).dev) }; 453 454 // SAFETY: `dev` points to a valid `struct device`. 455 unsafe { device::Device::as_ref(dev) } 456 } 457 } 458 459 impl<Ctx: device::DeviceContext> TryFrom<&device::Device<Ctx>> for &Device<Ctx> { 460 type Error = kernel::error::Error; 461 462 fn try_from(dev: &device::Device<Ctx>) -> Result<Self, Self::Error> { 463 // SAFETY: By the type invariant of `Device`, `dev.as_raw()` is a valid pointer to a 464 // `struct device`. 465 if !unsafe { bindings::dev_is_pci(dev.as_raw()) } { 466 return Err(EINVAL); 467 } 468 469 // SAFETY: We've just verified that the bus type of `dev` equals `bindings::pci_bus_type`, 470 // hence `dev` must be embedded in a valid `struct pci_dev` as guaranteed by the 471 // corresponding C code. 472 let pdev = unsafe { container_of!(dev.as_raw(), bindings::pci_dev, dev) }; 473 474 // SAFETY: `pdev` is a valid pointer to a `struct pci_dev`. 475 Ok(unsafe { &*pdev.cast() }) 476 } 477 } 478 479 // SAFETY: A `Device` is always reference-counted and can be released from any thread. 480 unsafe impl Send for Device {} 481 482 // SAFETY: `Device` can be shared among threads because all methods of `Device` 483 // (i.e. `Device<Normal>) are thread safe. 484 unsafe impl Sync for Device {} 485