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