Skip to main content

ostd/io/io_mem/
mod.rs

1// SPDX-License-Identifier: MPL-2.0
2//! I/O memory and its allocator that allocates memory I/O (MMIO) to device drivers.
3//!
4//! # Verification Design
5//! Verification follows the intended exclusive ownership model: Multiple `IoMem` instances should not overlap, and
6//!the `Clone` and `IoMem::slice` are disabled.
7use vstd::{arithmetic::power2::is_pow2, prelude::*};
8
9use crate::specs::{
10    arch::PAGE_SIZE,
11    mm::{io::VmIoOwner, virt_mem::VirtPtr},
12};
13use crate::util::range_alloc::FreePermit;
14
15mod allocator;
16
17use core::ops::{Deref, Range};
18
19use align_ext::AlignExt;
20
21pub(crate) use self::allocator::IoMemAllocatorBuilder;
22pub(super) use self::allocator::{init, io_mem_allocator_initialized};
23use crate::{
24    Error,
25    mm::{
26        FallibleVmRead, FallibleVmWrite, HasPaddr, Infallible, /*PAGE_SIZE,*/ Paddr, PodOnce,
27        VmIo, VmIoOnce, VmReader, VmWriter,
28        kspace::kvirt_area::KVirtArea,
29        page_prop::{CachePolicy, PageFlags, PageProperty, PrivilegedPageFlags},
30    },
31    prelude::*,
32};
33
34/// I/O memory.
35/* Exclusive ownership does not allow `Clone`
36 * Origin Rust: #[derive(Debug, Clone)]
37 */
38#[derive(Debug)]
39#[verus_verify]
40pub struct IoMem {
41    kvirt_area: Arc<KVirtArea>,
42    // The actually used range for MMIO is `kvirt_area.start + offset..kvirt_area.start + offset + limit`
43    offset: usize,
44    limit: usize,
45    pa: Paddr,
46    #[cfg(verus_keep_ghost_body)]
47    tracked_perm: Tracked<Option<FreePermit>>,
48}
49
50verus! {
51
52#[verus_verify]
53impl IoMem {
54    /// Logical offset into the page-aligned mapping.
55    pub closed spec fn offset_spec(&self) -> usize {
56        self.offset
57    }
58
59    /// The allocator-issued permit for the original MMIO range, if present.
60    pub closed spec fn allocation_perm(&self) -> Option<FreePermit> {
61        self.tracked_perm@
62    }
63}
64
65} // verus!
66#[verus_verify]
67impl HasPaddr for IoMem {
68    #[verus_spec(returns IoMem::paddr(self))]
69    fn paddr(&self) -> Paddr {
70        self.pa
71    }
72}
73
74#[verus_verify]
75impl IoMem {
76    /// Acquires an `IoMem` instance for the given range.
77    #[verifier::external_body]
78    #[verus_spec(result =>
79        requires
80            range.start < range.end <= usize::MAX - (PAGE_SIZE - 1),
81            allocator::io_mem_range_registered(range),
82            allocator::io_mem_allocator_initialized(),
83        ensures
84            result matches Ok(io_mem) ==> {
85                &&& io_mem.paddr() == range.start
86                &&& io_mem.length() == range.end - range.start
87                &&& io_mem.allocation_perm() matches Some(permit)
88                &&& permit.range() == range
89            },
90    )]
91    pub fn acquire(range: Range<Paddr>) -> Result<IoMem> {
92        allocator::IO_MEM_ALLOCATOR
93            .get()
94            .unwrap()
95            .acquire(range)
96            .ok_or(Error::AccessDenied)
97    }
98
99    /// Returns the physical address of the I/O memory.
100    #[verus_verify(dual_spec)]
101    #[verus_spec(returns self.paddr())]
102    pub fn paddr(&self) -> Paddr {
103        self.pa
104    }
105
106    /// Returns the length of the I/O memory region.
107    #[verus_verify(dual_spec)]
108    #[verus_spec(returns self.length())]
109    pub fn length(&self) -> usize {
110        self.limit
111    }
112
113    /* Exclusive ownership does not allow `slice`
114    /// Slices the `IoMem`, returning another `IoMem` representing the subslice.
115    ///
116    /// # Panics
117    ///
118    /// This method will panic if the range is empty or out of bounds.
119    pub fn slice(&self, range: Range<usize>) -> Self {
120        // This ensures `range.start < range.end` and `range.end <= limit`.
121        assert!(!range.is_empty() && range.end <= self.limit);
122
123        // We've checked the range is in bounds, so we can construct the new `IoMem` safely.
124        Self {
125            kvirt_area: self.kvirt_area.clone(),
126            offset: self.offset + range.start,
127            limit: range.len(),
128            pa: self.pa + range.start,
129        }
130    }
131    */
132
133    /// Creates a new `IoMem`.
134    ///
135    /// # Safety
136    ///
137    /// - The given physical address range must be in the I/O memory region.
138    /// - Reading from or writing to I/O memory regions may have side effects. Those side effects
139    ///   must not cause soundness problems (e.g., they must not corrupt the kernel memory).
140    #[verifier::external_body]
141    #[verus_spec(result =>
142        requires
143            is_pow2(PAGE_SIZE as int),
144            range.start <= range.end <= usize::MAX - (PAGE_SIZE - 1),
145        ensures
146            result.paddr() == range.start,
147            result.length()
148                == range.end - range.start,
149            result.offset_spec() < PAGE_SIZE,
150            result.allocation_perm() is None,
151    )]
152    pub(crate) unsafe fn new(range: Range<Paddr>, flags: PageFlags, cache: CachePolicy) -> Self {
153        let first_page_start = range.start.align_down(PAGE_SIZE);
154        let last_page_end = range.end.align_up(PAGE_SIZE);
155
156        let frames_range = first_page_start..last_page_end;
157        let area_size = frames_range.len();
158
159        #[cfg(target_arch = "x86_64")]
160        let priv_flags = crate::arch::if_tdx_enabled!({
161            assert!(
162                first_page_start == range.start && last_page_end == range.end,
163                "I/O memory is not page aligned, which cannot be unprotected in TDX: {:#x?}..{:#x?}",
164                range.start,
165                range.end,
166            );
167
168            let num_pages = area_size / PAGE_SIZE;
169            // SAFETY:
170            //  - The range `first_page_start..last_page_end` is always page aligned.
171            //  - FIXME: We currently do not limit the I/O memory allocator with the maximum GPA,
172            //    so the address range may not fall in the GPA limit.
173            //  - FIXME: The I/O memory can be at a high address, so it may not be contained in the
174            //    linear mapping.
175            //  - The caller guarantees that operations on the I/O memory do not have any side
176            //    effects that may cause soundness problems, so the pages can safely be viewed as
177            //    untyped memory.
178            unsafe { crate::arch::tdx_guest::unprotect_gpa_range(first_page_start, num_pages).unwrap() };
179
180            PrivilegedPageFlags::SHARED
181        } else {
182            PrivilegedPageFlags::empty()
183        });
184        #[cfg(not(target_arch = "x86_64"))]
185        let priv_flags = PrivilegedPageFlags::empty();
186
187        let prop = PageProperty {
188            flags,
189            cache,
190            priv_flags,
191        };
192
193        // SAFETY: The caller of `IoMem::new()` ensures that the given
194        // physical address range is I/O memory, so it is safe to map.
195        let kva = unsafe { KVirtArea::map_untracked_frames(area_size, 0, frames_range, prop) };
196
197        proof_with! { tracked_perm: Tracked(None) }
198        Self {
199            kvirt_area: Arc::new(kva),
200            offset: range.start - first_page_start,
201            limit: range.len(),
202            pa: range.start,
203        }
204    }
205}
206
207// For now, we reuse `VmReader` and `VmWriter` to access I/O memory.
208//
209// Note that I/O memory is not normal typed or untyped memory. Strictly speaking, it is not
210// "memory", but rather I/O ports that communicate directly with the hardware. However, this code
211// is in OSTD, so we can rely on the implementation details of `VmReader` and `VmWriter`, which we
212// know are also suitable for accessing I/O memory.
213
214impl IoMem {
215    fn reader(&self) -> VmReader<'_, Infallible> {
216        // SAFETY: The constructor of the `IoMem` structure has already ensured the
217        // safety of reading from the mapped physical address, and the mapping is valid.
218        unsafe {
219            VmReader::from_kernel_space(
220                /* Original Rust:
221                (self.kvirt_area.deref().start() + self.offset) as *mut u8, */
222                VirtPtr::from_vaddr(self.kvirt_area.deref().start() + self.offset, self.limit),
223                self.limit,
224            )
225        }
226    }
227
228    fn writer(&self) -> VmWriter<'_, Infallible> {
229        // SAFETY: The constructor of the `IoMem` structure has already ensured the
230        // safety of writing to the mapped physical address, and the mapping is valid.
231        unsafe {
232            VmWriter::from_kernel_space(
233                /* Original Rust:
234                (self.kvirt_area.deref().start() + self.offset) as *mut u8, */
235                VirtPtr::from_vaddr(self.kvirt_area.deref().start() + self.offset, self.limit),
236                self.limit,
237            )
238        }
239    }
240}
241
242verus! {
243
244/* Original Rust: impl VmIo for IoMem { */
245impl VmIo<()> for IoMem {
246    closed spec fn obeys_vmio_spec() -> bool {
247        false
248    }
249
250    closed spec fn obeys_vmio_read_spec() -> bool {
251        false
252    }
253
254    closed spec fn obeys_vmio_write_spec() -> bool {
255        false
256    }
257
258    open spec fn read_spec(
259        self,
260        offset: usize,
261        old_writer: VmWriter<'_>,
262        new_writer: VmWriter<'_>,
263        old_writer_own: VmIoOwner,
264        new_writer_own: VmIoOwner,
265        old_owner: (),
266        new_owner: (),
267        r: Result<()>,
268    ) -> bool {
269        false
270    }
271
272    open spec fn write_spec(
273        self,
274        offset: usize,
275        old_reader: VmReader<'_>,
276        new_reader: VmReader<'_>,
277        old_reader_own: VmIoOwner,
278        new_reader_own: VmIoOwner,
279        old_owner: (),
280        new_owner: (),
281        r: Result<()>,
282    ) -> bool {
283        false
284    }
285
286    #[verifier::external_body]
287    /* Original Rust: fn read(&self, offset: usize, writer: &mut VmWriter) -> Result<()> { */
288    fn read(
289        &self,
290        offset: usize,
291        writer: &mut VmWriter,
292        Tracked(_writer_own): Tracked<&mut VmIoOwner>,
293        Tracked(_owner): Tracked<&mut ()>,
294    ) -> Result<()> {
295        let offset = offset + self.offset;
296        if self.limit.checked_sub(offset).is_none_or(|remain| remain < writer.avail()) {
297            return Err(Error::InvalidArgs);
298        }
299        self.reader().skip(offset).read_fallible(writer).map_err(|(e, _)| e)?;
300        debug_assert!(!writer.has_avail());
301
302        Ok(())
303    }
304
305    #[verifier::external_body]
306    /* Original Rust: fn write(&self, offset: usize, reader: &mut VmReader) -> Result<()> { */
307    fn write(
308        &self,
309        offset: usize,
310        reader: &mut VmReader,
311        Tracked(_reader_own): Tracked<&mut VmIoOwner>,
312        Tracked(_owner): Tracked<&mut ()>,
313    ) -> Result<()> {
314        let offset = offset + self.offset;
315        if self.limit.checked_sub(offset).is_none_or(|remain| remain < reader.remain()) {
316            return Err(Error::InvalidArgs);
317        }
318        self.writer().skip(offset).write_fallible(reader).map_err(|(e, _)| e)?;
319        debug_assert!(!reader.has_remain());
320
321        Ok(())
322    }
323}
324
325impl VmIoOnce for IoMem {
326    closed spec fn obeys_vmio_once_read_requires() -> bool {
327        false
328    }
329
330    closed spec fn obeys_vmio_once_write_requires() -> bool {
331        false
332    }
333
334    closed spec fn obeys_vmio_once_read_ensures() -> bool {
335        false
336    }
337
338    closed spec fn obeys_vmio_once_write_ensures() -> bool {
339        false
340    }
341
342    #[verifier::external_body]
343    fn read_once<T: PodOnce>(&self, offset: usize) -> Result<T> {
344        self.reader().skip(offset).read_once()
345    }
346
347    #[verifier::external_body]
348    fn write_once<T: PodOnce>(&self, offset: usize, new_val: &T) -> Result<()> {
349        self.writer().skip(offset).write_once(new_val)
350    }
351}
352
353} // verus!
354impl Drop for IoMem {
355    fn drop(&mut self) {
356        // TODO: Multiple `IoMem` instances should not overlap, we should refactor the driver code and
357        // remove the `Clone` and `IoMem::slice`. After refactoring, the `Drop` can be implemented to recycle
358        // the `IoMem`.
359    }
360}