Skip to main content

ostd/mm/
io.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Abstractions for reading and writing virtual memory (VM) objects.
3//!
4//! # Safety
5//!
6//! The core virtual memory (VM) access APIs provided by this module are [`VmReader`] and
7//! [`VmWriter`], which allow for writing to or reading from a region of memory _safely_.
8//! `VmReader` and `VmWriter` objects can be constructed from memory regions of either typed memory
9//! (e.g., `&[u8]`) or untyped memory (e.g, [`UFrame`]). Behind the scene, `VmReader` and `VmWriter`
10//! must be constructed via their [`from_user_space`] and [`from_kernel_space`] methods, whose
11//! safety depends on whether the given memory regions are _valid_ or not.
12//!
13//! [`UFrame`]: crate::mm::UFrame
14//! [`from_user_space`]: `VmReader::from_user_space`
15//! [`from_kernel_space`]: `VmReader::from_kernel_space`
16//!
17//! Here is a list of conditions for memory regions to be considered valid:
18//!
19//! - The memory region as a whole must be either typed or untyped memory, not both typed and
20//!   untyped.
21//!
22//! - If the memory region is typed, we require that:
23//!   - the [validity requirements] from the official Rust documentation must be met, and
24//!   - the type of the memory region (which must exist since the memory is typed) must be
25//!     plain-old-data, so that the writer can fill it with arbitrary data safely.
26//!
27//! [validity requirements]: core::ptr#safety
28//!
29//! - If the memory region is untyped, we require that:
30//!   - the underlying pages must remain alive while the validity requirements are in effect, and
31//!   - the kernel must access the memory region using only the APIs provided in this module, but
32//!     external accesses from hardware devices or user programs do not count.
33//!
34//! We have the last requirement for untyped memory to be valid because the safety interaction with
35//! other ways to access the memory region (e.g., atomic/volatile memory loads/stores) is not
36//! currently specified. Tis may be relaxed in the future, if appropriate and necessary.
37//!
38//! Note that data races on untyped memory are explicitly allowed (since pages can be mapped to
39//! user space, making it impossible to avoid data races). However, they may produce erroneous
40//! results, such as unexpected bytes being copied, but do not cause soundness problems.
41use vstd::{arithmetic::power2::is_pow2, prelude::*};
42use vstd_extra::{assert, ownership::Inv, panic::allowed_to_panic_if};
43
44pub use crate::specs::mm::io::{
45    VmIoMemView, VmIoOwner, axiom_kernel_mem_view, axiom_slice_in_kernel,
46};
47use crate::specs::mm::virt_mem::{MemView, VirtPtr};
48
49use crate::arch::mm::{__memcpy_fallible, __memset_fallible};
50use crate::error::*;
51use crate::{
52    Pod,
53    mm::{
54        MAX_USERSPACE_VADDR,
55        kspace::{KERNEL_BASE_VADDR, KERNEL_END_VADDR},
56    },
57};
58use core::marker::PhantomData;
59use core::ops::Range;
60
61verus! {
62
63/// Copies `len` bytes from `src` to `dst`, stopping early on page fault.
64/// Returns the number of bytes successfully copied (which is at most `len`).
65///
66/// The return value bound is the only thing the verifier promises; the actual
67/// memory state after the call is trusted (the underlying arch primitive is
68/// `extern "C"`).
69///
70/// # Safety
71/// - `src` must be valid for reads of `len` bytes.
72/// - `dst` must either be valid for writes of `len` bytes or be in user space.
73#[verifier::external_body]
74#[verus_spec(r =>
75    ensures
76        r <= len,
77)]
78unsafe fn memcpy_fallible(dst: VirtPtr, src: VirtPtr, len: usize) -> usize {
79    // SAFETY: The safety is upheld by the caller.
80    let failed_bytes = unsafe { __memcpy_fallible(dst.vaddr as *mut u8, src.vaddr as *const u8, len)
81    };
82    len - failed_bytes
83}
84
85/// Fills `len` bytes of memory at `dst` with the specified `value`, stopping
86/// early on page fault. Returns the number of bytes successfully set (at most `len`).
87///
88/// The return value bound is the only thing the verifier promises; the actual
89/// memory state after the call is trusted (the underlying arch primitive is
90/// `extern "C"`).
91///
92/// # Safety
93/// - `dst` must either be valid for writes of `len` bytes or be in user space.
94#[verifier::external_body]
95#[verus_spec(r =>
96    ensures
97        r <= len,
98)]
99unsafe fn memset_fallible(dst: VirtPtr, value: u8, len: usize) -> usize {
100    // SAFETY: The safety is upheld by the caller.
101    let failed_bytes = unsafe { __memset_fallible(dst.vaddr as *mut u8, value, len) };
102    len - failed_bytes
103}
104
105/// Marker type indicating that VM I/O operations may fail (e.g., user-space access).
106pub struct Fallible {}
107
108/// Marker type indicating that VM I/O operations cannot fail (e.g., kernel-space access).
109pub struct Infallible {}
110
111/// Copies `len` bytes from `src` to `dst`.
112///
113/// This is the escape hatch into the abstract [`VirtPtr`] memory model: it is
114/// the only place in the executable code that performs a multi-byte copy, and
115/// it discharges the obligation by delegating to [`VirtPtr::copy_nonoverlapping`].
116///
117/// # Safety
118///
119/// - `src` must be [valid] for reads of `len` bytes.
120/// - `dst` must be [valid] for writes of `len` bytes.
121///
122/// [valid]: crate::mm::io#safety
123#[inline]
124#[verus_spec(
125    with
126        Tracked(mem_src): Tracked<&MemView>,
127        Tracked(mem_dst): Tracked<&mut MemView>,
128    requires
129        src.inv(),
130        dst.inv(),
131        src.vaddr + len <= src.range@.end,
132        forall|i: usize|
133            #![trigger mem_src.addr_transl(i)]
134            src.vaddr <= i < src.vaddr + len ==> {
135                &&& mem_src.addr_transl(i) is Some
136                &&& mem_src.memory.contains_key((mem_src.addr_transl(i)->0).0)
137                &&& mem_src.memory[(mem_src.addr_transl(i)->0).0].contents[(mem_src.addr_transl(i)->0).1 as int] is Init
138            },
139        dst.vaddr + len <= dst.range@.end,
140        forall|i: usize|
141            dst.vaddr <= i < dst.vaddr + len ==> {
142                &&& old(mem_dst).addr_transl(i) is Some
143            },
144    ensures
145        *final(mem_dst) == VirtPtr::memcpy_spec(src, dst, *mem_src, *old(mem_dst), len),
146        final(mem_dst).mappings == old(mem_dst).mappings,
147        old(mem_dst).memory.dom().subset_of(final(mem_dst).memory.dom()),
148        forall|i: usize|
149            #![trigger final(mem_dst).addr_transl(i)]
150            dst.vaddr <= i < dst.vaddr + len ==> {
151                &&& final(mem_dst).addr_transl(i) is Some
152            },
153)]
154unsafe fn memcpy(dst: VirtPtr, src: VirtPtr, len: usize) {
155    /*
156    // Original memcpy using volatile_copy_memory (replaced during Verus migration):
157    unsafe { core::intrinsics::volatile_copy_memory(dst, src, len) };
158    */
159    VirtPtr::copy_nonoverlapping(&src, &dst, Tracked(mem_src), Tracked(mem_dst), len);
160}
161
162/// [`VmReader`] is a reader for reading data from a contiguous range of memory.
163///
164/// The memory range read by [`VmReader`] can be in either kernel space or user space.
165/// When the operating range is in kernel space, the memory within that range
166/// is guaranteed to be valid, and the corresponding memory reads are infallible.
167/// When the operating range is in user space, it is ensured that the page table of
168/// the process creating the [`VmReader`] is active for the duration of `'a`,
169/// and the corresponding memory reads are considered fallible.
170///
171/// When perform reading with a [`VmWriter`], if one of them represents typed memory,
172/// it can ensure that the reading range in this reader and writing range in the
173/// writer are not overlapped.
174///
175/// NOTE: The overlap mentioned above is at both the virtual address level
176/// and physical address level. There is not guarantee for the operation results
177/// of [`VmReader`] and [`VmWriter`] in overlapping untyped addresses, and it is
178/// the user's responsibility to handle this situation.
179pub struct VmReader<'a, Fallibility = Fallible> {
180    pub ghost_id: Ghost<nat>,
181    pub cursor: VirtPtr,
182    pub end: VirtPtr,
183    pub phantom: PhantomData<(&'a [u8], Fallibility)>,
184}
185
186/// [`VmWriter`] is a writer for writing data to a contiguous range of memory.
187///
188/// The memory range write by [`VmWriter`] can be in either kernel space or user space.
189/// When the operating range is in kernel space, the memory within that range
190/// is guaranteed to be valid, and the corresponding memory writes are infallible.
191/// When the operating range is in user space, it is ensured that the page table of
192/// the process creating the [`VmWriter`] is active for the duration of `'a`,
193/// and the corresponding memory writes are considered fallible.
194///
195/// When perform writing with a [`VmReader`], if one of them represents typed memory,
196/// it can ensure that the writing range in this writer and reading range in the
197/// reader are not overlapped.
198///
199/// NOTE: The overlap mentioned above is at both the virtual address level
200/// and physical address level. There is not guarantee for the operation results
201/// of [`VmReader`] and [`VmWriter`] in overlapping untyped addresses, and it is
202/// the user's responsibility to handle this situation.
203pub struct VmWriter<'a, Fallibility = Fallible> {
204    pub ghost_id: Ghost<nat>,
205    pub cursor: VirtPtr,
206    pub end: VirtPtr,
207    pub phantom: PhantomData<(&'a [u8], Fallibility)>,
208}
209
210#[verus_verify]
211impl<'a> VmWriter<'a, Infallible> {
212    /// Constructs a [`VmWriter`] from a pointer and a length, which represents
213    /// a memory range in kernel space.
214    ///
215    /// # Verified Properties
216    /// ## Preconditions
217    /// - The memory region represented by `ptr` and `len` must be valid for writes of `len` bytes
218    ///   during the entire lifetime `a`. This means that the underlying pages must remain alive,
219    ///   and the kernel must access the memory region using only the APIs provided in this module.
220    /// - The range `ptr.vaddr..ptr.vaddr + len` must represent a kernel space memory range.
221    /// ## Postconditions
222    /// - An infallible [`VmWriter`] will be created with the range `ptr.vaddr..ptr.vaddr + len`.
223    /// - The created [`VmWriter`] will have a unique identifier `id`, and its cursor will be
224    ///   initialized to `ptr`.
225    /// - The created [`VmWriter`] will be associated with a [`VmIoOwner`] that has the same `id`, the
226    ///   same memory range, and is marked as kernel space and infallible.
227    /// - The memory view of the associated [`VmIoOwner`] will be `None`, indicating that it does not
228    ///   have any specific permissions yet.
229    /// ## Safety
230    ///
231    /// `ptr` must be [valid] for writes of `len` bytes during the entire lifetime `a`.
232    ///
233    /// [valid]: crate::mm::io#safety
234    #[verus_spec(r =>
235        with
236            Ghost(id): Ghost<nat>,
237            Tracked(fallible): Tracked<bool>,
238                -> owner: Tracked<VmIoOwner>,
239        ensures
240            r.inv_wf(),
241            owner@.id == id,
242            owner@.is_fallible == fallible,
243            owner@.is_kernel,
244            r.cursor == ptr,
245            r.end == ptr.wrapping_add_spec(len),
246            r.cursor.range@ == ptr.range@,
247            r.end.range@ == ptr.range@,
248            fallible ==> owner@.mem_view is None,
249            !fallible && ptr.inv() && ptr.range@.start == ptr.vaddr
250                && len == ptr.range@.end - ptr.range@.start
251                && (len == 0 || KERNEL_BASE_VADDR <= ptr.vaddr)
252                && (len == 0 || ptr.vaddr + len <= KERNEL_END_VADDR) ==> {
253                &&& r.inv()
254                &&& owner@.inv()
255                &&& r.wf(owner@)
256                &&& owner@.has_write_view()
257            },
258    )]
259    pub unsafe fn from_kernel_space(ptr: VirtPtr, len: usize) -> Self {
260        let ghost range: Range<usize> = ptr.vaddr..(ptr.vaddr + len) as usize;
261        let tracked mem_view: Option<VmIoMemView> = if fallible {
262            None
263        } else {
264            let tracked mv = axiom_kernel_mem_view(range);
265            Some(VmIoMemView::WriteView(mv))
266        };
267        let tracked owner = VmIoOwner {
268            id,
269            range: ptr.vaddr..(ptr.vaddr + len) as usize,
270            is_fallible: fallible,
271            is_kernel: true,
272            mem_view,
273        };
274
275        proof_with!(|= Tracked(owner));
276        Self { ghost_id: Ghost(id), cursor: ptr, end: ptr.wrapping_add(len), phantom: PhantomData }
277    }
278
279    /// Converts an infallible writer into a fallible one.
280    #[verus_spec(r =>
281        requires
282            self.inv(),
283        ensures
284            r.inv(),
285            r.cursor == self.cursor,
286            r.end == self.end,
287            r.ghost_id == self.ghost_id,
288    )]
289    pub fn to_fallible(self) -> VmWriter<'a, Fallible> {
290        VmWriter {
291            ghost_id: self.ghost_id,
292            cursor: self.cursor,
293            end: self.end,
294            phantom: PhantomData,
295        }
296    }
297
298    /// Writes a value of `Pod` type to the kernel-space buffer.
299    ///
300    /// If the length of the `Pod` type exceeds `self.avail()`, this method
301    /// will return `Err(InvalidArgs)`. Kernel-space writes don't fault, so
302    /// no rollback is needed — see [`VmWriter<Fallible>::write_val`] for the
303    /// user-space variant with cursor rewind.
304    ///
305    /// # Verified Properties
306    /// ## Preconditions
307    /// - The writer and its owner must satisfy their invariants.
308    /// - The owner must match this writer and carry a write memory view.
309    /// ## Postconditions
310    /// - The writer and owner still satisfy their invariants.
311    /// - On success, the cursor advances by `size_of::<T>()`.
312    /// - On error, the writer state is unchanged.
313    #[verus_spec(r =>
314        with
315            Tracked(owner): Tracked<&mut VmIoOwner>,
316        requires
317            old(self).inv(),
318            old(self).wf(*old(owner)),
319            old(owner).has_write_view(),
320        ensures
321            final(self).inv(),
322            final(owner).inv(),
323            final(self).wf(*final(owner)),
324            final(owner).has_write_view(),
325            old(self).avail() >= core::mem::size_of::<T>() ==> r is Ok,
326            old(self).avail() < core::mem::size_of::<T>()
327                ==> r == Err(Error::InvalidArgs),
328            match r {
329                Ok(_) => {
330                    &&& final(self).avail() == old(self).avail() - core::mem::size_of::<T>()
331                    &&& final(self).cursor.vaddr == old(self).cursor.vaddr + core::mem::size_of::<T>()
332                },
333                Err(_) => {
334                    &&& *old(self) == *final(self)
335                    &&& *old(owner) == *final(owner)
336                },
337            }
338    )]
339    pub fn write_val<T: Pod>(&mut self, new_val: &T) -> Result<()> {
340        let len = core::mem::size_of::<T>();
341        if self.avail() < len {
342            return Err(Error::InvalidArgs);
343        }
344        proof_decl! {
345            let tracked mut reader_owner_inner: VmIoOwner;
346        }
347        #[verus_spec(with => Tracked(reader_owner_inner))]
348        let mut reader = VmReader::from(new_val.as_bytes());
349        #[verus_spec(with Tracked(owner), Tracked(&mut reader_owner_inner))]
350        let _ = self.write(&mut reader);
351        Ok(())
352    }
353
354    /// Panic condition for [`Self::fill`]: either the cursor isn't aligned
355    /// for `T`, or the available space isn't a multiple of `size_of::<T>()`.
356    pub open spec fn fill_panic_condition<T>(self) -> bool {
357        ||| self.cursor.vaddr as int % core::mem::align_of::<T>() as int != 0
358        ||| (self.end.vaddr - self.cursor.vaddr) % core::mem::size_of::<T>() as int != 0
359    }
360
361    /// Fills the available space by repeatedly writing the same `Pod` value.
362    ///
363    /// Returns the number of elements written.
364    ///
365    /// # Panics
366    /// If cursor isn't aligned for `T`, or `avail()` isn't a multiple of
367    /// `size_of::<T>()` ([`Self::fill_panic_condition`]).
368    #[verus_spec(r =>
369        with
370            Tracked(writer_owner): Tracked<&mut VmIoOwner>,
371                -> reader_owner: Tracked<VmIoOwner>,
372        requires
373            old(self).inv(),
374            old(self).wf(*old(writer_owner)),
375            old(writer_owner).has_write_view(),
376            core::mem::size_of::<T>() > 0,
377            core::mem::align_of::<T>() > 0,
378            core::mem::size_of::<T>() % core::mem::align_of::<T>() == 0,
379            allowed_to_panic_if(old(self).fill_panic_condition::<T>()),
380        ensures
381            final(self).inv(),
382            final(self).wf(*final(writer_owner)),
383            !old(self).fill_panic_condition::<T>(),
384            final(self).cursor == old(self).end,
385            final(self).end == old(self).end,
386            // writer_owner: fully advanced past the filled region.
387            final(writer_owner).range.start == old(writer_owner).range.end,
388            final(writer_owner).range.end == old(writer_owner).range.end,
389            // reader_owner: brand-new ReadView over the filled region.
390            reader_owner@.inv(),
391            reader_owner@.range.start == old(writer_owner).range.start,
392            reader_owner@.range.end == old(writer_owner).range.end,
393            reader_owner@.has_read_view(),
394            reader_owner@.is_kernel == old(writer_owner).is_kernel,
395            // Return value: exactly `avail / size_of::<T>()` elements written.
396            r * core::mem::size_of::<T>() == old(self).avail(),
397    )]
398    pub fn fill<T: Pod>(&mut self, value: T) -> usize {
399        let cursor = self.cursor.cast::<T>();
400        assert!(cursor.is_aligned());
401
402        let avail = self.avail();
403        assert!(avail % core::mem::size_of::<T>() == 0);
404        let len = core::mem::size_of::<T>();
405        let written_num = avail / len;
406        proof {
407            // (avail / len) * len == avail when avail % len == 0 and len > 0.
408            assert(written_num * len == avail) by (nonlinear_arith)
409                requires
410                    len > 0,
411                    avail % len == 0,
412                    written_num == avail / len,
413            ;
414        }
415
416        proof_decl! {
417            let tracked mut reader_owner_inner: VmIoOwner;
418        }
419
420        let tracked mut mv = match writer_owner.mem_view.tracked_take() {
421            VmIoMemView::WriteView(v) => v,
422            _ => { proof_from_false() },
423        };
424        let ghost mv_pre = mv;
425        let ghost start = self.cursor.vaddr;
426        let ghost end = self.end.vaddr;
427        let ghost cursor_range = self.cursor.range@;
428
429        let mut cursor_i: VirtPtr = self.cursor;
430        let mut i: usize = 0;
431        while i < written_num
432            invariant
433                self.inv(),
434                self.cursor.vaddr == start,
435                self.end.vaddr == end,
436                self.cursor.range@ == cursor_range,
437                end - start == avail,
438                avail == written_num * len,
439                len == core::mem::size_of::<T>(),
440                len > 0,
441                core::mem::align_of::<T>() > 0,
442                len % core::mem::align_of::<T>() == 0,
443                start % core::mem::align_of::<T>() == 0,
444                cursor_i.range@ == cursor_range,
445                cursor_i.vaddr == start + i * len,
446                cursor_i.vaddr <= end,
447                cursor_i.vaddr % core::mem::align_of::<T>() == 0,
448                i <= written_num,
449                mv.mappings == mv_pre.mappings,
450                forall|va: usize|
451                    #![trigger mv.addr_transl(va)]
452                    start <= va < end ==> mv.addr_transl(va) is Some,
453            decreases written_num - i,
454        {
455            proof {
456                // (i + 1) * len <= written_num * len, hence cursor_i.vaddr + len <= end
457                assert((i + 1) * len <= written_num * len) by (nonlinear_arith)
458                    requires
459                        i < written_num,
460                        len > 0,
461                ;
462                assert(i * len + len == (i + 1) * len) by (nonlinear_arith);
463                // forall va in [cursor_i.vaddr, cursor_i.vaddr + len), mv.addr_transl is Some
464                assert forall|va: usize|
465                    cursor_i.vaddr <= va < cursor_i.vaddr + len implies #[trigger] mv.addr_transl(
466                    va,
467                ) is Some by {};
468            }
469            // SAFETY: written_num is bounded by avail / size_of::<T>() so each
470            // write targets memory owned by this writer, and cursor is aligned.
471            #[allow(unused_unsafe)]
472            unsafe { cursor_i.write_volatile::<T>(Tracked(&mut mv), value) };
473            cursor_i = cursor_i.wrapping_add(len);
474            i = i + 1;
475            proof {
476                assert((start + i * len) % core::mem::align_of::<T>() as int == 0) by {
477                    let a = core::mem::align_of::<T>() as int;
478                    assert(a > 0);
479                    let q_start = start as int / a;
480                    let q_len = len as int / a;
481                    vstd::arithmetic::div_mod::lemma_fundamental_div_mod(start as int, a);
482                    vstd::arithmetic::div_mod::lemma_fundamental_div_mod(len as int, a);
483                    assert(start as int % a == 0);
484                    assert(len as int % a == 0);
485                    assert((q_start + i * q_len) * a == q_start * a + (i * q_len) * a)
486                        by (nonlinear_arith);
487                    assert((i * q_len) * a == i * (q_len * a)) by (nonlinear_arith);
488                    assert(start as int == q_start * a);
489                    assert(i * (len as int) == (i * q_len) * a);
490                    vstd::arithmetic::div_mod::lemma_mod_multiples_basic(q_start + i * q_len, a);
491                }
492            }
493        }
494
495        proof {
496            writer_owner.mem_view = Some(VmIoMemView::WriteView(mv));
497            // Split off the front of writer_owner (the filled region) as a new
498            // VmIoOwner and convert its WriteView to a ReadView so the caller
499            // can read back what was just written.
500            reader_owner_inner = writer_owner.split(avail);
501            reader_owner_inner.write_to_read();
502        }
503
504        // All available space has been filled; cursor moves to end.
505        self.cursor = self.end;
506        proof_with!(|= Tracked(reader_owner_inner));
507        written_num
508    }
509
510    /// Writes data into `self` by reading from the provided `reader`.
511    ///
512    /// This function treats `self` as the destination buffer. It pulls data *from*
513    /// the source `reader` and writes it into the current instance.
514    ///
515    /// # Arguments
516    ///
517    /// * `reader` - The source `VmReader` to read data from.
518    ///
519    /// # Returns
520    ///
521    /// Returns the number of bytes written to `self` (which is equal to the number of bytes read from `reader`).
522    ///
523    /// # Verified Properties
524    /// ## Preconditions
525    /// - The writer, reader, and both associated owners must satisfy their invariants.
526    /// - The owners must match the given writer and reader.
527    /// - The writer owner must carry a write memory view.
528    /// - The source and destination ranges must not overlap.
529    /// - The reader owner must provide initialized readable memory for the readable range.
530    /// ## Postconditions
531    /// - The writer, reader, and both owners still satisfy their invariants.
532    /// - The owners still match the updated writer and reader.
533    /// - The returned byte count equals the minimum of writable bytes and readable bytes.
534    /// - Both cursors advance by exactly the returned byte count.
535    #[verus_spec(r =>
536        with
537            Tracked(owner_w): Tracked<&mut VmIoOwner>,
538            Tracked(owner_r): Tracked<&mut VmIoOwner>,
539        requires
540            old(self).inv(),
541            old(reader).inv(),
542            old(self).wf(*old(owner_w)),
543            old(reader).wf(*old(owner_r)),
544            old(owner_w).has_write_view(),
545            old(owner_r).read_view_initialized(),
546        ensures
547            final(self).inv(),
548            final(reader).inv(),
549            final(owner_w).inv(),
550            final(owner_r).inv(),
551            final(self).wf(*final(owner_w)),
552            final(reader).wf(*final(owner_r)),
553            r == vstd::math::min(old(self).avail() as int, old(reader).remain() as int),
554            final(self).avail() == old(self).avail() - r as usize,
555            final(self).cursor.vaddr == old(self).cursor.vaddr + r as usize,
556            final(reader).remain() == old(reader).remain() - r as usize,
557            final(reader).cursor.vaddr == old(reader).cursor.vaddr + r as usize,
558            final(owner_w).has_write_view(),
559            final(owner_r).read_view_initialized(),
560    )]
561    pub fn write(&mut self, reader: &mut VmReader<'_, Infallible>) -> usize {
562        proof_decl! {
563            let tracked mut _discarded_consumed_w: VmIoOwner;
564        }
565        #[verus_spec(with Tracked(owner_r), Tracked(owner_w) => Tracked(_discarded_consumed_w))]
566        reader.read(self)
567    }
568
569    /// Writes a value of the `PodOnce` type using one non-tearing memory store.
570    ///
571    /// If the length of the `PodOnce` type exceeds `self.avail()`, this method will return `Err`.
572    ///
573    /// # Panics
574    ///
575    /// This method will panic if the current position of the writer does not meet the alignment
576    /// requirements of type `T`.
577    ///
578    /// # Verified Properties
579    /// ## Preconditions
580    /// - The writer and its owner must satisfy their invariants.
581    /// - The owner must match this writer and carry a write memory view.
582    /// - Every byte in the writable range must translate in the write view.
583    /// ## Postconditions
584    /// - The writer and owner still satisfy their invariants.
585    /// - On success, the cursor advances by `size_of::<T>()` and the cursor was
586    ///   aligned to `align_of::<T>()` (the runtime `assert!` would otherwise diverge).
587    /// - On error, the writer state is unchanged.
588    #[verus_spec(r =>
589        with
590            Tracked(owner): Tracked<&mut VmIoOwner>,
591        requires
592            old(self).inv(),
593            old(self).wf(*old(owner)),
594            old(owner).has_write_view(),
595            // The runtime `assert!(cursor.is_aligned())` diverges unless the
596            // cursor is aligned for `T`.
597            allowed_to_panic_if(old(self).cursor.vaddr % core::mem::align_of::<T>() != 0),
598        ensures
599            final(self).inv(),
600            final(owner).inv(),
601            final(self).wf(*final(owner)),
602            match r {
603                Ok(_) => {
604                    &&& old(self).cursor.vaddr % core::mem::align_of::<T>() == 0
605                    &&& final(self).avail() == old(self).avail() - core::mem::size_of::<T>()
606                    &&& final(self).cursor.vaddr == old(self).cursor.vaddr + core::mem::size_of::<T>()
607                },
608                Err(_) => {
609                    *old(self) == *final(self)
610                },
611            }
612    )]
613    pub fn write_once<T: PodOnce>(&mut self, new_val: &T) -> Result<()> {
614        if self.avail() < core::mem::size_of::<T>() {
615            return Err(Error::InvalidArgs);
616        }
617        let cursor = self.cursor.cast::<T>();
618        assert!(cursor.is_aligned());
619
620        // NOTE: vostd has `const { assert!(pod_once_impls::is_non_tearing::<T>()) };` here, but
621        // verus doesn't yet support const block expressions. The non-tearing guarantee for our
622        // `PodOnce` impls is restricted to types of size 1/2/4/8 by convention.
623
624        // SAFETY: We have checked that the number of bytes available is at least the size of `T`
625        // and that the cursor is properly aligned with respect to the type `T`. All other safety
626        // requirements are the same as for `Self::write`.
627
628        let len = core::mem::size_of::<T>();
629        let tracked mut mem_dst = match owner.mem_view.tracked_take() {
630            VmIoMemView::WriteView(mv) => mv,
631            _ => { proof_from_false() },
632        };
633
634        proof {
635            assert forall|i: usize|
636                #![trigger mem_dst.addr_transl(i)]
637                self.cursor.vaddr <= i < self.cursor.vaddr + core::mem::size_of::<T>() implies {
638                mem_dst.addr_transl(i) is Some
639            } by {}
640        }
641        #[allow(unused_unsafe)]
642        unsafe { self.cursor.write_volatile::<T>(Tracked(&mut mem_dst), *new_val) };
643
644        self.cursor = self.cursor.wrapping_add(len);
645
646        proof {
647            owner.mem_view = Some(VmIoMemView::WriteView(mem_dst));
648
649            assert forall|va| owner.range.start <= va < owner.range.end implies mem_dst.addr_transl(
650                va,
651            ) is Some by {}
652
653            owner.advance(len);
654        }
655
656        Ok(())
657    }
658}
659
660impl<Fallibility> Clone for VmReader<'_, Fallibility> {
661    /// [`Clone`] can be implemented for [`VmReader`]
662    /// because it either points to untyped memory or represents immutable references.
663    ///
664    /// Note that we cannot implement [`Clone`] for [`VmWriter`]
665    /// because it can represent mutable references, which must remain exclusive.
666    fn clone(&self) -> Self {
667        Self { ghost_id: self.ghost_id, cursor: self.cursor, end: self.end, phantom: PhantomData }
668    }
669}
670
671#[verus_verify]
672impl<'a> VmReader<'a, Infallible> {
673    /// Constructs a [`VmReader`] from a pointer and a length, which represents
674    /// a memory range in kernel space.
675    ///
676    /// # Verified Properties
677    /// ## Preconditions
678    /// - The memory region represented by `ptr` and `len` must be valid for reads of `len` bytes
679    ///   during the entire lifetime `a`. This means that the underlying pages must remain alive,
680    ///   and the kernel must access the memory region using only the APIs provided in this module.
681    /// - The range `ptr.vaddr..ptr.vaddr + len` must represent a kernel space memory range.
682    /// ## Postconditions
683    /// - An infallible [`VmReader`] will be created with the range `ptr.vaddr..ptr.vaddr + len`.
684    /// - The created [`VmReader`] will have a unique identifier `id`, and its cursor will be
685    ///   initialized to `ptr`.
686    /// - The created [`VmReader`] will be associated with a [`VmIoOwner`] that has the same `id`,
687    ///   the same memory range, and is marked as kernel space and infallible.
688    /// ## Safety
689    ///
690    /// `ptr` must be [valid] for reads of `len` bytes during the entire lifetime `a`.
691    ///
692    /// [valid]: crate::mm::io#safety
693    #[verus_spec(r =>
694        with
695            Ghost(id): Ghost<nat>,
696            -> owner: Tracked<VmIoOwner>,
697        ensures
698            r.inv_wf(),
699            owner@.id == id,
700            owner@.is_kernel,
701            r.cursor == ptr,
702            r.end == ptr.wrapping_add_spec(len),
703            r.cursor.range@ == ptr.range@,
704            r.end.range@ == ptr.range@,
705            ptr.inv() && ptr.range@.start == ptr.vaddr
706                && len == ptr.range@.end - ptr.range@.start
707                && (len == 0 || KERNEL_BASE_VADDR <= ptr.vaddr)
708                && (len == 0 || ptr.vaddr + len <= KERNEL_END_VADDR) ==> {
709                &&& r.inv()
710                &&& owner@.inv()
711                &&& r.wf(owner@)
712                &&& owner@.read_view_initialized()
713            },
714    )]
715    pub unsafe fn from_kernel_space(ptr: VirtPtr, len: usize) -> Self {
716        let ghost range: Range<usize> = ptr.vaddr..(ptr.vaddr + len) as usize;
717        let tracked mv = axiom_kernel_mem_view(range);
718        let tracked owner = VmIoOwner {
719            id,
720            range,
721            is_fallible: false,
722            is_kernel: true,
723            mem_view: Some(VmIoMemView::ReadView(mv)),
724        };
725
726        proof_with!(|= Tracked(owner));
727        Self { ghost_id: Ghost(id), cursor: ptr, end: ptr.wrapping_add(len), phantom: PhantomData }
728    }
729
730    /// Converts an infallible reader into a fallible one.
731    pub fn to_fallible(self) -> (r: VmReader<'a, Fallible>)
732        requires
733            self.inv(),
734        ensures
735            r.inv(),
736            r.remain() == self.remain(),
737            r.cursor == self.cursor,
738            r.end == self.end,
739            r.ghost_id == self.ghost_id,
740    {
741        VmReader {
742            ghost_id: self.ghost_id,
743            cursor: self.cursor,
744            end: self.end,
745            phantom: PhantomData,
746        }
747    }
748
749    /// Reads data from `self` and writes it into the provided `writer`.
750    ///
751    /// This function acts as the source side of a transfer. It copies data from
752    /// the current instance (`self`) into the destination `writer`, up to the limit
753    /// of available data in `self` or available space in `writer` (whichever is smaller).
754    ///
755    /// # Logic
756    ///
757    /// 1. Calculates the copy length: `min(self.remaining_data, writer.available_space)`.
758    /// 2. Copies bytes from `self`'s internal buffer to `writer`'s buffer.
759    /// 3. Advances the cursors of both `self` and `writer`.
760    ///
761    /// # Arguments
762    ///
763    /// * `writer` - The destination `VmWriter` where the data will be copied to.
764    ///
765    /// # Returns
766    ///
767    /// The number of bytes actually transferred.
768    ///
769    /// # Verified Properties
770    /// ## Preconditions
771    /// - The reader, writer, and both associated owners must satisfy their invariants.
772    /// - The owners must match the given reader and writer.
773    /// - The writer owner must carry a write memory view.
774    /// - The source and destination ranges must not overlap.
775    /// - The reader owner must provide initialized readable memory for the readable range.
776    /// ## Postconditions
777    /// - The reader, writer, and both owners still satisfy their invariants.
778    /// - The owners still match the updated reader and writer.
779    /// - The returned byte count equals the minimum of readable bytes and writable bytes.
780    /// - Both cursors advance by exactly the returned byte count.
781    /// - `consumed_w` is the just-written portion of the writer's owner, covering
782    ///   `[old(owner_w).range@.start, old(owner_w).range@.start + r)`.
783    #[verus_spec(r =>
784        with
785            Tracked(owner_r): Tracked<&mut VmIoOwner>,
786            Tracked(owner_w): Tracked<&mut VmIoOwner>,
787                -> consumed_w: Tracked<VmIoOwner>,
788        requires
789            old(self).inv(),
790            old(writer).inv(),
791            old(self).wf(*old(owner_r)),
792            old(writer).wf(*old(owner_w)),
793            old(owner_w).has_write_view(),
794            old(owner_r).read_view_initialized(),
795        ensures
796            final(self).inv(),
797            final(writer).inv(),
798            final(self).wf(*final(owner_r)),
799            final(writer).wf(*final(owner_w)),
800            r == vstd::math::min(old(self).remain() as int, old(writer).avail() as int),
801            final(self).remain() == old(self).remain() - r as usize,
802            final(self).cursor.vaddr == old(self).cursor.vaddr + r as usize,
803            final(writer).avail() == old(writer).avail() - r as usize,
804            final(writer).cursor.vaddr == old(writer).cursor.vaddr + r as usize,
805            consumed_w@.inv(),
806            consumed_w@.range.start == old(owner_w).range.start,
807            consumed_w@.range.end == old(owner_w).range.start + r as usize,
808            consumed_w@.has_write_view(),
809            final(owner_w).has_write_view(),
810            final(owner_r).read_view_initialized(),
811    )]
812    pub fn read(&mut self, writer: &mut VmWriter<'_, Infallible>) -> usize {
813        let copy_len = self.remain().min(writer.avail());
814        proof_decl! {
815            let tracked mut consumed_w_owner_inner: VmIoOwner;
816        }
817        if copy_len == 0 {
818            proof {
819                consumed_w_owner_inner = owner_w.split(0);
820            }
821            proof_with!(|= Tracked(consumed_w_owner_inner));
822            0
823        } else {
824            let tracked mv_r = match owner_r.mem_view.tracked_take() {
825                VmIoMemView::ReadView(mv) => mv,
826                _ => { proof_from_false() },
827            };
828            let tracked mut mv_w = match owner_w.mem_view.tracked_take() {
829                VmIoMemView::WriteView(mv) => mv,
830                _ => { proof_from_false() },
831            };
832            let ghost mv_w_pre = mv_w;
833
834            proof {
835                assert forall|i: usize|
836                    #![trigger mv_r.addr_transl(i)]
837                    self.cursor.vaddr <= i < self.cursor.vaddr + copy_len implies {
838                    &&& mv_r.addr_transl(i) is Some
839                    &&& mv_r.memory.contains_key(mv_r.addr_transl(i).unwrap().0)
840                    &&& mv_r.memory[mv_r.addr_transl(i).unwrap().0].contents[mv_r.addr_transl(
841                        i,
842                    ).unwrap().1 as int] is Init
843                } by {}
844            }
845            // SAFETY: The source and destination are subsets of memory ranges specified by the
846            // reader and writer, so they are valid for reading and writing.
847            unsafe {
848                #[verus_spec(with Tracked(&mv_r), Tracked(&mut mv_w))]
849                memcpy(writer.cursor, self.cursor, copy_len)
850            };
851
852            self.cursor = self.cursor.wrapping_add(copy_len);
853            writer.cursor = writer.cursor.wrapping_add(copy_len);
854
855            proof {
856                owner_w.mem_view = Some(VmIoMemView::WriteView(mv_w));
857                owner_r.mem_view = Some(VmIoMemView::ReadView(mv_r));
858
859                assert forall|va|
860                    owner_w.range.start <= va < owner_w.range.end implies mv_w.addr_transl(
861                    va,
862                ) is Some by {
863                    assert(mv_w.addr_transl(va) == mv_w_pre.addr_transl(va));
864                }
865
866                consumed_w_owner_inner = owner_w.split(copy_len);
867                owner_r.advance(copy_len);
868            }
869            proof_with!(|= Tracked(consumed_w_owner_inner));
870            copy_len
871        }
872    }
873
874    /// Reads a value of `Pod` type.
875    ///
876    /// If the length of the `Pod` type exceeds `self.remain()`,
877    /// this method will return `Err`.
878    ///
879    /// # Verified Properties
880    /// ## Preconditions
881    /// - The reader and its owner must satisfy their invariants.
882    /// - The owner must match this reader and carry an initialized read memory view.
883    /// ## Postconditions
884    /// - The reader and its owner still satisfy their invariants.
885    /// - On success, the cursor advances by `size_of::<T>()`; the returned value's
886    ///   byte contents are not pinned by the current model.
887    /// - On error, the reader and owner states are unchanged.
888    #[verus_spec(r =>
889        with
890            Tracked(owner): Tracked<&mut VmIoOwner>,
891        requires
892            old(self).inv(),
893            old(self).wf(*old(owner)),
894            old(owner).read_view_initialized(),
895        ensures
896            final(self).inv(),
897            final(owner).inv(),
898            final(self).wf(*final(owner)),
899            final(owner).read_view_initialized(),
900            old(self).remain() >= core::mem::size_of::<T>() ==> r is Ok,
901            old(self).remain() < core::mem::size_of::<T>()
902                ==> r == Err(Error::InvalidArgs),
903            match r {
904                Ok(_) => {
905                    &&& final(self).remain() == old(self).remain() - core::mem::size_of::<T>()
906                    &&& final(self).cursor.vaddr == old(self).cursor.vaddr + core::mem::size_of::<T>()
907                },
908                Err(_) => {
909                    &&& *old(self) == *final(self)
910                    &&& *old(owner) == *final(owner)
911                },
912            }
913    )]
914    pub fn read_val<T: Pod>(&mut self) -> Result<T> {
915        let len = core::mem::size_of::<T>();
916        if self.remain() < len {
917            Err(Error::InvalidArgs)
918        } else {
919            let mut val = T::new_uninit();
920            proof_decl! {
921                let tracked mut writer_owner_inner: VmIoOwner;
922            }
923            #[verus_spec(with => Tracked(writer_owner_inner))]
924            let mut writer = VmWriter::from(val.as_bytes_mut());
925            #[verus_spec(with Tracked(owner), Tracked(&mut writer_owner_inner))]
926            let _ = self.read(&mut writer);
927            Ok(val)
928        }
929    }
930
931    /// Reads a value of the `PodOnce` type using one non-tearing memory load.
932    ///
933    /// If the length of the `PodOnce` type exceeds `self.remain()`, this method will return `Err`.
934    ///
935    /// This method will not compile if the `Pod` type is too large for the current architecture
936    /// and the operation must be tear into multiple memory loads.
937    ///
938    /// # Panics
939    ///
940    /// This method will panic if the current position of the reader does not meet the alignment
941    /// requirements of type `T`.
942    ///
943    /// # Verified Properties
944    /// ## Preconditions
945    /// - The reader and its owner must satisfy their invariants.
946    /// - The owner must match this reader and carry a read memory view.
947    /// - The readable range must translate to initialized bytes in the read view.
948    /// ## Postconditions
949    /// - The reader and owner still satisfy their invariants.
950    /// - On success, the cursor advances by `size_of::<T>()` and the cursor was
951    ///   aligned to `align_of::<T>()` (the runtime `assert!` would otherwise diverge).
952    /// - On error, the reader state is unchanged.
953    #[verus_spec(r =>
954        with
955            Tracked(owner): Tracked<&mut VmIoOwner>,
956        requires
957            old(self).inv(),
958            old(self).wf(*old(owner)),
959            old(owner).read_view_initialized(),
960            allowed_to_panic_if(old(self).cursor.vaddr % core::mem::align_of::<T>() != 0),
961        ensures
962            final(self).inv(),
963            final(owner).inv(),
964            final(self).wf(*final(owner)),
965            final(owner).read_view_initialized(),
966            old(self).remain() >= core::mem::size_of::<T>() ==> r is Ok,
967            old(self).remain() < core::mem::size_of::<T>()
968                ==> r == Err(Error::InvalidArgs),
969            final(self).end == old(self).end,
970            final(self).ghost_id == old(self).ghost_id,
971            match r {
972                Ok(v) => {
973                    &&& old(self).cursor.vaddr % core::mem::align_of::<T>() == 0
974                    &&& final(self).remain() == old(self).remain() - core::mem::size_of::<T>()
975                    &&& final(self).cursor.vaddr == old(self).cursor.vaddr + core::mem::size_of::<T>()
976                    &&& ostd_pod::pod_bytes::<T>(v)
977                        == crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner))
978                            .read_bytes(old(self).cursor.vaddr, core::mem::size_of::<T>())
979                    &&& forall|va: usize|
980                        #![trigger crate::specs::mm::io::VmIoOwner::read_view_of(*final(owner)).read(va)]
981                        final(self).cursor.vaddr <= va < old(self).end.vaddr
982                        && crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner)).addr_transl(va) is Some
983                        && crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner)).memory.contains_key(
984                            (crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner)).addr_transl(va)->0).0
985                        ) ==> {
986                            &&& crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner)).addr_transl(va)
987                                == crate::specs::mm::io::VmIoOwner::read_view_of(*final(owner)).addr_transl(va)
988                            &&& crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner)).read(va)
989                                == crate::specs::mm::io::VmIoOwner::read_view_of(*final(owner)).read(va)
990                        }
991                },
992                Err(_) => {
993                    &&& *old(self) == *final(self)
994                    &&& *old(owner) == *final(owner)
995                },
996            }
997    )]
998    pub fn read_once<T: PodOnce>(&mut self) -> Result<T> {
999        if self.remain() < core::mem::size_of::<T>() {
1000            return Err(Error::InvalidArgs);
1001        }
1002        let cursor = self.cursor.cast::<T>();
1003        assert!(cursor.is_aligned());
1004
1005        // NOTE: vostd has `const { assert!(pod_once_impls::is_non_tearing::<T>()) };` here, but
1006        // verus doesn't yet support const block expressions. The non-tearing guarantee for our
1007        // `PodOnce` impls is restricted to types of size 1/2/4/8 by convention.
1008
1009        // SAFETY: We have checked that the number of bytes remaining is at least the size of `T`
1010        // and that the cursor is properly aligned with respect to the type `T`. All other safety
1011        // requirements are the same as for `Self::read`.
1012
1013        let tracked mem_src = owner.tracked_read_view_unwrap();
1014        proof {
1015            assert forall|i: usize|
1016                #![trigger mem_src.addr_transl(i)]
1017                self.cursor.vaddr <= i < self.cursor.vaddr + core::mem::size_of::<T>() implies {
1018                &&& mem_src.addr_transl(i) is Some
1019                &&& mem_src.memory.contains_key(mem_src.addr_transl(i).unwrap().0)
1020                &&& mem_src.memory[mem_src.addr_transl(i).unwrap().0].contents[mem_src.addr_transl(
1021                    i,
1022                ).unwrap().1 as int] is Init
1023            } by {}
1024        }
1025        #[allow(unused_unsafe)]
1026        let val = unsafe { self.cursor.read_volatile::<T>(Tracked(mem_src)) };
1027        self.cursor = self.cursor.wrapping_add(core::mem::size_of::<T>());
1028
1029        proof {
1030            owner.advance(core::mem::size_of::<T>());
1031        }
1032
1033        Ok(val)
1034    }
1035}
1036
1037#[verus_verify]
1038impl<'a> VmReader<'a, Fallible> {
1039    /// Constructs a [`VmReader`] from a pointer and a length, which represents
1040    /// a memory range in USER space.
1041    ///
1042    /// # Verified Properties
1043    /// ## Preconditions
1044    /// - `ptr` must satisfy [`VirtPtr::inv`].
1045    /// ## Postconditions
1046    /// - The returned [`VmReader`] satisfies its invariant.
1047    /// - The returned reader is associated with a [`VmIoOwner`] that satisfies both [`VmIoOwner::inv`]
1048    ///   and [`VmReader::wf`].
1049    /// - The owner has the same range as `ptr`, has no memory view yet, and is marked as user-space.
1050    #[verus_spec(r =>
1051        with
1052            Ghost(id): Ghost<nat>,
1053            -> owner: Tracked<VmIoOwner>,
1054        ensures
1055            r.inv_wf(),
1056            owner@.id == id,
1057            owner@.range == ptr.range@,
1058            owner@.mem_view is None,
1059            !owner@.is_kernel,
1060            r.cursor == ptr,
1061            r.end == ptr.wrapping_add_spec(len),
1062            r.end.range@ == ptr.range@,
1063            ptr.inv() && ptr.range@.start == ptr.vaddr
1064                && len == ptr.range@.end - ptr.range@.start ==> {
1065                &&& r.inv()
1066                &&& owner@.inv()
1067                &&& r.wf(owner@)
1068            },
1069    )]
1070    pub unsafe fn from_user_space(ptr: VirtPtr, len: usize) -> Self {
1071        let tracked owner = VmIoOwner {
1072            id,
1073            range: ptr.range@,
1074            is_fallible: true,
1075            is_kernel: false,
1076            mem_view: None,
1077        };
1078        proof_with!(|= Tracked(owner));
1079        Self { ghost_id: Ghost(id), cursor: ptr, end: ptr.wrapping_add(len), phantom: PhantomData }
1080    }
1081
1082    /// Reads a value of `Pod` type from a (potentially) user-space buffer.
1083    ///
1084    /// If the length of the `Pod` type exceeds `self.remain()`, or the value
1085    /// can not be read completely (e.g. due to a page fault), this method
1086    /// returns `Err` and the reader's cursor is rolled back to its original
1087    /// position.
1088    #[verus_spec(r =>
1089        requires
1090            old(self).inv(),
1091        ensures
1092            final(self).inv(),
1093            final(self).end == old(self).end,
1094            final(self).ghost_id == old(self).ghost_id,
1095            final(self).cursor.range == old(self).cursor.range,
1096            old(self).remain() < core::mem::size_of::<T>()
1097                ==> r == Err(Error::InvalidArgs),
1098            match r {
1099                Ok(_) => {
1100                    &&& final(self).remain() == old(self).remain() - core::mem::size_of::<T>()
1101                    &&& final(self).cursor.vaddr == old(self).cursor.vaddr + core::mem::size_of::<T>()
1102                },
1103                Err(_) => *final(self) == *old(self),
1104            },
1105    )]
1106    pub fn read_val<T: Pod>(&mut self) -> Result<T> {
1107        let len = core::mem::size_of::<T>();
1108        if self.remain() < len {
1109            Err(Error::InvalidArgs)
1110        } else {
1111            let mut val = T::new_uninit();
1112            proof_decl! {
1113                let tracked mut writer_owner_inner: VmIoOwner;
1114            }
1115            #[verus_spec(with => Tracked(writer_owner_inner))]
1116            let mut writer = VmWriter::from(val.as_bytes_mut());
1117
1118            match self.read_fallible(&mut writer) {
1119                Ok(_) => Ok(val),
1120                Err((err, copied_len)) => {
1121                    self.cursor = self.cursor.sub(copied_len);
1122                    Err(err)
1123                },
1124            }
1125        }
1126    }
1127
1128    /// Collects all the remaining bytes into a `Vec<u8>`.
1129    ///
1130    /// If the memory read failed, this method will return `Err`
1131    /// and the current reader's cursor remains pointing to
1132    /// the original starting position.
1133    ///
1134    /// The destination buffer is allocated fresh inside this function. The
1135    /// kernel-space precondition for the resulting `VmWriter` is discharged
1136    /// via [`axiom_slice_in_kernel`] — the natural trust boundary where a
1137    /// native Rust slice meets the tracked-memory model.
1138    #[verus_spec(r =>
1139        requires
1140            old(self).inv(),
1141        ensures
1142            final(self).inv(),
1143            final(self).end == old(self).end,
1144            final(self).ghost_id == old(self).ghost_id,
1145            final(self).cursor.range == old(self).cursor.range,
1146            r matches Ok(collected) ==> collected.len() == old(self).remain(),
1147            r is Err ==> *final(self) == *old(self),
1148    )]
1149    pub fn collect(&mut self) -> Result<alloc::vec::Vec<u8>> {
1150        let len = self.remain();
1151        let mut buf = alloc::vec![0u8; len];
1152
1153        let ptr = {
1154            let slice: &[u8] = buf.as_slice();
1155            let ptr = slice.as_virt_ptr();
1156            proof {
1157                axiom_slice_in_kernel(slice);
1158            }
1159            ptr
1160        };
1161        proof_decl! {
1162            let tracked mut owner: VmIoOwner;
1163        }
1164        let mut writer = unsafe {
1165            #[verus_spec(with Ghost(0nat), Tracked(false) => Tracked(owner))]
1166            VmWriter::from_kernel_space(ptr, len)
1167        };
1168        match self.read_fallible(&mut writer) {
1169            Ok(_) => Ok(buf),
1170            Err((err, copied_len)) => {
1171                self.cursor = self.cursor.sub(copied_len);
1172                Err(err)
1173            },
1174        }
1175    }
1176}
1177
1178type Result<T> = core::result::Result<T, Error>;
1179
1180/// A trait that enables reading/writing data from/to a VM object,
1181/// e.g., [`USegment`], [`Vec<UFrame>`] and [`UFrame`].
1182///
1183/// # Concurrency
1184///
1185/// The methods may be executed by multiple concurrent reader and writer
1186/// threads. In this case, if the results of concurrent reads or writes
1187/// desire predictability or atomicity, the users should add extra mechanism
1188/// for such properties.
1189///
1190/// [`USegment`]: crate::mm::USegment
1191/// [`UFrame`]: crate::mm::UFrame
1192///
1193/// Note: In this trait we follow the standard of `vstd` trait that allows precondition and
1194/// postcondition overriding by introducing `obeys_`, `_requires`, and `_ensures` spec functions.
1195///
1196/// `P` is the type of the permission/ownership token used to track the state of the VM object.
1197pub trait VmIo<P: Sized>: Send + Sync + Sized {
1198    spec fn obeys_vmio_spec() -> bool;
1199
1200    open spec fn obeys_vmio_read_requires() -> bool {
1201        false
1202    }
1203
1204    open spec fn obeys_vmio_write_requires() -> bool {
1205        false
1206    }
1207
1208    spec fn obeys_vmio_read_spec() -> bool;
1209
1210    spec fn obeys_vmio_write_spec() -> bool;
1211
1212    open spec fn read_requires(
1213        self,
1214        offset: usize,
1215        writer: VmWriter<'_>,
1216        writer_own: VmIoOwner,
1217        owner: P,
1218    ) -> bool {
1219        true
1220    }
1221
1222    open spec fn write_requires(
1223        self,
1224        offset: usize,
1225        reader: VmReader<'_>,
1226        reader_own: VmIoOwner,
1227        owner: P,
1228    ) -> bool {
1229        true
1230    }
1231
1232    spec fn read_spec(
1233        self,
1234        offset: usize,
1235        old_writer: VmWriter<'_>,
1236        new_writer: VmWriter<'_>,
1237        old_writer_own: VmIoOwner,
1238        new_writer_own: VmIoOwner,
1239        old_owner: P,
1240        new_owner: P,
1241        r: Result<()>,
1242    ) -> bool;
1243
1244    spec fn write_spec(
1245        self,
1246        offset: usize,
1247        old_reader: VmReader<'_>,
1248        new_reader: VmReader<'_>,
1249        old_writer_own: VmIoOwner,
1250        new_writer_own: VmIoOwner,
1251        old_owner: P,
1252        new_owner: P,
1253        r: Result<()>,
1254    ) -> bool;
1255
1256    /// Reads requested data at a specified offset into a given [`VmWriter`].
1257    ///
1258    /// # No short reads
1259    ///
1260    /// On success, the `writer` must be written with the requested data
1261    /// completely. If, for any reason, the requested data is only partially
1262    /// available, then the method shall return an error.
1263    fn read(
1264        &self,
1265        offset: usize,
1266        writer: &mut VmWriter<'_>,
1267        Tracked(writer_own): Tracked<&mut VmIoOwner>,
1268        Tracked(owner): Tracked<&mut P>,
1269    ) -> (r: Result<()>)
1270        requires
1271            Self::obeys_vmio_read_requires() ==> Self::read_requires(
1272                *self,
1273                offset,
1274                *old(writer),
1275                *old(writer_own),
1276                *old(owner),
1277            ),
1278        ensures
1279            Self::obeys_vmio_read_spec() ==> Self::read_spec(
1280                *self,
1281                offset,
1282                *old(writer),
1283                *final(writer),
1284                *old(writer_own),
1285                *final(writer_own),
1286                *old(owner),
1287                *final(owner),
1288                r,
1289            ),
1290    ;
1291
1292    /// Writes all data from a given `VmReader` at a specified offset.
1293    ///
1294    /// # No short writes
1295    ///
1296    /// On success, the data from the `reader` must be read to the VM object entirely.
1297    /// If, for any reason, the input data can only be written partially,
1298    /// then the method shall return an error.
1299    fn write(
1300        &self,
1301        offset: usize,
1302        reader: &mut VmReader,
1303        Tracked(writer_own): Tracked<&mut VmIoOwner>,
1304        Tracked(owner): Tracked<&mut P>,
1305    ) -> (r: Result<()>)
1306        requires
1307            Self::obeys_vmio_write_requires() ==> Self::write_requires(
1308                *self,
1309                offset,
1310                *old(reader),
1311                *old(writer_own),
1312                *old(owner),
1313            ),
1314        ensures
1315            Self::obeys_vmio_write_spec() ==> Self::write_spec(
1316                *self,
1317                offset,
1318                *old(reader),
1319                *final(reader),
1320                *old(writer_own),
1321                *final(writer_own),
1322                *old(owner),
1323                *final(owner),
1324                r,
1325            ),
1326    ;
1327
1328    /// Reads a specified number of bytes at a specified offset into a given buffer.
1329    ///
1330    /// Wraps `buf` in a [`VmWriter`] (whose tracked owner is minted internally
1331    /// from the slice via [`VmWriter::from`]) and delegates to [`Self::read`].
1332    /// The shallow contract here only forwards the result; impls with non-trivial
1333    /// `read_requires` must override.
1334    fn read_bytes(&self, offset: usize, buf: &mut [u8], Tracked(owner): Tracked<&mut P>) -> (r:
1335        Result<()>)
1336        requires
1337            !Self::obeys_vmio_read_requires(),
1338    {
1339        proof_decl! {
1340            let tracked mut writer_own_inner: VmIoOwner;
1341        }
1342        #[verus_spec(with => Tracked(writer_own_inner))]
1343        let infallible_writer = VmWriter::from(buf);
1344        let mut writer = infallible_writer.to_fallible();
1345        self.read(offset, &mut writer, Tracked(&mut writer_own_inner), Tracked(owner))
1346    }
1347
1348    /// Reads a value of a specified type at a specified offset.
1349    fn read_val<T: Pod>(&self, offset: usize, Tracked(owner): Tracked<&mut P>) -> (r: Result<T>)
1350        requires
1351            !Self::obeys_vmio_read_requires(),
1352    {
1353        let mut val = T::new_uninit();
1354        match self.read_bytes(offset, val.as_bytes_mut(), Tracked(owner)) {
1355            Ok(_) => Ok(val),
1356            Err(e) => Err(e),
1357        }
1358    }
1359
1360    /// Reads a slice of a specified type at a specified offset.
1361    fn read_slice<T: Pod>(
1362        &self,
1363        offset: usize,
1364        slice: &mut [T],
1365        Tracked(owner): Tracked<&mut P>,
1366    ) -> (r: Result<()>)
1367        requires
1368            !Self::obeys_vmio_read_requires(),
1369    {
1370        let len_in_bytes = core::mem::size_of_val(slice);
1371        let ptr = slice.as_mut_ptr() as *mut u8;
1372        // SAFETY: the slice can be transmuted to a writable byte slice since
1373        // the elements are all Plain-Old-Data (Pod) types.
1374        let buf = unsafe { core::slice::from_raw_parts_mut(ptr, len_in_bytes) };
1375        self.read_bytes(offset, buf, Tracked(owner))
1376    }
1377
1378    /// Writes a specified number of bytes from a given buffer at a specified offset.
1379    ///
1380    /// Wraps `buf` in a [`VmReader`] (whose tracked owner is minted internally
1381    /// from the slice via [`VmReader::from`]) and delegates to [`Self::write`].
1382    /// The shallow contract here only forwards the result; impls with non-trivial
1383    /// `write_requires` must override.
1384    fn write_bytes(&self, offset: usize, buf: &[u8], Tracked(owner): Tracked<&mut P>) -> (r: Result<
1385        (),
1386    >)
1387        requires
1388            !Self::obeys_vmio_write_requires(),
1389    {
1390        proof_decl! {
1391            let tracked mut reader_own_inner: VmIoOwner;
1392        }
1393        #[verus_spec(with => Tracked(reader_own_inner))]
1394        let infallible_reader = VmReader::from(buf);
1395        let mut reader = infallible_reader.to_fallible();
1396        self.write(offset, &mut reader, Tracked(&mut reader_own_inner), Tracked(owner))
1397    }
1398
1399    /// Writes a value of a specified type at a specified offset.
1400    fn write_val<T: Pod>(&self, offset: usize, new_val: &T, Tracked(owner): Tracked<&mut P>) -> (r:
1401        Result<()>)
1402        requires
1403            !Self::obeys_vmio_write_requires(),
1404    {
1405        self.write_bytes(offset, new_val.as_bytes(), Tracked(owner))
1406    }
1407
1408    /// Writes a slice of a specified type at a specified offset.
1409    fn write_slice<T: Pod>(
1410        &self,
1411        offset: usize,
1412        slice: &[T],
1413        Tracked(owner): Tracked<&mut P>,
1414    ) -> (r: Result<()>)
1415        requires
1416            !Self::obeys_vmio_write_requires(),
1417    {
1418        let len_in_bytes = core::mem::size_of_val(slice);
1419        let ptr = slice.as_ptr() as *const u8;
1420        // SAFETY: the slice can be transmuted to a readable byte slice since
1421        // the elements are all Plain-Old-Data (Pod) types.
1422        let buf = unsafe { core::slice::from_raw_parts(ptr, len_in_bytes) };
1423        self.write_bytes(offset, buf, Tracked(owner))
1424    }
1425
1426    /// Writes a sequence of values given by an iterator (`iter`) from the
1427    /// specified offset (`offset`).
1428    ///
1429    /// Stops on iterator exhaustion or write error. Returns `Ok(nr_written)`
1430    /// if at least one value was written; only the first-call error path
1431    /// surfaces as `Err`.
1432    ///
1433    /// `align` rounds the offset and item size up: `0`/`1` means no padding,
1434    /// otherwise must be a power of two. Bad `align` panics at runtime — this
1435    /// is captured as a *post-condition*, not a pre-condition, since the panic
1436    /// is what enforces it.
1437    ///
1438    /// Preconditions left for the caller:
1439    /// - `offset + (align - 1)` and `size_of::<T>() + (align - 1)` don't overflow
1440    ///   (so the post-panic call to `align_up` is safe).
1441    /// - The supplied iterator obeys Verus' prophetic iterator laws and provides
1442    ///   a `decrease` measure (true for slice iterators, `repeat_n`, and the
1443    ///   stdlib iterator combinators ostd uses).
1444    /// - `self`'s impl has no custom `write_requires` (use the override route
1445    ///   for impls that do).
1446    fn write_vals<
1447        'a,
1448        T: Pod + 'a,
1449        I: ::vstd::std_specs::iter::IteratorSpec<Item = &'a T> + Iterator<Item = &'a T>,
1450    >(&self, offset: usize, iter: I, align: usize, Tracked(owner): Tracked<&mut P>) -> (r: Result<
1451        usize,
1452    >)
1453        requires
1454            !Self::obeys_vmio_write_requires(),
1455            offset + align <= usize::MAX,
1456            core::mem::size_of::<T>() + align <= usize::MAX,
1457            iter.obeys_prophetic_iter_laws(),
1458            iter.decrease() is Some,
1459            // `align_up` (called for `align > 1`) diverges unless `align`
1460            // is a power of two.
1461            allowed_to_panic_if(!(align <= 1 || is_pow2(align as int))),
1462        ensures
1463            align <= 1 || is_pow2(align as int),
1464    {
1465        use ::align_ext::AlignExt;
1466        let mut nr_written: usize = 0;
1467        // `align_up` itself panics on invalid `align`, so reaching the post-`else`
1468        // statements gives us the post-condition for free.
1469        let (mut offset, item_size) = if align <= 1 {
1470            (offset, core::mem::size_of::<T>())
1471        } else {
1472            (offset.align_up(align), core::mem::size_of::<T>().align_up(align))
1473        };
1474        let mut iter = iter;
1475        loop
1476            invariant
1477                !Self::obeys_vmio_write_requires(),
1478                iter.obeys_prophetic_iter_laws(),
1479                iter.decrease() is Some,
1480                align == 0 || align == 1 || is_pow2(align as int),
1481            decreases iter.decrease().unwrap(),
1482        {
1483            match iter.next() {
1484                Some(item) => {
1485                    // Stop *before* writing if we couldn't safely advance afterwards.
1486                    if nr_written == usize::MAX || (item_size > 0 && offset > usize::MAX
1487                        - item_size) {
1488                        return Ok(nr_written);
1489                    }
1490                    match self.write_val(offset, item, Tracked(owner)) {
1491                        Ok(_) => {
1492                            offset = offset + item_size;
1493                            nr_written = nr_written + 1;
1494                        },
1495                        Err(e) => {
1496                            if nr_written > 0 {
1497                                return Ok(nr_written);
1498                            }
1499                            return Err(e);
1500                        },
1501                    }
1502                },
1503                None => return Ok(nr_written),
1504            }
1505        }
1506    }
1507}
1508
1509/// A trait that enables reading/writing data from/to a VM object using one non-tearing memory
1510/// load/store.
1511///
1512/// See also [`VmIo`], which enables reading/writing data from/to a VM object without the guarantee
1513/// of using one non-tearing memory load/store.
1514pub trait VmIoOnce: Sized {
1515    spec fn obeys_vmio_once_read_requires() -> bool;
1516
1517    spec fn obeys_vmio_once_write_requires() -> bool;
1518
1519    spec fn obeys_vmio_once_read_ensures() -> bool;
1520
1521    spec fn obeys_vmio_once_write_ensures() -> bool;
1522
1523    /// Reads a value of the `PodOnce` type at the specified offset using one non-tearing memory
1524    /// load.
1525    ///
1526    /// Except that the offset is specified explicitly, the semantics of this method is the same as
1527    /// [`VmReader::read_once`].
1528    fn read_once<T: PodOnce>(&self, offset: usize) -> Result<T>;
1529
1530    /// Writes a value of the `PodOnce` type at the specified offset using one non-tearing memory
1531    /// store.
1532    ///
1533    /// Except that the offset is specified explicitly, the semantics of this method is the same as
1534    /// [`VmWriter::write_once`].
1535    fn write_once<T: PodOnce>(&self, offset: usize, new_val: &T) -> Result<()>;
1536}
1537
1538/*
1539// Original impl_vm_io_pointer macro and invocations (removed during Verus migration):
1540macro_rules! impl_vm_io_pointer {
1541    ($typ:ty,$from:tt) => {
1542        #[inherit_methods(from = $from)]
1543        impl<T: VmIo> VmIo for $typ {
1544            fn read(&self, offset: usize, writer: &mut VmWriter) -> Result<()>;
1545            fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()>;
1546            fn read_val<F: Pod>(&self, offset: usize) -> Result<F>;
1547            fn read_slice<F: Pod>(&self, offset: usize, slice: &mut [F]) -> Result<()>;
1548            fn write(&self, offset: usize, reader: &mut VmReader) -> Result<()>;
1549            fn write_bytes(&self, offset: usize, buf: &[u8]) -> Result<()>;
1550            fn write_val<F: Pod>(&self, offset: usize, new_val: &F) -> Result<()>;
1551            fn write_slice<F: Pod>(&self, offset: usize, slice: &[F]) -> Result<()>;
1552        }
1553    };
1554}
1555
1556impl_vm_io_pointer!(&T, "(**self)");
1557impl_vm_io_pointer!(&mut T, "(**self)");
1558impl_vm_io_pointer!(Box<T>, "(**self)");
1559impl_vm_io_pointer!(Arc<T>, "(**self)");
1560*/
1561
1562/*
1563// Original impl_vm_io_once_pointer macro and invocations (removed during Verus migration):
1564macro_rules! impl_vm_io_once_pointer {
1565    ($typ:ty,$from:tt) => {
1566        #[inherit_methods(from = $from)]
1567        impl<T: VmIoOnce> VmIoOnce for $typ {
1568            fn read_once<F: PodOnce>(&self, offset: usize) -> Result<F>;
1569            fn write_once<F: PodOnce>(&self, offset: usize, new_val: &F) -> Result<()>;
1570        }
1571    };
1572}
1573
1574impl_vm_io_once_pointer!(&T, "(**self)");
1575impl_vm_io_once_pointer!(&mut T, "(**self)");
1576impl_vm_io_once_pointer!(Box<T>, "(**self)");
1577impl_vm_io_once_pointer!(Arc<T>, "(**self)");
1578*/
1579
1580#[verus_verify]
1581impl<Fallibility> VmReader<'_, Fallibility> {
1582    pub open spec fn remain_spec(&self) -> usize {
1583        (self.end.vaddr - self.cursor.vaddr) as usize
1584    }
1585
1586    /// Returns the number of remaining bytes that can be read.
1587    ///
1588    /// # Verified Properties
1589    /// ## Preconditions
1590    /// - `self` must satisfy its invariant.
1591    /// ## Postconditions
1592    /// - The returned value equals [`Self::remain_spec`].
1593    #[verus_spec(
1594        requires
1595            self.inv(),
1596        returns
1597            self.remain_spec(),
1598    )]
1599    #[verifier::when_used_as_spec(remain_spec)]
1600    pub fn remain(&self) -> usize {
1601        self.end.addr() - self.cursor.addr()
1602    }
1603
1604    /// Returns the cursor pointer, which refers to the address of the next byte to read.
1605    #[verus_spec(returns self.cursor)]
1606    pub fn cursor(&self) -> VirtPtr {
1607        self.cursor
1608    }
1609
1610    /// Returns whether there is remaining data to read.
1611    #[verus_spec(
1612        requires
1613            self.inv(),
1614        returns
1615            self.remain() > 0,
1616    )]
1617    pub fn has_remain(&self) -> bool {
1618        self.remain() > 0
1619    }
1620
1621    /// Limits the length of remaining data.
1622    ///
1623    /// This method ensures the post-condition `self.remain() <= max_remain`.
1624    #[verus_spec(r =>
1625        requires
1626            old(self).inv(),
1627        ensures
1628            r.inv(),
1629            r.remain() == (if old(self).remain() <= max_remain {
1630                old(self).remain()
1631            } else {
1632                max_remain
1633            }),
1634            r.cursor == old(self).cursor,
1635            r.ghost_id == old(self).ghost_id,
1636    )]
1637    pub fn limit(&mut self, max_remain: usize) -> &mut Self {
1638        if max_remain < self.remain() {
1639            self.end = self.cursor.wrapping_add(max_remain);
1640        }
1641        self
1642    }
1643
1644    /// Skips the first `nbytes` bytes of data.
1645    ///
1646    /// The length of remaining data is decreased accordingly.
1647    ///
1648    /// # Panics
1649    ///
1650    /// If `nbytes` is greater than `self.remain()`, then the method panics.
1651    #[verus_spec(r =>
1652        requires
1653            old(self).inv(),
1654            nbytes <= old(self).remain(),
1655        ensures
1656            r.inv(),
1657            r.cursor.vaddr == old(self).cursor.vaddr + nbytes,
1658            r.remain() == old(self).remain() - nbytes,
1659            r.end == old(self).end,
1660            r.ghost_id == old(self).ghost_id,
1661    )]
1662    pub fn skip(&mut self, nbytes: usize) -> &mut Self {
1663        assert!(nbytes <= self.remain());
1664        self.cursor = self.cursor.wrapping_add(nbytes);
1665        self
1666    }
1667
1668    /// Same as [`Self::skip`] but returns `()` instead of `&mut Self`.
1669    ///
1670    /// Sidesteps a Verus modeling quirk: `&mut self`-returning-`&mut Self`
1671    /// reborrows don't auto-propagate the return-value's ensures (`r.*`)
1672    /// to the post-state of `*self` (`final(self).*`). Callers that don't
1673    /// need to chain can use this in-place variant to avoid `r`-vs-`self`
1674    /// reborrow tracking.
1675    #[verus_spec(
1676        with
1677            Tracked(owner): Tracked<&mut crate::specs::mm::io::VmIoOwner>,
1678        requires
1679            old(self).inv(),
1680            old(self).wf(*old(owner)),
1681            old(owner).mem_view is Some,
1682            nbytes <= old(self).remain(),
1683        ensures
1684            final(self).inv(),
1685            final(owner).inv(),
1686            final(self).wf(*final(owner)),
1687            old(owner).read_view_initialized() ==> final(owner).read_view_initialized(),
1688            final(self).cursor.vaddr == old(self).cursor.vaddr + nbytes,
1689            final(self).remain() == old(self).remain() - nbytes,
1690            final(self).end == old(self).end,
1691            final(self).ghost_id == old(self).ghost_id,
1692
1693            old(owner).mem_view matches Some(crate::specs::mm::io::VmIoMemView::ReadView(_)) ==>
1694                forall|va: usize|
1695                    #![trigger crate::specs::mm::io::VmIoOwner::read_view_of(*final(owner)).read(va)]
1696                    final(self).cursor.vaddr <= va < old(self).end.vaddr
1697                    && crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner)).addr_transl(va) is Some
1698                    && crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner)).memory.contains_key(
1699                            (crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner)).addr_transl(va)->0).0
1700                    ) ==> {
1701                        &&& crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner)).addr_transl(va)
1702                            == crate::specs::mm::io::VmIoOwner::read_view_of(*final(owner)).addr_transl(va)
1703                        &&& crate::specs::mm::io::VmIoOwner::read_view_of(*old(owner)).read(va)
1704                            == crate::specs::mm::io::VmIoOwner::read_view_of(*final(owner)).read(va)
1705                    },
1706    )]
1707    pub fn skip_in_place(&mut self, nbytes: usize) {
1708        assert!(nbytes <= self.remain());
1709        self.cursor = self.cursor.wrapping_add(nbytes);
1710        proof {
1711            owner.advance(nbytes);
1712        }
1713    }
1714}
1715
1716#[verus_verify]
1717impl<'a, Fallibility> VmWriter<'a, Fallibility> {
1718    pub open spec fn avail_spec(&self) -> usize {
1719        (self.end.vaddr - self.cursor.vaddr) as usize
1720    }
1721
1722    /// Returns the number of available bytes that can be written.
1723    ///
1724    /// This has the same implementation as [`VmReader::remain`] but semantically
1725    /// they are different.
1726    ///
1727    /// # Verified Properties
1728    /// ## Preconditions
1729    /// - `self` must satisfy its invariant.
1730    /// ## Postconditions
1731    /// - The returned value equals [`Self::avail_spec`].
1732    #[inline]
1733    #[verus_spec(
1734        requires
1735            self.inv(),
1736        returns
1737            self.avail_spec(),
1738    )]
1739    #[verifier::when_used_as_spec(avail_spec)]
1740    pub fn avail(&self) -> usize {
1741        self.end.addr() - self.cursor.addr()
1742    }
1743
1744    /// Returns the cursor pointer, which refers to the address of the next byte to write.
1745    #[verus_spec(returns self.cursor)]
1746    pub fn cursor(&self) -> VirtPtr {
1747        self.cursor
1748    }
1749
1750    /// Returns if it has available space to write.
1751    #[verus_spec(
1752        requires
1753            self.inv(),
1754        returns
1755            self.avail() > 0,
1756    )]
1757    pub fn has_avail(&self) -> bool {
1758        self.avail() > 0
1759    }
1760
1761    /// Limits the length of available space.
1762    ///
1763    /// This method ensures the post-condition `self.avail() <= max_avail`.
1764    #[verus_spec(r =>
1765        requires
1766            old(self).inv(),
1767        ensures
1768            r.inv(),
1769            r.avail() == (if old(self).avail() <= max_avail {
1770                old(self).avail()
1771            } else {
1772                max_avail
1773            }),
1774            r.cursor == old(self).cursor,
1775            r.ghost_id == old(self).ghost_id,
1776    )]
1777    pub fn limit(&mut self, max_avail: usize) -> &mut Self {
1778        if max_avail < self.avail() {
1779            self.end = self.cursor.wrapping_add(max_avail);
1780        }
1781        self
1782    }
1783
1784    /// Skips the first `nbytes` of available space.
1785    ///
1786    /// The length of available space is decreased accordingly.
1787    ///
1788    /// # Panics
1789    ///
1790    /// If `nbytes` is greater than `self.avail()`, then the method panics.
1791    #[verus_spec(r =>
1792        requires
1793            old(self).inv(),
1794            nbytes <= old(self).avail(),
1795        ensures
1796            r.inv(),
1797            r.cursor.vaddr == old(self).cursor.vaddr + nbytes,
1798            r.avail() == old(self).avail() - nbytes,
1799            r.end == old(self).end,
1800            r.ghost_id == old(self).ghost_id,
1801    )]
1802    pub fn skip(&mut self, nbytes: usize) -> &mut Self {
1803        assert!(nbytes <= self.avail());
1804        self.cursor = self.cursor.wrapping_add(nbytes);
1805        self
1806    }
1807}
1808
1809#[verus_verify]
1810impl<'a> VmWriter<'a, Fallible> {
1811    /// Constructs a [`VmWriter`] from a pointer and a length, which represents
1812    /// a memory range in USER space.
1813    ///
1814    /// # Verified Properties
1815    /// ## Preconditions
1816    /// - `ptr` must satisfy [`VirtPtr::inv`].
1817    /// ## Postconditions
1818    /// - The returned [`VmWriter`] satisfies its invariant.
1819    /// - The returned writer is associated with a [`VmIoOwner`] that satisfies both [`VmIoOwner::inv`]
1820    ///   and [`VmWriter::wf`].
1821    /// - The owner has the same range as `ptr`, has no memory view yet, and is marked as user-space.
1822    #[verus_spec(r =>
1823        with
1824            Ghost(id): Ghost<nat>,
1825                -> owner: Tracked<VmIoOwner>,
1826        ensures
1827            r.inv_wf(),
1828            owner@.id == id,
1829            owner@.range == ptr.range@,
1830            owner@.mem_view is None,
1831            !owner@.is_kernel,
1832            r.cursor == ptr,
1833            r.end == ptr.wrapping_add_spec(len),
1834            r.end.range@ == ptr.range@,
1835            ptr.inv() && ptr.range@.start == ptr.vaddr
1836                && len == ptr.range@.end - ptr.range@.start ==> {
1837                &&& r.inv()
1838                &&& owner@.inv()
1839                &&& r.wf(owner@)
1840            },
1841    )]
1842    pub unsafe fn from_user_space(ptr: VirtPtr, len: usize) -> Self {
1843        let tracked owner = VmIoOwner {
1844            id,
1845            range: ptr.range@,
1846            is_fallible: true,
1847            is_kernel: false,
1848            mem_view: None,
1849        };
1850        proof_with!(|= Tracked(owner));
1851        Self { ghost_id: Ghost(id), cursor: ptr, end: ptr.wrapping_add(len), phantom: PhantomData }
1852    }
1853
1854    /// Writes a value of `Pod` type to user space.
1855    ///
1856    /// If the underlying memory access faults during the write, the cursor
1857    /// is rolled back to its starting position before returning `Err`.
1858    ///
1859    /// # Verified Properties
1860    /// ## Postconditions
1861    /// - On success, the cursor advances by `size_of::<T>()`.
1862    /// - On error, the cursor is at its original position (writer state preserved).
1863    #[verus_spec(r =>
1864        requires
1865            old(self).inv(),
1866        ensures
1867            final(self).inv(),
1868            final(self).end == old(self).end,
1869            final(self).ghost_id == old(self).ghost_id,
1870            final(self).cursor.range == old(self).cursor.range,
1871            old(self).avail() < core::mem::size_of::<T>()
1872                ==> r == Err(Error::InvalidArgs),
1873            match r {
1874                Ok(_) => {
1875                    &&& final(self).avail() == old(self).avail() - core::mem::size_of::<T>()
1876                    &&& final(self).cursor.vaddr == old(self).cursor.vaddr + core::mem::size_of::<T>()
1877                },
1878                Err(_) => *final(self) == *old(self),
1879            },
1880    )]
1881    pub fn write_val<T: Pod>(&mut self, new_val: &T) -> Result<()> {
1882        let len = core::mem::size_of::<T>();
1883        if self.avail() < len {
1884            return Err(Error::InvalidArgs);
1885        }
1886        proof_decl! {
1887            let tracked mut reader_owner_inner: VmIoOwner;
1888        }
1889        #[verus_spec(with => Tracked(reader_owner_inner))]
1890        let mut reader = VmReader::from(new_val.as_bytes());
1891        match self.write_fallible(&mut reader) {
1892            Ok(_) => Ok(()),
1893            Err((err, copied_len)) => {
1894                self.cursor = self.cursor.sub(copied_len);
1895                Err(err)
1896            },
1897        }
1898    }
1899
1900    /// Writes `len` zeros to the target memory.
1901    ///
1902    /// This method attempts to fill up to `len` bytes with zeros. If the
1903    /// available memory from the current cursor position is less than `len`,
1904    /// it will only fill the available space.
1905    ///
1906    /// If the memory write failed due to an unresolvable page fault, this
1907    /// method will return `Err` with the length set so far.
1908    #[verus_spec(r =>
1909        requires
1910            old(self).inv(),
1911        ensures
1912            final(self).inv(),
1913            final(self).end == old(self).end,
1914            final(self).ghost_id == old(self).ghost_id,
1915            final(self).cursor.range == old(self).cursor.range,
1916            final(self).cursor.vaddr >= old(self).cursor.vaddr,
1917            final(self).cursor.vaddr <= old(self).end.vaddr,
1918            {
1919                let n = match r { Ok(n) => n, Err((_, n)) => n };
1920                &&& n <= len
1921                &&& n <= old(self).avail()
1922                &&& final(self).cursor.vaddr == old(self).cursor.vaddr + n
1923            },
1924    )]
1925    pub fn fill_zeros(&mut self, len: usize) -> core::result::Result<usize, (Error, usize)> {
1926        let len_to_set = self.avail().min(len);
1927        if len_to_set == 0 {
1928            return Ok(0);
1929        }
1930        // SAFETY: The destination is a subset of the memory range specified by
1931        // the current writer, so it is either valid for writing or in user space.
1932
1933        let set_len = unsafe { memset_fallible(self.cursor, 0u8, len_to_set) };
1934        self.cursor = self.cursor.wrapping_add(set_len);
1935
1936        if set_len < len_to_set {
1937            Err((Error::PageFault, set_len))
1938        } else {
1939            Ok(len_to_set)
1940        }
1941    }
1942}
1943
1944/// Extension trait for byte slices that produces a [`VirtPtr`] covering the
1945/// slice's bytes. Mirrors the role of [`<[u8]>::as_ptr`] but in our verified
1946/// pointer model.
1947pub trait AsVirtPtr {
1948    fn as_virt_ptr(&self) -> VirtPtr;
1949}
1950
1951#[verus_verify]
1952impl AsVirtPtr for [u8] {
1953    #[verus_spec(r =>
1954        ensures
1955            r.inv(),
1956            r.range@.start == r.vaddr,
1957            r.range@.end - r.range@.start == self.len(),
1958            r.vaddr == ::vstd_extra::external::slice::as_ptr_spec(self) as usize,
1959    )]
1960    fn as_virt_ptr(&self) -> VirtPtr {
1961        let addr = self.as_ptr() as usize;
1962        let len = self.len();
1963        proof {
1964            ::vstd_extra::external::slice::axiom_slice_addr_no_overflow(self);
1965        }
1966        let ghost range: Range<usize> = addr..(addr + len) as usize;
1967        VirtPtr { vaddr: addr, range: Ghost(range) }
1968    }
1969}
1970
1971/*
1972// Original From<&mut [u8]> for VmWriter (replaced by pub fn from during Verus migration):
1973impl<'a> From<&'a mut [u8]> for VmWriter<'a, Infallible> {
1974    fn from(slice: &'a mut [u8]) -> Self {
1975        unsafe { Self::from_kernel_space(slice.as_mut_ptr(), slice.len()) }
1976    }
1977}
1978*/
1979
1980#[verus_verify]
1981impl<'a> VmWriter<'a, Infallible> {
1982    /// Constructs a [`VmWriter<'a, Infallible>`] from a mutable byte slice.
1983    ///
1984    /// The slice's address establishes the writer's cursor range; the kernel-space
1985    /// trust ([`axiom_slice_in_kernel`] + [`axiom_kernel_mem_view`] via
1986    /// [`Self::from_kernel_space`]) supplies the tracked [`VmIoOwner`] with its
1987    /// `WriteView`. Callers receive the owner via `proof_with!`.
1988    ///
1989    /// # Safety
1990    ///
1991    /// The slice's memory must be valid for writes during `'a` — guaranteed by
1992    /// Rust's borrow checker for `&'a mut [u8]`.
1993    #[verus_spec(r =>
1994        with
1995            -> owner: Tracked<VmIoOwner>,
1996        ensures
1997            r.inv(),
1998            owner@.inv(),
1999            r.wf(*owner),
2000            owner@.has_write_view(),
2001            r.cursor.range == owner@.range,
2002            owner@.range.end - owner@.range.start == old(slice).len(),
2003            old(slice).len() == 0 || KERNEL_BASE_VADDR <= r.cursor.vaddr,
2004            old(slice).len() == 0
2005                || r.cursor.vaddr + old(slice).len() <= KERNEL_END_VADDR,
2006    )]
2007    pub fn from(slice: &'a mut [u8]) -> Self {
2008        // SAFETY:
2009        // - The memory range points to typed memory.
2010        // - The validity requirements for write accesses are met because the pointer is converted
2011        //   from a mutable reference that outlives the lifetime `'a`.
2012        // - The type, i.e., the `u8` slice, is plain-old-data.
2013        let shared: &[u8] = &*slice;
2014        proof {
2015            axiom_slice_in_kernel(shared);
2016        }
2017        let ptr = shared.as_virt_ptr();
2018        let len = shared.len();
2019        proof_decl! {
2020            let tracked mut owner_inner: VmIoOwner;
2021        }
2022        let writer = unsafe {
2023            #[verus_spec(with Ghost(0nat), Tracked(false) => Tracked(owner_inner))]
2024            Self::from_kernel_space(ptr, len)
2025        };
2026        proof_with!(|= Tracked(owner_inner));
2027        writer
2028    }
2029}
2030
2031/*
2032// Original From<&[u8]> for VmReader (replaced by pub fn from during Verus migration):
2033impl<'a> From<&'a [u8]> for VmReader<'a, Infallible> {
2034    fn from(slice: &'a [u8]) -> Self {
2035        unsafe { Self::from_kernel_space(slice.as_ptr(), slice.len()) }
2036    }
2037}
2038*/
2039
2040#[verus_verify]
2041impl<'a> VmReader<'a, Infallible> {
2042    /// Constructs a [`VmReader<'a, Infallible>`] from a shared byte slice.
2043    ///
2044    /// The slice's address establishes the reader's cursor range; the kernel-space
2045    /// trust ([`axiom_slice_in_kernel`] + [`axiom_kernel_mem_view`] via
2046    /// [`Self::from_kernel_space`]) supplies the tracked [`VmIoOwner`] with its
2047    /// initialized `ReadView`. Callers receive the owner via `proof_with!`.
2048    ///
2049    /// # Safety
2050    ///
2051    /// The slice's memory must be valid for reads during `'a` — guaranteed by
2052    /// Rust's borrow checker for `&'a [u8]`.
2053    #[verus_spec(r =>
2054        with
2055            -> owner: Tracked<VmIoOwner>,
2056        ensures
2057            r.inv(),
2058            owner@.inv(),
2059            r.wf(*owner),
2060            owner@.read_view_initialized(),
2061            r.cursor.range == owner@.range,
2062            owner@.range.end - owner@.range.start == slice.len(),
2063            slice.len() == 0 || KERNEL_BASE_VADDR <= r.cursor.vaddr,
2064            slice.len() == 0 || r.cursor.vaddr + slice.len() <= KERNEL_END_VADDR,
2065    )]
2066    pub fn from(slice: &'a [u8]) -> Self {
2067        // SAFETY:
2068        // - The memory range points to typed memory.
2069        // - The validity requirements for read accesses are met because the pointer is converted
2070        //   from a shared reference that outlives the lifetime `'a`.
2071        // - The type, i.e., the `u8` slice, is plain-old-data.
2072        proof {
2073            axiom_slice_in_kernel(slice);
2074        }
2075        let ptr = slice.as_virt_ptr();
2076        let len = slice.len();
2077        proof_decl! {
2078            let tracked mut owner_inner: VmIoOwner;
2079        }
2080        let reader = unsafe {
2081            #[verus_spec(with Ghost(0nat) => Tracked(owner_inner))]
2082            Self::from_kernel_space(ptr, len)
2083        };
2084        proof_with!(|= Tracked(owner_inner));
2085        reader
2086    }
2087}
2088
2089} // verus!
2090/// Fallible memory read from a `VmWriter`.
2091pub trait FallibleVmRead<F> {
2092    fn read_fallible(
2093        &mut self,
2094        writer: &mut VmWriter<'_, F>,
2095    ) -> core::result::Result<usize, (Error, usize)>;
2096}
2097
2098/// Fallible memory write from a `VmReader`.
2099pub trait FallibleVmWrite<F> {
2100    fn write_fallible(
2101        &mut self,
2102        reader: &mut VmReader<'_, F>,
2103    ) -> core::result::Result<usize, (Error, usize)>;
2104}
2105
2106macro_rules! impl_read_fallible {
2107    ($reader_fallibility:ty, $writer_fallibility:ty) => {
2108        ::vstd::prelude::verus! {
2109        impl<'a> FallibleVmRead<$writer_fallibility> for VmReader<'a, $reader_fallibility> {
2110            #[verus_spec(r =>
2111                requires
2112                    old(self).inv(),
2113                    old(writer).inv(),
2114                ensures
2115                    final(self).end == old(self).end,
2116                    final(self).ghost_id == old(self).ghost_id,
2117                    final(self).cursor.range == old(self).cursor.range,
2118                    final(writer).end == old(writer).end,
2119                    final(writer).ghost_id == old(writer).ghost_id,
2120                    final(writer).cursor.range == old(writer).cursor.range,
2121                    final(self).inv(),
2122                    final(writer).inv(),
2123                    {
2124                        let n = match r { Ok(n) => n, Err((_, n)) => n };
2125                        &&& final(self).cursor.vaddr == old(self).cursor.vaddr + n
2126                        &&& final(writer).cursor.vaddr == old(writer).cursor.vaddr + n
2127                        &&& n <= old(self).remain()
2128                        &&& n <= old(writer).avail()
2129                        &&& r is Ok ==> n == vstd::math::min(old(self).remain() as int, old(writer).avail() as int)
2130                    },
2131            )]
2132            fn read_fallible(
2133                &mut self,
2134                writer: &mut VmWriter<'_, $writer_fallibility>,
2135            ) -> core::result::Result<usize, (Error, usize)> {
2136                let copy_len = self.remain().min(writer.avail());
2137                if copy_len == 0 {
2138                    return Ok(0);
2139                }
2140
2141                // SAFETY: The source and destination are subsets of memory ranges specified by
2142                // the reader and writer, so they are either valid for reading and writing or in
2143                // user space.
2144                let copied_len = unsafe {
2145                    memcpy_fallible(writer.cursor, self.cursor, copy_len)
2146                };
2147                self.cursor = self.cursor.wrapping_add(copied_len);
2148                writer.cursor = writer.cursor.wrapping_add(copied_len);
2149
2150                if copied_len < copy_len {
2151                    Err((Error::PageFault, copied_len))
2152                } else {
2153                    Ok(copied_len)
2154                }
2155            }
2156        }
2157        } // verus!
2158};
2159}
2160
2161macro_rules! impl_write_fallible {
2162    ($writer_fallibility:ty, $reader_fallibility:ty) => {
2163        ::vstd::prelude::verus! {
2164        impl<'a> FallibleVmWrite<$reader_fallibility> for VmWriter<'a, $writer_fallibility> {
2165            #[verus_spec(r =>
2166                requires
2167                    old(self).inv(),
2168                    old(reader).inv(),
2169                ensures
2170                    final(self).end == old(self).end,
2171                    final(self).ghost_id == old(self).ghost_id,
2172                    final(self).cursor.range == old(self).cursor.range,
2173                    final(reader).end == old(reader).end,
2174                    final(reader).ghost_id == old(reader).ghost_id,
2175                    final(reader).cursor.range == old(reader).cursor.range,
2176                    final(self).inv(),
2177                    final(reader).inv(),
2178                    {
2179                        let n = match r { Ok(n) => n, Err((_, n)) => n };
2180                        &&& final(self).cursor.vaddr == old(self).cursor.vaddr + n
2181                        &&& final(reader).cursor.vaddr == old(reader).cursor.vaddr + n
2182                        &&& n <= old(self).avail()
2183                        &&& n <= old(reader).remain()
2184                        &&& r is Ok ==> n == vstd::math::min(old(self).avail() as int, old(reader).remain() as int)
2185                    },
2186            )]
2187            fn write_fallible(
2188                &mut self,
2189                reader: &mut VmReader<'_, $reader_fallibility>,
2190            ) -> core::result::Result<usize, (Error, usize)> {
2191                reader.read_fallible(self)
2192            }
2193        }
2194        } // verus!
2195};
2196}
2197
2198impl_read_fallible!(Fallible, Infallible);
2199impl_read_fallible!(Fallible, Fallible);
2200impl_read_fallible!(Infallible, Fallible);
2201impl_write_fallible!(Fallible, Infallible);
2202impl_write_fallible!(Fallible, Fallible);
2203impl_write_fallible!(Infallible, Fallible);
2204
2205verus! {
2206
2207/// A marker trait for POD types that can be read or written with one instruction.
2208///
2209/// This trait is mostly a hint, since it's safe and can be implemented for _any_ POD type. If it
2210/// is implemented for a type that cannot be read or written with a single instruction, calling
2211/// `read_once`/`write_once` will lead to a failed compile-time assertion.
2212pub trait PodOnce: Pod {
2213
2214}
2215
2216#[cfg(any(
2217    target_arch = "x86_64",
2218    target_arch = "riscv64",
2219    target_arch = "loongarch64"
2220))]
2221mod pod_once_impls {
2222    use super::PodOnce;
2223
2224    impl PodOnce for u8 {
2225
2226    }
2227
2228    impl PodOnce for u16 {
2229
2230    }
2231
2232    impl PodOnce for u32 {
2233
2234    }
2235
2236    impl PodOnce for u64 {
2237
2238    }
2239
2240    impl PodOnce for usize {
2241
2242    }
2243
2244    impl PodOnce for i8 {
2245
2246    }
2247
2248    impl PodOnce for i16 {
2249
2250    }
2251
2252    impl PodOnce for i32 {
2253
2254    }
2255
2256    impl PodOnce for i64 {
2257
2258    }
2259
2260    impl PodOnce for isize {
2261
2262    }
2263
2264    /// Checks whether the memory operation created by `ptr::read_volatile` and
2265    /// `ptr::write_volatile` doesn't tear.
2266    ///
2267    /// Note that the Rust documentation makes no such guarantee, and even the wording in the LLVM
2268    /// LangRef is ambiguous. But this is unlikely to break in practice because the Linux kernel
2269    /// also uses "volatile" semantics to implement `READ_ONCE`/`WRITE_ONCE`.
2270    pub(super) const fn is_non_tearing<T>() -> bool {
2271        let size = core::mem::size_of::<T>();
2272
2273        size == 1 || size == 2 || size == 4 || size == 8
2274    }
2275
2276}
2277
2278} // verus!