summaryrefslogtreecommitdiff
path: root/rust/kernel/pci/io.rs
blob: 953e16735c6ed77ffa59a5d82966c87e1346ad72 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// SPDX-License-Identifier: GPL-2.0

//! PCI memory-mapped I/O infrastructure.

use super::Device;
use crate::{
    bindings,
    device,
    devres::DevresLt,
    io::{
        IoBackend,
        IoBase,
        IoCapable,
        Mmio,
        MmioBackend,
        MmioRaw,
        Region, //
    },
    prelude::*,
    ptr::KnownSize,
    types::{
        CovariantForLt,
        ForLt, //
    }, //
};

/// Represents the size of a PCI configuration space.
///
/// PCI devices can have either a *normal* (legacy) configuration space of 256 bytes,
/// or an *extended* configuration space of 4096 bytes as defined in the PCI Express
/// specification.
#[repr(usize)]
#[derive(Eq, PartialEq)]
pub enum ConfigSpaceSize {
    /// 256-byte legacy PCI configuration space.
    Normal = 256,

    /// 4096-byte PCIe extended configuration space.
    Extended = 4096,
}

impl ConfigSpaceSize {
    /// Get the raw value of this enum.
    #[inline(always)]
    pub const fn into_raw(self) -> usize {
        // CAST: PCI configuration space size is at most 4096 bytes, so the value always fits
        // within `usize` without truncation or sign change.
        self as usize
    }
}

/// Alias for normal (256-byte) PCI configuration space.
pub type Normal = Region<256>;

/// Alias for extended (4096-byte) PCIe configuration space.
pub type Extended = Region<4096>;

/// A view of PCI configuration space of a device.
///
/// Provides typed read and write accessors for configuration registers
/// using the standard `pci_read_config_*` and `pci_write_config_*` helpers.
///
/// The generic parameter `T` is the type of the view. The full configuration space is also a
/// special type of view; in such cases, `T` can be [`Normal`] for 256-byte legacy configuration
/// space or [`Extended`] for 4096-byte PCIe extended configuration space (default).
///
/// # Invariants
///
/// `ptr` is aligned and range `ptr..ptr + KnownSize::size(ptr)` is within
/// `0..pdev.cfg_size().into_raw()`.
pub struct ConfigSpace<'a, T: ?Sized = Extended> {
    pub(crate) pdev: &'a Device<device::Bound>,
    ptr: *mut T,
}

impl<T: ?Sized> Copy for ConfigSpace<'_, T> {}
impl<T: ?Sized> Clone for ConfigSpace<'_, T> {
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}

// SAFETY: `ConfigSpace<'_, T>` is conceptually `&T` but in I/O memory.
unsafe impl<T: ?Sized + Sync> Send for ConfigSpace<'_, T> {}

// SAFETY: `ConfigSpace<'_, T>` is conceptually `&T` but in I/O memory.
unsafe impl<T: ?Sized + Sync> Sync for ConfigSpace<'_, T> {}

/// I/O Backend for PCI configuration space.
pub struct ConfigSpaceBackend;

impl IoBackend for ConfigSpaceBackend {
    type View<'a, T: ?Sized + KnownSize> = ConfigSpace<'a, T>;

    #[inline]
    fn as_ptr<'a, T: ?Sized + KnownSize>(view: ConfigSpace<'a, T>) -> *mut T {
        view.ptr
    }

    #[inline]
    unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSize>(
        view: Self::View<'a, T>,
        ptr: *mut U,
    ) -> Self::View<'a, U> {
        // INVARIANT: Per safety requirement.
        ConfigSpace {
            pdev: view.pdev,
            ptr,
        }
    }
}

/// Implements [`IoCapable`] on [`ConfigSpace`] for `$ty` using `$read_fn` and `$write_fn`.
macro_rules! impl_config_space_io_capable {
    ($ty:ty, $read_fn:ident, $write_fn:ident) => {
        impl IoCapable<$ty> for ConfigSpaceBackend {
            fn io_read(view: ConfigSpace<'_, $ty>) -> $ty {
                // CAST: The offset is cast to `i32` because the C functions expect a 32-bit
                // signed offset parameter. PCI configuration space size is at most 4096 bytes,
                // so the value always fits within `i32` without truncation or sign change.
                let addr = view.ptr.addr() as i32;

                let mut val: $ty = 0;

                // Return value from C function is ignored in infallible accessors.
                // SAFETY: By the type invariant `pdev` is a valid address.
                let _ = unsafe { bindings::$read_fn(view.pdev.as_raw(), addr, &mut val) };
                val
            }

            fn io_write(view: ConfigSpace<'_, $ty>, value: $ty) {
                // CAST: The offset is cast to `i32` because the C functions expect a 32-bit
                // signed offset parameter. PCI configuration space size is at most 4096 bytes,
                // so the value always fits within `i32` without truncation or sign change.
                let addr = view.ptr.addr() as i32;

                // Return value from C function is ignored in infallible accessors.
                // SAFETY: By the type invariant `pdev` is a valid address.
                let _ = unsafe { bindings::$write_fn(view.pdev.as_raw(), addr, value) };
            }
        }
    };
}

// PCI configuration space supports 8, 16, and 32-bit accesses.
impl_config_space_io_capable!(u8, pci_read_config_byte, pci_write_config_byte);
impl_config_space_io_capable!(u16, pci_read_config_word, pci_write_config_word);
impl_config_space_io_capable!(u32, pci_read_config_dword, pci_write_config_dword);

impl<'a, T: ?Sized + KnownSize> IoBase<'a> for ConfigSpace<'a, T> {
    type Backend = ConfigSpaceBackend;
    type Target = T;

    #[inline]
    fn as_view(self) -> ConfigSpace<'a, T> {
        self
    }
}

/// A PCI BAR to perform I/O-Operations on.
///
/// I/O backend assumes that the device is little-endian and will automatically
/// convert from little-endian to CPU endianness.
///
/// # Invariants
///
/// `Bar` always holds an `IoRaw` instance that holds a valid pointer to the start of the I/O
/// memory mapped PCI BAR and its size.
pub struct Bar<'a, const SIZE: usize = 0> {
    pdev: &'a Device<device::Bound>,
    io: MmioRaw<crate::io::Region<SIZE>>,
    num: i32,
}

impl<const SIZE: usize> ForLt for Bar<'static, SIZE> {
    type Of<'a> = Bar<'a, SIZE>;
}

// SAFETY: `Bar<'a, SIZE>` is covariant over `'a`; it holds `&'a Device<Bound>`,
// which is covariant.
unsafe impl<const SIZE: usize> CovariantForLt for Bar<'static, SIZE> {}

/// A device-managed PCI BAR mapping.
///
/// See [`Bar::into_devres`].
pub type DevresBar<const SIZE: usize = 0> = DevresLt<Bar<'static, SIZE>>;

impl<'a, const SIZE: usize> Bar<'a, SIZE> {
    pub(super) fn new(
        pdev: &'a Device<device::Bound>,
        num: u32,
        name: &'static CStr,
    ) -> Result<Self> {
        let len = pdev.resource_len(num)?;
        if len == 0 {
            return Err(ENOMEM);
        }

        // Convert to `i32`, since that's what all the C bindings use.
        let num = i32::try_from(num)?;

        // SAFETY:
        // `pdev` is valid by the invariants of `Device`.
        // `num` is checked for validity by a previous call to `Device::resource_len`.
        // `name` is always valid.
        let ret = unsafe { bindings::pci_request_region(pdev.as_raw(), num, name.as_char_ptr()) };
        if ret != 0 {
            return Err(EBUSY);
        }

        // SAFETY:
        // `pdev` is valid by the invariants of `Device`.
        // `num` is checked for validity by a previous call to `Device::resource_len`.
        // `name` is always valid.
        let ioptr: usize = unsafe { bindings::pci_iomap(pdev.as_raw(), num, 0) } as usize;
        if ioptr == 0 {
            // SAFETY:
            // `pdev` is valid by the invariants of `Device`.
            // `num` is checked for validity by a previous call to `Device::resource_len`.
            unsafe { bindings::pci_release_region(pdev.as_raw(), num) };
            return Err(ENOMEM);
        }

        let io = match MmioRaw::new_region(ioptr, len as usize) {
            Ok(io) => io,
            Err(err) => {
                // SAFETY:
                // `pdev` is valid by the invariants of `Device`.
                // `ioptr` is guaranteed to be the start of a valid I/O mapped memory region.
                // `num` is checked for validity by a previous call to `Device::resource_len`.
                unsafe { Self::do_release(pdev, ioptr, num) };
                return Err(err);
            }
        };

        Ok(Bar { pdev, io, num })
    }

    /// # Safety
    ///
    /// `ioptr` must be a valid pointer to the memory mapped PCI BAR number `num`.
    unsafe fn do_release(pdev: &Device, ioptr: usize, num: i32) {
        // SAFETY:
        // `pdev` is valid by the invariants of `Device`.
        // `ioptr` is valid by the safety requirements.
        // `num` is valid by the safety requirements.
        unsafe {
            bindings::pci_iounmap(pdev.as_raw(), ioptr as *mut c_void);
            bindings::pci_release_region(pdev.as_raw(), num);
        }
    }

    fn release(&self) {
        // SAFETY: The safety requirements are guaranteed by the type invariant of `self.pdev`.
        unsafe { Self::do_release(self.pdev, self.io.addr(), self.num) };
    }

    /// Consume the `Bar` and register it as a device-managed resource.
    ///
    /// The returned [`DevresBar`] can outlive the original borrow and be stored in driver data.
    /// Access to the BAR is revoked automatically when the device is unbound.
    pub fn into_devres(self) -> Result<DevresBar<SIZE>> {
        let pdev = self.pdev;
        // SAFETY: `Bar` only holds a reference to the device and an I/O mapping, both of which
        // remain valid for the device's full bound scope, not just for `'a`.
        unsafe { DevresLt::new(pdev.as_ref(), self) }
    }
}

impl Bar<'_> {
    #[inline]
    pub(super) fn index_is_valid(index: u32) -> bool {
        // A `struct pci_dev` owns an array of resources with at most `PCI_NUM_RESOURCES` entries.
        index < bindings::PCI_NUM_RESOURCES
    }
}

impl<const SIZE: usize> Drop for Bar<'_, SIZE> {
    fn drop(&mut self) {
        self.release();
    }
}

impl<'a, const SIZE: usize> IoBase<'a> for &'a Bar<'_, SIZE> {
    type Backend = MmioBackend;
    type Target = crate::io::Region<SIZE>;

    #[inline]
    fn as_view(self) -> Mmio<'a, Self::Target> {
        // SAFETY: By the type invariant of `Self`, the MMIO range in `self.io` is properly mapped.
        unsafe { Mmio::from_raw(self.io) }
    }
}

impl Device<device::Bound> {
    /// Maps an entire PCI BAR after performing a region-request on it. I/O operation bound checks
    /// can be performed on compile time for offsets (plus the requested type size) < SIZE.
    pub fn iomap_region_sized<'a, const SIZE: usize>(
        &'a self,
        bar: u32,
        name: &'static CStr,
    ) -> Result<Bar<'a, SIZE>> {
        Bar::new(self, bar, name)
    }

    /// Maps an entire PCI BAR after performing a region-request on it.
    pub fn iomap_region<'a>(&'a self, bar: u32, name: &'static CStr) -> Result<Bar<'a>> {
        self.iomap_region_sized::<0>(bar, name)
    }

    /// Returns the size of configuration space.
    pub fn cfg_size(&self) -> ConfigSpaceSize {
        // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
        let size = unsafe { (*self.as_raw()).cfg_size };
        match size {
            256 => ConfigSpaceSize::Normal,
            4096 => ConfigSpaceSize::Extended,
            _ => {
                // PANIC: The PCI subsystem only ever reports the configuration space size as either
                // `ConfigSpaceSize::Normal` or `ConfigSpaceSize::Extended`.
                unreachable!();
            }
        }
    }

    /// Return a view of the normal (256-byte) config space.
    pub fn config_space<'a>(&'a self) -> ConfigSpace<'a, Normal> {
        // INVARIANT: null is aligned and the range is within config space.
        ConfigSpace {
            pdev: self,
            ptr: Normal::ptr_from_raw_parts_mut(core::ptr::null_mut(), self.cfg_size().into_raw()),
        }
    }

    /// Return a view of the extended (4096-byte) config space.
    pub fn config_space_extended<'a>(&'a self) -> Result<ConfigSpace<'a, Extended>> {
        if self.cfg_size() != ConfigSpaceSize::Extended {
            return Err(EINVAL);
        }

        // INVARIANT: null is aligned and we just checked the `cfg_size`.
        Ok(ConfigSpace {
            pdev: self,
            ptr: Extended::ptr_from_raw_parts_mut(core::ptr::null_mut(), 4096),
        })
    }
}