kernel/pci/
io.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! PCI memory-mapped I/O infrastructure.
4
5use super::Device;
6use crate::{
7    bindings,
8    device,
9    devres::Devres,
10    io::{
11        Io,
12        IoRaw, //
13    },
14    prelude::*,
15    sync::aref::ARef, //
16};
17use core::ops::Deref;
18
19/// A PCI BAR to perform I/O-Operations on.
20///
21/// I/O backend assumes that the device is little-endian and will automatically
22/// convert from little-endian to CPU endianness.
23///
24/// # Invariants
25///
26/// `Bar` always holds an `IoRaw` instance that holds a valid pointer to the start of the I/O
27/// memory mapped PCI BAR and its size.
28pub struct Bar<const SIZE: usize = 0> {
29    pdev: ARef<Device>,
30    io: IoRaw<SIZE>,
31    num: i32,
32}
33
34impl<const SIZE: usize> Bar<SIZE> {
35    pub(super) fn new(pdev: &Device, num: u32, name: &CStr) -> Result<Self> {
36        let len = pdev.resource_len(num)?;
37        if len == 0 {
38            return Err(ENOMEM);
39        }
40
41        // Convert to `i32`, since that's what all the C bindings use.
42        let num = i32::try_from(num)?;
43
44        // SAFETY:
45        // `pdev` is valid by the invariants of `Device`.
46        // `num` is checked for validity by a previous call to `Device::resource_len`.
47        // `name` is always valid.
48        let ret = unsafe { bindings::pci_request_region(pdev.as_raw(), num, name.as_char_ptr()) };
49        if ret != 0 {
50            return Err(EBUSY);
51        }
52
53        // SAFETY:
54        // `pdev` is valid by the invariants of `Device`.
55        // `num` is checked for validity by a previous call to `Device::resource_len`.
56        // `name` is always valid.
57        let ioptr: usize = unsafe { bindings::pci_iomap(pdev.as_raw(), num, 0) } as usize;
58        if ioptr == 0 {
59            // SAFETY:
60            // `pdev` is valid by the invariants of `Device`.
61            // `num` is checked for validity by a previous call to `Device::resource_len`.
62            unsafe { bindings::pci_release_region(pdev.as_raw(), num) };
63            return Err(ENOMEM);
64        }
65
66        let io = match IoRaw::new(ioptr, len as usize) {
67            Ok(io) => io,
68            Err(err) => {
69                // SAFETY:
70                // `pdev` is valid by the invariants of `Device`.
71                // `ioptr` is guaranteed to be the start of a valid I/O mapped memory region.
72                // `num` is checked for validity by a previous call to `Device::resource_len`.
73                unsafe { Self::do_release(pdev, ioptr, num) };
74                return Err(err);
75            }
76        };
77
78        Ok(Bar {
79            pdev: pdev.into(),
80            io,
81            num,
82        })
83    }
84
85    /// # Safety
86    ///
87    /// `ioptr` must be a valid pointer to the memory mapped PCI BAR number `num`.
88    unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) {
89        // SAFETY:
90        // `pdev` is valid by the invariants of `Device`.
91        // `ioptr` is valid by the safety requirements.
92        // `num` is valid by the safety requirements.
93        unsafe {
94            bindings::pci_iounmap(pdev.as_raw(), ioptr as *mut c_void);
95            bindings::pci_release_region(pdev.as_raw(), num);
96        }
97    }
98
99    fn release(&self) {
100        // SAFETY: The safety requirements are guaranteed by the type invariant of `self.pdev`.
101        unsafe { Self::do_release(&self.pdev, self.io.addr(), self.num) };
102    }
103}
104
105impl Bar {
106    #[inline]
107    pub(super) fn index_is_valid(index: u32) -> bool {
108        // A `struct pci_dev` owns an array of resources with at most `PCI_NUM_RESOURCES` entries.
109        index < bindings::PCI_NUM_RESOURCES
110    }
111}
112
113impl<const SIZE: usize> Drop for Bar<SIZE> {
114    fn drop(&mut self) {
115        self.release();
116    }
117}
118
119impl<const SIZE: usize> Deref for Bar<SIZE> {
120    type Target = Io<SIZE>;
121
122    fn deref(&self) -> &Self::Target {
123        // SAFETY: By the type invariant of `Self`, the MMIO range in `self.io` is properly mapped.
124        unsafe { Io::from_raw(&self.io) }
125    }
126}
127
128impl Device<device::Bound> {
129    /// Maps an entire PCI BAR after performing a region-request on it. I/O operation bound checks
130    /// can be performed on compile time for offsets (plus the requested type size) < SIZE.
131    pub fn iomap_region_sized<'a, const SIZE: usize>(
132        &'a self,
133        bar: u32,
134        name: &'a CStr,
135    ) -> impl PinInit<Devres<Bar<SIZE>>, Error> + 'a {
136        Devres::new(self.as_ref(), Bar::<SIZE>::new(self, bar, name))
137    }
138
139    /// Maps an entire PCI BAR after performing a region-request on it.
140    pub fn iomap_region<'a>(
141        &'a self,
142        bar: u32,
143        name: &'a CStr,
144    ) -> impl PinInit<Devres<Bar>, Error> + 'a {
145        self.iomap_region_sized::<0>(bar, name)
146    }
147}