Skip to content

Commit 79af67e

Browse files
author
Danilo Krummrich
committed
rust: pci: implement I/O mappable pci::Bar
Implement `pci::Bar`, `pci::Device::iomap_region` and `pci::Device::iomap_region_sized` to allow for I/O mappings of PCI BARs. To ensure that a `pci::Bar`, and hence the I/O memory mapping, can't out-live the PCI device, the `pci::Bar` type is always embedded into a `Devres` container, such that the `pci::Bar` is revoked once the device is unbound and hence the I/O mapped memory is unmapped. A `pci::Bar` can be requested with (`pci::Device::iomap_region_sized`) or without (`pci::Device::iomap_region`) a const generic representing the minimal requested size of the I/O mapped memory region. In case of the latter only runtime checked I/O reads / writes are possible. Co-developed-by: Philipp Stanner <[email protected]> Signed-off-by: Philipp Stanner <[email protected]> Signed-off-by: Danilo Krummrich <[email protected]>
1 parent 9490ecf commit 79af67e

File tree

1 file changed

+145
-0
lines changed

1 file changed

+145
-0
lines changed

rust/kernel/pci.rs

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@
55
//! C header: [`include/linux/pci.h`](srctree/include/linux/pci.h)
66
77
use crate::{
8+
alloc::flags::*,
89
bindings, container_of, device,
910
device_id::RawDeviceId,
11+
devres::Devres,
1012
driver,
1113
error::{to_result, Result},
14+
io::Io,
15+
io::IoRaw,
1216
str::CStr,
1317
types::{ARef, ForeignOwnable},
1418
ThisModule,
@@ -239,9 +243,115 @@ pub trait Driver {
239243
///
240244
/// A PCI device is based on an always reference counted `device:Device` instance. Cloning a PCI
241245
/// device, hence, also increments the base device' reference count.
246+
///
247+
/// # Invariants
248+
///
249+
/// `Device` hold a valid reference of `ARef<device::Device>` whose underlying `struct device` is a
250+
/// member of a `struct pci_dev`.
242251
#[derive(Clone)]
243252
pub struct Device(ARef<device::Device>);
244253

254+
/// A PCI BAR to perform I/O-Operations on.
255+
///
256+
/// # Invariants
257+
///
258+
/// `Bar` always holds an `IoRaw` inststance that holds a valid pointer to the start of the I/O
259+
/// memory mapped PCI bar and its size.
260+
pub struct Bar<const SIZE: usize = 0> {
261+
pdev: Device,
262+
io: IoRaw<SIZE>,
263+
num: i32,
264+
}
265+
266+
impl<const SIZE: usize> Bar<SIZE> {
267+
fn new(pdev: Device, num: u32, name: &CStr) -> Result<Self> {
268+
let len = pdev.resource_len(num)?;
269+
if len == 0 {
270+
return Err(ENOMEM);
271+
}
272+
273+
// Convert to `i32`, since that's what all the C bindings use.
274+
let num = i32::try_from(num)?;
275+
276+
// SAFETY:
277+
// `pdev` is valid by the invariants of `Device`.
278+
// `num` is checked for validity by a previous call to `Device::resource_len`.
279+
// `name` is always valid.
280+
let ret = unsafe { bindings::pci_request_region(pdev.as_raw(), num, name.as_char_ptr()) };
281+
if ret != 0 {
282+
return Err(EBUSY);
283+
}
284+
285+
// SAFETY:
286+
// `pdev` is valid by the invariants of `Device`.
287+
// `num` is checked for validity by a previous call to `Device::resource_len`.
288+
// `name` is always valid.
289+
let ioptr: usize = unsafe { bindings::pci_iomap(pdev.as_raw(), num, 0) } as usize;
290+
if ioptr == 0 {
291+
// SAFETY:
292+
// `pdev` valid by the invariants of `Device`.
293+
// `num` is checked for validity by a previous call to `Device::resource_len`.
294+
unsafe { bindings::pci_release_region(pdev.as_raw(), num) };
295+
return Err(ENOMEM);
296+
}
297+
298+
let io = match IoRaw::new(ioptr, len as usize) {
299+
Ok(io) => io,
300+
Err(err) => {
301+
// SAFETY:
302+
// `pdev` is valid by the invariants of `Device`.
303+
// `ioptr` is guaranteed to be the start of a valid I/O mapped memory region.
304+
// `num` is checked for validity by a previous call to `Device::resource_len`.
305+
unsafe { Self::do_release(&pdev, ioptr, num) };
306+
return Err(err);
307+
}
308+
};
309+
310+
Ok(Bar { pdev, io, num })
311+
}
312+
313+
/// # Safety
314+
///
315+
/// `ioptr` must be a valid pointer to the memory mapped PCI bar number `num`.
316+
unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) {
317+
// SAFETY:
318+
// `pdev` is valid by the invariants of `Device`.
319+
// `ioptr` is valid by the safety requirements.
320+
// `num` is valid by the safety requirements.
321+
unsafe {
322+
bindings::pci_iounmap(pdev.as_raw(), ioptr as _);
323+
bindings::pci_release_region(pdev.as_raw(), num);
324+
}
325+
}
326+
327+
fn release(&self) {
328+
// SAFETY: The safety requirements are guaranteed by the type invariant of `self.pdev`.
329+
unsafe { Self::do_release(&self.pdev, self.io.addr(), self.num) };
330+
}
331+
}
332+
333+
impl Bar {
334+
fn index_is_valid(index: u32) -> bool {
335+
// A `struct pci_dev` owns an array of resources with at most `PCI_NUM_RESOURCES` entries.
336+
index < bindings::PCI_NUM_RESOURCES
337+
}
338+
}
339+
340+
impl<const SIZE: usize> Drop for Bar<SIZE> {
341+
fn drop(&mut self) {
342+
self.release();
343+
}
344+
}
345+
346+
impl<const SIZE: usize> Deref for Bar<SIZE> {
347+
type Target = Io<SIZE>;
348+
349+
fn deref(&self) -> &Self::Target {
350+
// SAFETY: By the type invariant of `Self`, the MMIO range in `self.io` is properly mapped.
351+
unsafe { Io::from_raw(&self.io) }
352+
}
353+
}
354+
245355
impl Device {
246356
/// Create a PCI Device instance from an existing `device::Device`.
247357
///
@@ -275,6 +385,41 @@ impl Device {
275385
// SAFETY: `self.as_raw` is guaranteed to be a pointer to a valid `struct pci_dev`.
276386
unsafe { bindings::pci_set_master(self.as_raw()) };
277387
}
388+
389+
/// Returns the size of the given PCI bar resource.
390+
pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> {
391+
if !Bar::index_is_valid(bar) {
392+
return Err(EINVAL);
393+
}
394+
395+
// SAFETY:
396+
// - `bar` is a valid bar number, as guaranteed by the above call to `Bar::index_is_valid`,
397+
// - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`.
398+
Ok(unsafe { bindings::pci_resource_len(self.as_raw(), bar.try_into()?) })
399+
}
400+
401+
/// Mapps an entire PCI-BAR after performing a region-request on it. I/O operation bound checks
402+
/// can be performed on compile time for offsets (plus the requested type size) < SIZE.
403+
pub fn iomap_region_sized<const SIZE: usize>(
404+
&self,
405+
bar: u32,
406+
name: &CStr,
407+
) -> Result<Devres<Bar<SIZE>>> {
408+
let bar = Bar::<SIZE>::new(self.clone(), bar, name)?;
409+
let devres = Devres::new(self.as_ref(), bar, GFP_KERNEL)?;
410+
411+
Ok(devres)
412+
}
413+
414+
/// Mapps an entire PCI-BAR after performing a region-request on it.
415+
pub fn iomap_region(&self, bar: u32, name: &CStr) -> Result<Devres<Bar>> {
416+
self.iomap_region_sized::<0>(bar, name)
417+
}
418+
419+
/// Returns a new `ARef` of the base `device::Device`.
420+
pub fn as_dev(&self) -> ARef<device::Device> {
421+
self.0.clone()
422+
}
278423
}
279424

280425
impl AsRef<device::Device> for Device {

0 commit comments

Comments
 (0)