Skip to content

Commit aba7d07

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 ec8dca4 commit aba7d07

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,13 @@
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,
1215
str::CStr,
1316
types::{ARef, ForeignOwnable},
1417
ThisModule,
@@ -239,9 +242,116 @@ pub trait Driver {
239242
///
240243
/// A PCI device is based on an always reference counted `device:Device` instance. Cloning a PCI
241244
/// device, hence, also increments the base device' reference count.
245+
///
246+
/// # Invariants
247+
///
248+
/// `Device` hold a valid reference of `ARef<device::Device>` whose underlying `struct device` is a
249+
/// member of a `struct pci_dev`.
242250
#[derive(Clone)]
243251
pub struct Device(ARef<device::Device>);
244252

253+
/// A PCI BAR to perform I/O-Operations on.
254+
///
255+
/// # Invariants
256+
///
257+
/// `Bar` always holds an `Io` inststance that holds a valid pointer to the start of the I/O memory
258+
/// mapped PCI bar and its size.
259+
pub struct Bar<const SIZE: usize = 0> {
260+
pdev: Device,
261+
io: Io<SIZE>,
262+
num: i32,
263+
}
264+
265+
impl<const SIZE: usize> Bar<SIZE> {
266+
fn new(pdev: Device, num: u32, name: &CStr) -> Result<Self> {
267+
let len = pdev.resource_len(num)?;
268+
if len == 0 {
269+
return Err(ENOMEM);
270+
}
271+
272+
// Convert to `i32`, since that's what all the C bindings use.
273+
let num = i32::try_from(num)?;
274+
275+
// SAFETY:
276+
// `pdev` is valid by the invariants of `Device`.
277+
// `num` is checked for validity by a previous call to `Device::resource_len`.
278+
// `name` is always valid.
279+
let ret = unsafe { bindings::pci_request_region(pdev.as_raw(), num, name.as_char_ptr()) };
280+
if ret != 0 {
281+
return Err(EBUSY);
282+
}
283+
284+
// SAFETY:
285+
// `pdev` is valid by the invariants of `Device`.
286+
// `num` is checked for validity by a previous call to `Device::resource_len`.
287+
// `name` is always valid.
288+
let ioptr: usize = unsafe { bindings::pci_iomap(pdev.as_raw(), num, 0) } as usize;
289+
if ioptr == 0 {
290+
// SAFETY:
291+
// `pdev` valid by the invariants of `Device`.
292+
// `num` is checked for validity by a previous call to `Device::resource_len`.
293+
unsafe { bindings::pci_release_region(pdev.as_raw(), num) };
294+
return Err(ENOMEM);
295+
}
296+
297+
// SAFETY: `ioptr` is guaranteed to be the start of a valid I/O mapped memory region of size
298+
// `len`.
299+
let io = match unsafe { Io::new(ioptr, len as usize) } {
300+
Ok(io) => io,
301+
Err(err) => {
302+
// SAFETY:
303+
// `pdev` is valid by the invariants of `Device`.
304+
// `ioptr` is guaranteed to be the start of a valid I/O mapped memory region.
305+
// `num` is checked for validity by a previous call to `Device::resource_len`.
306+
unsafe { Self::do_release(&pdev, ioptr, num) };
307+
return Err(err);
308+
}
309+
};
310+
311+
Ok(Bar { pdev, io, num })
312+
}
313+
314+
/// # Safety
315+
///
316+
/// `ioptr` must be a valid pointer to the memory mapped PCI bar number `num`.
317+
unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) {
318+
// SAFETY:
319+
// `pdev` is valid by the invariants of `Device`.
320+
// `ioptr` is valid by the safety requirements.
321+
// `num` is valid by the safety requirements.
322+
unsafe {
323+
bindings::pci_iounmap(pdev.as_raw(), ioptr as _);
324+
bindings::pci_release_region(pdev.as_raw(), num);
325+
}
326+
}
327+
328+
fn release(&self) {
329+
// SAFETY: The safety requirements are guaranteed by the type invariant of `self.pdev`.
330+
unsafe { Self::do_release(&self.pdev, self.io.base_addr(), self.num) };
331+
}
332+
}
333+
334+
impl Bar {
335+
fn index_is_valid(index: u32) -> bool {
336+
// A `struct pci_dev` owns an array of resources with at most `PCI_NUM_RESOURCES` entries.
337+
index < bindings::PCI_NUM_RESOURCES
338+
}
339+
}
340+
341+
impl<const SIZE: usize> Drop for Bar<SIZE> {
342+
fn drop(&mut self) {
343+
self.release();
344+
}
345+
}
346+
347+
impl<const SIZE: usize> Deref for Bar<SIZE> {
348+
type Target = Io<SIZE>;
349+
350+
fn deref(&self) -> &Self::Target {
351+
&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)