Skip to main content

ostd/mm/frame/
meta.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Metadata management of frames.
3//!
4//! You can picture a globally shared, static, gigantic array of metadata
5//! initialized for each frame.
6//! Each entry in this array holds the metadata for a single frame.
7//! There would be a dedicated small
8//! "heap" space in each slot for dynamic metadata. You can store anything as
9//! the metadata of a frame as long as it's [`Sync`].
10//!
11//! # Implementation
12//!
13//! The slots are placed in the metadata pages mapped to a certain virtual
14//! address in the kernel space. So finding the metadata of a frame often
15//! comes with no costs since the translation is a simple arithmetic operation.
16use vstd::prelude::*;
17
18verus! {
19
20pub(crate) mod mapping {
21    //! The metadata of each physical page is linear mapped to fixed virtual addresses
22    //! in [`FRAME_METADATA_RANGE`].
23    use vstd::prelude::*;
24    use crate::specs::arch::*;
25    use core::mem::size_of;
26    use super::MetaSlot;
27    use crate::mm::{kspace::FRAME_METADATA_RANGE, Paddr, PagingConstsTrait, Vaddr};
28    use super::META_SLOT_SIZE;
29
30    pub open spec fn frame_to_meta_spec(paddr: Paddr) -> Vaddr {
31        (FRAME_METADATA_RANGE.start + (paddr / PAGE_SIZE) * META_SLOT_SIZE) as usize
32    }
33
34    pub open spec fn meta_to_frame_spec(vaddr: Vaddr) -> Paddr {
35        ((vaddr - FRAME_METADATA_RANGE.start) / META_SLOT_SIZE as int * PAGE_SIZE) as usize
36    }
37
38    /// Converts a physical address of a base frame to the virtual address of the metadata slot.
39    #[verifier::when_used_as_spec(frame_to_meta_spec)]
40    pub const fn frame_to_meta(paddr: Paddr) -> (res: Vaddr)
41        requires
42            valid_frame_paddr(paddr),
43        ensures
44            res % META_SLOT_SIZE == 0,
45        returns
46            frame_to_meta(paddr),
47        no_unwind
48    {
49        proof {
50            MetaSlot::lemma_layout();
51        }
52        let base = FRAME_METADATA_RANGE.start;
53        let offset = paddr / PAGE_SIZE;
54        base + offset * size_of::<MetaSlot>()
55    }
56
57    /// Converts a virtual address of the metadata slot to the physical address of the frame.
58    #[verifier::when_used_as_spec(meta_to_frame_spec)]
59    pub const fn meta_to_frame(vaddr: Vaddr) -> (res: Paddr)
60        requires
61            FRAME_METADATA_RANGE.start <= vaddr < FRAME_METADATA_RANGE.end,
62            vaddr % META_SLOT_SIZE == 0,
63        ensures
64            res % PAGE_SIZE == 0,
65        returns
66            meta_to_frame(vaddr),
67    {
68        proof {
69            MetaSlot::lemma_layout();
70        }
71        let base = FRAME_METADATA_RANGE.start;
72        let offset = (vaddr - base) / size_of::<MetaSlot>();
73        offset * PAGE_SIZE
74    }
75
76}
77
78} // verus!
79use vstd::{
80    atomic::{PAtomicU64, PermissionU64},
81    cell::pcell_maybe_uninit,
82    prelude::*,
83    simple_pptr::PPtr,
84};
85use vstd_extra::{
86    cast_ptr::{Repr, ReprPtr},
87    ownership::*,
88    panic::{allowed_to_panic_if, panic_diverge},
89    prelude::*,
90    raw_ptr::{ExposedPointsTo, ptr_from_addr, ptr_ref},
91    sum::Sum,
92};
93
94use crate::specs::{
95    arch::*,
96    mm::frame::{mapping::frame_to_index, meta_owners::*, meta_region_owners::MetaRegionOwners},
97};
98
99use core::{
100    alloc::Layout,
101    any::Any,
102    cell::UnsafeCell,
103    fmt::Debug,
104    marker::PhantomData,
105    mem::{ManuallyDrop, MaybeUninit},
106    result::Result,
107    sync::atomic::{AtomicU64, Ordering},
108};
109
110use align_ext::AlignExt;
111//use log::info;
112
113use self::mapping::{frame_to_meta, meta_to_frame};
114use crate::{
115    //    boot::memory_region::MemoryRegionType,
116    //    const_assert,
117    mm::{
118        Infallible,
119        Paddr,
120        PagingLevel,
121        //Segment,
122        Vaddr,
123        VmReader,
124        kspace::FRAME_METADATA_RANGE,
125        //        frame::allocator::{self, EarlyAllocatedFrameMeta},
126        paddr_to_vaddr,
127        //        page_table::boot_pt,
128        page_prop::{CachePolicy, PageFlags, PageProperty, PrivilegedPageFlags},
129    },
130    //    panic::abort,
131    //    util::ops::range_difference,
132};
133
134verus! {
135
136/* /// The maximum number of bytes of the metadata of a frame.
137pub const FRAME_METADATA_MAX_SIZE: usize = META_SLOT_SIZE
138    - size_of::<AtomicU64>()
139    - size_of::<FrameMetaVtablePtr>()
140    - size_of::<AtomicU64>(); */
141/// The maximum alignment in bytes of the metadata of a frame.
142pub const FRAME_METADATA_MAX_ALIGN: usize = META_SLOT_SIZE;
143
144pub const META_SLOT_SIZE: usize = 64;
145
146#[repr(C)]
147pub struct MetaSlot {
148    /// The metadata of a frame.
149    ///
150    /// It is placed at the beginning of a slot because:
151    ///  - the implementation can simply cast a `*const MetaSlot`
152    ///    to a `*const AnyFrameMeta` for manipulation;
153    ///  - if the metadata need special alignment, we can provide
154    ///    at most `PAGE_METADATA_ALIGN` bytes of alignment;
155    ///  - the subsequent fields can utilize the padding of the
156    ///    reference count to save space.
157    ///
158    /// Don't interpret this field as an array of bytes. It is a
159    /// placeholder for the metadata of a frame.
160    // storage: UnsafeCell<[u8; FRAME_METADATA_MAX_SIZE]>
161    /// # Verification Design
162    /// We model the metadata of the slot as a `MetaSlotStorage`, which is a tagged union of the different
163    /// types of metadata defined in the development.
164    pub storage: pcell_maybe_uninit::PCell<MetaSlotStorage>,
165    /// The reference count of the page.
166    ///
167    /// Specifically, the reference count has the following meaning:
168    ///  - `REF_COUNT_UNUSED`: The page is not in use.
169    ///  - `REF_COUNT_UNIQUE`: The page is owned by a [`UniqueFrame`].
170    ///  - `0`: The page is being constructed ([`Frame::from_unused`])
171    ///    or destructured ([`drop_last_in_place`]).
172    ///  - `1..REF_COUNT_MAX`: The page is in use.
173    ///  - `REF_COUNT_MAX..REF_COUNT_UNIQUE`: Illegal values to
174    ///    prevent the reference count from overflowing. Otherwise,
175    ///    overflowing the reference count will cause soundness issue.
176    ///
177    /// [`Frame::from_unused`]: super::Frame::from_unused
178    /// [`UniqueFrame`]: super::unique::UniqueFrame
179    /// [`drop_last_in_place`]: Self::drop_last_in_place
180    //
181    // Other than this field the fields should be `MaybeUninit`.
182    // See initialization in `alloc_meta_frames`.
183    pub ref_count: PAtomicU64,
184    /// The virtual table that indicates the type of the metadata.
185    /// VERUS LIMITATION: Currently we do not verify this because
186    /// of the dependency on the `dyn Trait` pattern. But we can revisit it now that `dyn Trait` is supported by Verus.
187    // pub vtable_ptr: UnsafeCell<MaybeUninit<FrameMetaVtablePtr>>,
188    pub vtable_ptr: PPtr<usize>,
189    /// This is only accessed by [`crate::mm::frame::linked_list`].
190    /// It stores 0 if the frame is not in any list, otherwise it stores the
191    /// ID of the list.
192    ///
193    /// It is ugly but allows us to tell if a frame is in a specific list by
194    /// one relaxed read. Otherwise, if we store it conditionally in `storage`
195    /// we would have to ensure that the type is correct before the read, which
196    /// costs a synchronization.
197    pub in_list: PAtomicU64,
198}
199
200pub const REF_COUNT_UNUSED: u64 = u64::MAX;
201
202pub const REF_COUNT_UNIQUE: u64 = u64::MAX - 1;
203
204pub const REF_COUNT_MAX: u64 = i64::MAX as u64;
205
206type FrameMetaVtablePtr = core::ptr::DynMetadata<dyn AnyFrameMeta>;
207
208/// All frame metadata types must implement this trait.
209///
210/// If a frame type needs specific drop behavior, it should specify
211/// when implementing this trait. When we drop the last handle to
212/// this frame, the `on_drop` method will be called. The `on_drop`
213/// method is called with the physical address of the frame.
214///
215/// The implemented structure should have a size less than or equal to
216/// [`FRAME_METADATA_MAX_SIZE`] and an alignment less than or equal to
217/// [`FRAME_METADATA_MAX_ALIGN`]. Otherwise, the metadata type cannot
218/// be used because storing it will fail compile-time assertions.
219///
220/// # Safety
221///
222/// If `on_drop` reads the page using the provided `VmReader`, the
223/// implementer must ensure that the frame is safe to read.
224pub unsafe trait AnyFrameMeta:   /*Any +*/
225Send + Sync {
226    /// Per-impl precondition for [`Self::on_drop`]. Default is `true`.
227    /// Impls that need richer caller-side invariants (e.g. the PT-node's
228    /// reader/region invariants) override this; the trait method's
229    /// `requires` clause calls it.
230    open spec fn on_drop_pre(
231        &self,
232        reader: VmReader<'_, Infallible>,
233        regions: MetaRegionOwners,
234        vm_io_owner: crate::specs::mm::io::VmIoOwner,
235    ) -> bool {
236        true
237    }
238
239    fn on_drop(
240        &mut self,
241        _reader: &mut VmReader<'_, Infallible>,
242        Tracked(_regions): Tracked<&mut MetaRegionOwners>,
243        Tracked(_vm_io_owner): Tracked<&mut crate::specs::mm::io::VmIoOwner>,
244    )
245        requires
246            old(_regions).inv(),
247            old(_reader).inv(),
248            old(_vm_io_owner).inv(),
249            old(_reader).wf(*old(_vm_io_owner)),
250            old(self).on_drop_pre(*old(_reader), *old(_regions), *old(_vm_io_owner)),
251        ensures
252            final(_regions).inv(),
253            final(_reader).inv(),
254            final(_vm_io_owner).inv(),
255            final(_reader).wf(*final(_vm_io_owner)),
256        default_ensures
257            *final(_reader) == *old(_reader),
258            *final(_regions) == *old(_regions),
259            *final(_vm_io_owner) == *old(_vm_io_owner),
260    {
261    }
262
263    fn is_untyped(&self) -> (res: bool)
264        default_ensures
265            res == false,
266    {
267        false
268    }
269
270    spec fn vtable_ptr(&self) -> usize where Self: Sized;
271}
272
273/*/// Makes a structure usable as a frame metadata.
274#[macro_export]
275macro_rules! impl_frame_meta_for {
276    // Implement without specifying the drop behavior.
277    ($t:ty) => {
278        // SAFETY: `on_drop` won't read the page.
279        unsafe impl $crate::mm::frame::meta::AnyFrameMeta for $t {}
280
281        $crate::const_assert!(
282            core::mem::size_of::<$t>() <= $crate::mm::frame::meta::FRAME_METADATA_MAX_SIZE
283        );
284        $crate::const_assert!(
285            $crate::mm::frame::meta::FRAME_METADATA_MAX_ALIGN % core::mem::align_of::<$t>() == 0
286        );
287    };
288}
289
290pub use impl_frame_meta_for;*/
291
292/// The error type for getting the frame from a physical address.
293#[derive(Debug)]
294pub enum GetFrameError {
295    /// The frame is in use.
296    InUse,
297    /// The frame is not in use.
298    Unused,
299    /// The frame is being initialized or destructed.
300    Busy,
301    /// The frame is private to an owner of [`UniqueFrame`].
302    ///
303    /// [`UniqueFrame`]: super::unique::UniqueFrame
304    Unique,
305    /// The provided physical address is out of bound.
306    OutOfBound,
307    /// The provided physical address is not aligned.
308    NotAligned,
309}
310
311/// Gets the reference to a metadata slot.
312/// # Verified Properties
313/// ## Preconditions
314/// `paddr` is the physical address of a frame, with a valid owner.
315/// ## Postconditions
316/// If `paddr` is aligned properly and in-bounds, the function returns a static reference to its metadata slot.
317/// ## Safety
318/// Verus ensures that the pointer is properly dereferenced with a permission object, so creating it is safe.
319#[verus_spec(res =>
320    with
321        Tracked(slot_perm): Tracked<Option<&'static ExposedPointsTo<MetaSlot>>>
322    requires
323        valid_frame_paddr(paddr) ==> {
324            &&& slot_perm is Some
325            &&& slot_perm->0.addr() == frame_to_meta(paddr)
326            &&& slot_perm->0.is_init()
327        }
328    ensures
329        valid_frame_paddr(paddr) == res is Ok,
330        res is Ok ==> res->Ok_0 == slot_perm->0.value(),
331)]
332pub(super) fn get_slot(paddr: Paddr) -> Result<&'static MetaSlot, GetFrameError> {
333    if paddr % PAGE_SIZE != 0 {
334        return Err(GetFrameError::NotAligned);
335    }
336    if paddr >= super::max_paddr() {
337        return Err(GetFrameError::OutOfBound);
338    }
339    let vaddr = mapping::frame_to_meta(paddr);
340    // Origin Rust: let ptr = vaddr as *mut MetaSlot;
341    let ptr = ptr_from_addr(vaddr, Tracked(slot_perm.tracked_borrow()));
342
343    // SAFETY: `ptr` points to a valid `MetaSlot` that will never be
344    // mutably borrowed, so taking an immutable reference to it is safe.
345    // Origin Rust: Ok(unsafe { &*ptr })
346    Ok(ptr_ref(ptr, Tracked(slot_perm.tracked_borrow())))
347}
348
349#[verus_verify]
350impl MetaSlot {
351    /// This is the equivalent of &self as *const as Vaddr, but we need to axiomatize it.
352    /// # Safety
353    /// It is safe to take the address of a pointer, but it may not be safe to use that
354    /// address for all purposes.
355    #[verifier::external_body]
356    #[verus_spec(
357        with
358            Tracked(perm): Tracked<&ExposedPointsTo<MetaSlot>>,
359        requires
360            self == perm.value(),
361        returns
362            perm.addr(),
363    )]
364    fn addr_of(&self) -> Vaddr {
365        unimplemented!()
366    }
367
368    /// Initializes the metadata slot of a frame assuming it is unused.
369    ///
370    /// If successful, the function returns a pointer to the metadata slot.
371    /// And the slot is initialized with the given metadata.
372    ///
373    /// The resulting reference count held by the returned pointer is
374    /// [`REF_COUNT_UNIQUE`] if `as_unique_ptr` is `true`, otherwise `1`.
375    ///
376    /// # Verified Properties
377    /// ## Preconditions
378    /// - **Safety Invariant**: Metaslot region invariants must hold.
379    /// - **Bookkeeping**: The slot permissions must be available in order to check the reference count.
380    /// This precondition is stronger than it needs to be; absent permissions correspond to error cases.
381    /// ## Postconditions
382    /// - **Safety Invariant**: Metaslot region invariants hold after the call.
383    /// - **Safety**: Other slots are not affected by the call.
384    /// - **Correctness**: If successful, the function returns a pointer to the metadata slot and a permission to the slot.
385    /// - **Correctness**: If successful, the slot is initialized with the given metadata.
386    /// ## Safety
387    /// - This function returns an error if `paddr` does not correspond to a valid slot or the slot is in use.
388    /// - Accesses to the slot itself are gated by atomic checks, avoiding data races.
389    #[verus_spec(res =>
390        with
391            Tracked(regions): Tracked<&mut MetaRegionOwners>,
392            -> permissions: Tracked<Option<Sum<FracMetadataPerm, MetadataPerm>>>
393        requires
394            old(regions).inv(),
395        ensures
396            res is Err ==> {
397                &&& *final(regions) == *old(regions)
398                &&& permissions@ is None
399            },
400            res matches Ok(res) ==> {
401                &&& valid_frame_paddr(paddr)
402                &&& res.addr() == frame_to_meta(paddr)
403                &&& res == final(regions).slots[frame_to_index(paddr)].ptr()
404                &&& final(regions).inv()
405                &&& permissions@ is Some
406                &&& Self::get_from_unused_spec(
407                    paddr,
408                    metadata,
409                    as_unique_ptr,
410                    *old(regions),
411                    *final(regions),
412                    permissions@->0,
413                )
414            },
415    )]
416    pub(super) fn get_from_unused<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf>(
417        paddr: Paddr,
418        metadata: M,
419        as_unique_ptr: bool,
420    ) -> Result<*const Self, GetFrameError> {
421        proof_decl! {
422            let tracked slot_perm = if valid_frame_paddr(paddr) {
423                Some(regions.tracked_borrow_slot(paddr))
424            } else {
425                None
426            };
427            if valid_frame_paddr(paddr) {
428                regions.lemma_contains_valid_frame_paddr(paddr);
429            }
430        }
431
432        // let slot = get_slot(paddr)?;
433        let slot = match #[verus_spec(with Tracked(slot_perm))]
434        get_slot(paddr) {
435            Ok(slot) => slot,
436            Err(err) => {
437                return #[verus_spec(with |= Tracked(None))]
438                Err(err);
439            },
440        };
441
442        let tracked slot_own = regions.tracked_borrow_mut_slot_owner(paddr);
443        // `Acquire` pairs with the `Release` in `drop_last_in_place` and ensures the metadata
444        // initialization won't be reordered before this memory compare-and-exchange.
445        let last_ref_cnt = slot.ref_count.compare_exchange(
446            Tracked(&mut slot_own.ref_count_perm),
447            REF_COUNT_UNUSED,
448            0,
449        ).map_err(
450            |val|
451                match val {
452                    REF_COUNT_UNIQUE => GetFrameError::Unique,
453                    0 => GetFrameError::Busy,
454                    _ => GetFrameError::InUse,
455                },
456        );
457
458        if let Err(err) = last_ref_cnt {
459            proof {
460                vstd_extra::auxiliary::axiom_permission_u64_ext_eq(
461                    regions.slot_owner(paddr).ref_count_perm,
462                    old(regions).slot_owner(paddr).ref_count_perm,
463                );
464            }
465
466            return #[verus_spec(with |= Tracked(None))]
467            Err(err);
468        }
469        let tracked mut metadata_perm = slot_own.metadata_perm.take_resource();
470
471        // SAFETY: The slot now has a reference count of `0`, other threads will
472        // not access the metadata slot so it is safe to have a mutable reference.
473        unsafe {
474            #[verus_spec(with
475                Tracked(&mut metadata_perm),
476            )]
477            slot.write_meta(metadata)
478        };
479
480        proof {
481            slot_own.usage = metadata_perm.usage();
482            slot_own.metadata_perm.put_resource(metadata_perm);
483        }
484
485        if as_unique_ptr {
486            // No one can create a `Frame` instance directly from the page
487            // address, so `Relaxed` is fine here.
488            slot.ref_count.store(Tracked(&mut slot_own.ref_count_perm), REF_COUNT_UNIQUE);
489        } else {
490            // `Release` is used to ensure that the metadata initialization
491            // won't be reordered after this memory store.
492            slot.ref_count.store(Tracked(&mut slot_own.ref_count_perm), 1);
493        }
494        let tracked perm = if as_unique_ptr {
495            Some(Sum::Right(slot_own.metadata_perm.take_resource()))
496        } else {
497            Some(Sum::Left(slot_own.metadata_perm.split_one()))
498        };
499        // Origin Rust: Ok(slot as *const MetaSlot)
500        proof_with!(|= Tracked(perm));
501        Ok(ptr_from_addr(frame_to_meta(paddr), Tracked(slot_perm.tracked_borrow())))
502    }
503
504    /// Gets another owning pointer to the metadata slot from the given page.
505    /// # Verified Properties
506    /// We do not prove termination.
507    /// ## Preconditions
508    /// - **Safety Invariant**: Metaslot region invariants must hold.
509    /// - **Bookkeeping**: The slot permissions must be available in order to check the reference count.
510    /// This precondition is stronger than it needs to be; absent permissions correspond to error cases.
511    /// - **Liveness**: The reference count of the inner permissions must not be at the maximum, or the function will panic.
512    /// ## Postconditions
513    /// - **Safety**: Metaslot region invariants hold after the call.
514    /// - **Correctness**: If successful, the slot's reference count is increased by one.
515    /// - **Correctness**: If unsuccessful, the metaslot region remains unchanged.
516    /// ## Safety
517    /// The potential data race is avoided by the spin-lock.
518    #[verus_spec(res =>
519        with
520            Tracked(regions): Tracked<&mut MetaRegionOwners>,
521            -> permission: Tracked<Option<FracMetadataPerm>>,
522        requires
523            old(regions).inv(),
524            allowed_to_panic_if(valid_frame_paddr(paddr) && old(regions).ref_count(frame_to_index(paddr)) >= REF_COUNT_MAX),
525        ensures
526            final(regions).inv(),
527            res matches Ok(ptr) ==> {
528                &&& Self::get_from_in_use_success_spec(paddr, *old(regions), *final(regions), permission@->0)
529                &&& valid_frame_paddr(paddr)
530                &&& permission@ is Some
531                &&& ptr.addr() == frame_to_meta(paddr)
532                &&& ptr == final(regions).slots[frame_to_index(paddr)].ptr()
533            },
534            res is Err ==> {
535                &&& *final(regions) == *old(regions)
536                &&& permission@ is None
537            }
538    )]
539    #[verifier::exec_allows_no_decreases_clause]
540    pub(super) fn get_from_in_use(paddr: Paddr) -> Result<*const Self, GetFrameError> {
541        proof_decl! {
542            if valid_frame_paddr(paddr) {
543                regions.lemma_contains_valid_frame_paddr(paddr);
544            }
545            let tracked slot_perm = if valid_frame_paddr(paddr) {
546                Some(regions.tracked_borrow_slot(paddr))
547            } else {
548                None
549            };
550        }
551        let slot = match #[verus_spec(with Tracked(slot_perm))]
552        get_slot(paddr) {
553            Ok(slot) => slot,
554            Err(err) => {
555                return #[verus_spec(with |= Tracked(None))]
556                Err(err);
557            },
558        };
559
560        loop
561            invariant
562                *regions == *old(regions),
563                old(regions).inv(),
564                valid_frame_paddr(paddr),
565                regions.contains(frame_to_index(paddr)),
566                slot == regions.slots[frame_to_index(paddr)].value(),
567                slot_perm == Some(old(regions).slots[frame_to_index(paddr)]),
568                allowed_to_panic_if(old(regions).ref_count(frame_to_index(paddr)) >= REF_COUNT_MAX),
569        {
570            let tracked slot_own = regions.tracked_borrow_mut_slot_owner(paddr);
571
572            match slot.ref_count.load(Tracked(&mut slot_own.ref_count_perm)) {
573                REF_COUNT_UNUSED => {
574                    return #[verus_spec(with |= Tracked(None))]
575                    Err(GetFrameError::Unused);
576                },
577                REF_COUNT_UNIQUE => {
578                    return #[verus_spec(with |= Tracked(None))]
579                    Err(GetFrameError::Unique);
580                },
581                0 => {
582                    return #[verus_spec(with |= Tracked(None))]
583                    Err(GetFrameError::Busy);
584                },
585                last_ref_cnt => {
586                    if last_ref_cnt >= REF_COUNT_MAX {
587                        // See `Self::inc_ref_count` for the explanation.
588                        vstd_extra::panic::panic_diverge();
589                    }
590                    // Using `Acquire` here to pair with `get_from_unused` or
591                    // `<Frame<M> as From<UniqueFrame<M>>>::from` (who must be
592                    // performed after writing the metadata).
593                    //
594                    // It ensures that the written metadata will be visible to us.
595
596                    if slot.ref_count.compare_exchange_weak(
597                        Tracked(&mut slot_own.ref_count_perm),
598                        last_ref_cnt,
599                        last_ref_cnt + 1,
600                    ).is_ok() {
601                        let tracked permission = slot_own.metadata_perm.split_one();
602                        // Origin Rust: return Ok(slot as *const MetaSlot);
603                        return #[verus_spec(with |= Tracked(Some(permission)))]
604                        Ok(
605                            ptr_from_addr(
606                                frame_to_meta(paddr),
607                                Tracked(slot_perm.tracked_borrow()),
608                            ),
609                        );
610                    }
611                    proof {
612                        vstd_extra::auxiliary::axiom_permission_u64_ext_eq(
613                            slot_own.ref_count_perm,
614                            old(regions).slot_owner(paddr).ref_count_perm,
615                        );
616                    }
617
618                },
619            }
620            core::hint::spin_loop();
621        }
622    }
623
624    /// Increases the frame reference count by one.
625    ///
626    /// # Verified Properties
627    /// ## Preconditions
628    /// - **Bookkeeping**: The permission must match the reference count being updated.
629    /// - **Liveness**: The function will abort if the reference count is at the maximum.
630    /// ## Postconditions
631    /// - **Correctness**: The reference count is increased by one.
632    /// ## Safety
633    /// By requiring the caller to provide a permission for the reference count, we ensure that it already has a reference to the frame.
634    #[verus_spec(
635        with
636            Tracked(rc_perm): Tracked<&mut PermissionU64>,
637        requires
638            old(rc_perm).is_for(self.ref_count),
639            old(rc_perm).value() != REF_COUNT_UNUSED,
640            allowed_to_panic_if(old(rc_perm).value() >= REF_COUNT_MAX),
641        ensures
642            final(rc_perm).value() == old(rc_perm).value() + 1,
643            old(rc_perm).value() < REF_COUNT_MAX,
644            final(rc_perm).id() == old(rc_perm).id(),
645    )]
646    pub(super) unsafe fn inc_ref_count(&self) {
647        let last_ref_cnt = self.ref_count.fetch_add(Tracked(rc_perm), 1);
648
649        if last_ref_cnt >= REF_COUNT_MAX {
650            // This follows the same principle as the `Arc::clone` implementation to prevent the
651            // reference count from overflowing. See also
652            // <https://doc.rust-lang.org/std/sync/struct.Arc.html#method.clone>.
653            panic_diverge();
654        }
655    }
656
657    /// Gets the corresponding frame's physical address.
658    ///
659    /// # Verified Properties
660    /// ## Preconditions
661    /// - **Safety**: The permission must point to a valid metadata slot.
662    /// - **Correctness**: The permission must point to the metadata slot.
663    /// ## Postconditions
664    /// - **Correctness**: The function returns the physical address of the frame.
665    /// ## Safety
666    /// The safety precondition requires that the permission points to a valid metadata slot.
667    /// This is an internal function, so it is fine to require the caller to verify this.
668    #[verus_spec(
669        with
670            Tracked(perm): Tracked<&ExposedPointsTo<MetaSlot>>,
671        requires
672            perm.value() == self,
673            Self::frame_paddr_safety_cond(*perm),
674        returns
675            meta_to_frame(perm.addr()),
676    )]
677    pub(super) fn frame_paddr(&self) -> (pa: Paddr) {
678        proof_with!(Tracked(perm));
679        let addr = self.addr_of();
680        meta_to_frame(addr)
681    }
682
683    /*
684    /// Gets a dynamically typed pointer to the stored metadata.
685    ///
686    /// # Safety
687    ///
688    /// The caller should ensure that:
689    ///  - the stored metadata is initialized (by [`Self::write_meta`]) and valid.
690    ///
691    /// The returned pointer should not be dereferenced as mutable unless having
692    /// exclusive access to the metadata slot.
693
694    #[verifier::external_body]
695    pub(super) unsafe fn dyn_meta_ptr<M: AnyFrameMeta>(&self) -> PPtr<M> {
696        unimplemented!()
697
698        // SAFETY: The page metadata is valid to be borrowed immutably, since
699        // it will never be borrowed mutably after initialization.
700        let vtable_ptr = unsafe { *self.vtable_ptr.get() };
701
702        // SAFETY: The page metadata is initialized and valid.
703        let vtable_ptr = *unsafe { vtable_ptr.assume_init_ref() };
704
705        let meta_ptr: *mut dyn AnyFrameMeta =
706            core::ptr::from_raw_parts_mut(self as *const MetaSlot as *mut MetaSlot, vtable_ptr);
707
708        meta_ptr
709    }
710
711    /// Gets the stored metadata as type `M`.
712    ///
713    /// Calling the method should be safe, but using the returned pointer would
714    /// be unsafe. Specifically, the derefernecer should ensure that:
715    ///  - the stored metadata is initialized (by [`Self::write_meta`]) and
716    ///    valid;
717    ///  - the initialized metadata is of type `M`;
718    ///  - the returned pointer should not be dereferenced as mutable unless
719    ///    having exclusive access to the metadata slot.
720    pub(super) fn as_meta_ptr<M: AnyFrameMeta>(&self) -> *mut M {
721        self.storage.get() as *mut M
722    }
723
724    */
725    /// Writes the metadata to the slot without reading or dropping the previous value.
726    ///
727    /// # Safety
728    ///
729    /// The caller should have exclusive access to the metadata slot's fields.
730    ///
731    /// # Verification Design
732    /// This function is axiomatized for now because of trait constraints.
733    /// ## Preconditions
734    /// - The caller must provide the permission token to the metadata slot's storage.
735    /// ## Postconditions
736    /// - The permission is initialized to the new metadata.
737    /// ## Safety
738    /// The caller must have exclusive access to the metadata slot's storage in order to provide the permission token.
739    #[verus_spec(
740        with
741            Tracked(metadata_perm): Tracked<&mut MetadataPerm>,
742        requires
743            self.storage.id() == old(metadata_perm).storage_perm.id(),
744            self.vtable_ptr == old(metadata_perm).vtable_ptr_perm.pptr(),
745            old(metadata_perm).vtable_ptr_perm.is_uninit(),
746        ensures
747            final(metadata_perm).storage_perm.id() == old(metadata_perm).storage_perm.id(),
748            final(metadata_perm).storage_perm.is_init(),
749            final(metadata_perm).vtable_ptr_perm.pptr() == old(metadata_perm).vtable_ptr_perm.pptr(),
750            final(metadata_perm).vtable_ptr_perm.is_init(),
751            <M as Repr<MetaSlotStorage>>::wf(
752                final(metadata_perm).storage_perm.value(),
753            ),
754            M::from_repr_spec(
755                final(metadata_perm).storage_perm.value(),
756            ) == metadata,
757    )]
758    pub(super) unsafe fn write_meta<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf>(
759        &self,
760        metadata: M,
761    ) {
762        // SAFETY: Caller ensures that the access to the fields are exclusive.
763        //        let vtable_ptr = unsafe { &mut *self.vtable_ptr.get() };
764        //        vtable_ptr.write(core::ptr::metadata(&metadata as &dyn AnyFrameMeta));
765        self.vtable_ptr.put(Tracked(&mut metadata_perm.vtable_ptr_perm), 0);
766
767        // SAFETY:
768        // 1. `ptr` points to the metadata storage.
769        // 2. The size and the alignment of the metadata storage is large enough to hold `M`
770        //    (guaranteed by the const assertions above).
771        // 3. We have exclusive access to the metadata storage (guaranteed by the caller).
772        // unsafe { ptr.cast::<M>().write(metadata) };
773        write_metadata_into_storage(&self.storage, Tracked(metadata_perm), metadata);
774    }
775
776    /// Drops the metadata and deallocates the frame.
777    ///
778    /// # Safety
779    ///
780    /// The caller should ensure that:
781    ///  - the reference count is `0` (so we are the sole owner of the frame);
782    ///  - the metadata is initialized;
783    ///
784    /// # Verified Properties
785    /// ## Preconditions
786    /// - **Safety Invariant**: The metadata slot must satisfy the safety invariants.
787    /// - **Safety**: The caller must provide an owner object for the metadata slot, which must include the permission for the
788    /// slot's `ref_count` field.
789    /// - **Safety**: The owner must satisfy [`drop_last_in_place_safety_cond`], which ensures that its reference count is 0
790    /// and it has no dangling raw pointers.
791    /// ## Postconditions
792    /// - **Safety**: The metadata slot satisfies the safety invariants after the call.
793    /// - **Correctness**: The reference count is set to `REF_COUNT_UNUSED` and the contents of the slot are uninitialized.
794    /// ## Safety
795    /// - By requiring the caller to provide an owner object, we ensure that it already has a reference to the frame.
796    /// - The safety precondition ensures that there are no dangling pointers, including raw pointer, guaranteeing temporal safety.
797    #[verus_spec(
798        with
799            Tracked(owner): Tracked<&mut MetaSlotOwner>,
800        requires
801            old(owner).inv(),
802            self.ref_count.id() == old(owner).ref_count_perm.id(),
803            self.in_list.id() == old(owner).in_list_perm.id(),
804            self.storage.id() == old(owner).storage_perm().id(),
805            self.vtable_ptr == old(owner).vtable_ptr_perm().pptr(),
806            Self::drop_last_in_place_safety_cond(*old(owner)),
807        ensures
808            final(owner).inv(),
809            final(owner).ref_count() == REF_COUNT_UNUSED,
810            final(owner).ref_count_perm.id() == old(owner).ref_count_perm.id(),
811            final(owner).metadata_perm.id() == old(owner).metadata_perm.id(),
812            final(owner).storage_perm().id() == old(owner).storage_perm().id(),
813            final(owner).storage_perm().is_uninit(),
814            final(owner).vtable_ptr_perm().is_uninit(),
815            final(owner).vtable_ptr_perm().pptr() == old(owner).vtable_ptr_perm().pptr(),
816            final(owner).in_list_perm == old(owner).in_list_perm,
817            final(owner).slot_vaddr == old(owner).slot_vaddr,
818            final(owner).usage == old(owner).usage,
819            final(owner).paths_in_pt == old(owner).paths_in_pt,
820    )]
821    pub(super) unsafe fn drop_last_in_place(&self) {
822        // This should be guaranteed as a safety requirement.
823        //        debug_assert_eq!(self.ref_count.load(Ordering::Relaxed), 0);
824        let tracked mut metadata_perm = owner.metadata_perm.take_resource();
825        // SAFETY: The caller ensures safety.
826        unsafe {
827            #[verus_spec(with
828                Tracked(&owner.ref_count_perm),
829                Tracked(&owner.in_list_perm),
830                Tracked(&mut metadata_perm)
831            )]
832            self.drop_meta_in_place()
833        };
834        proof {
835            owner.metadata_perm.put_resource(metadata_perm);
836        }
837
838        // `Release` pairs with the `Acquire` in `Frame::from_unused` and ensures
839        // `drop_meta_in_place` won't be reordered after this memory store.
840        self.ref_count.store(Tracked(&mut owner.ref_count_perm), REF_COUNT_UNUSED);
841    }
842
843    /// Drops the metadata of a slot in place.
844    ///
845    /// After this operation, the metadata becomes uninitialized. Any access to the
846    /// metadata is undefined behavior unless it is re-initialized by [`Self::write_meta`].
847    ///
848    /// # Verification Design
849    /// This function is axiomatized because of its reliance on dynamic trait methods and `VmReader`.
850    /// The latter dependency makes it part of the "bootstrap gap".
851    /// Now that Verus better supports the `dyn Trait` pattern and we have verified `VmReader`, we can revisit it.
852    /// ## Preconditions
853    /// - The caller must provide the concrete permissions for the metadata slot.
854    /// - The reference count must be `0` or [`REF_COUNT_UNIQUE`].
855    /// ## Safety
856    ///
857    /// The caller should ensure that:
858    ///  - the reference count grants exclusive access (`0` or [`REF_COUNT_UNIQUE`]);
859    ///  - the metadata is initialized;
860    #[verifier::external_body]
861    #[verus_spec(
862        with
863            Tracked(ref_count_perm): Tracked<&PermissionU64>,
864            Tracked(in_list_perm): Tracked<&PermissionU64>,
865            Tracked(metadata_perm): Tracked<&mut MetadataPerm>,
866        requires
867            self.ref_count.id() == ref_count_perm.id(),
868            ref_count_perm.value() == 0 || ref_count_perm.value() == REF_COUNT_UNIQUE,
869            self.in_list.id() == in_list_perm.id(),
870            in_list_perm.value() == 0,
871            old(metadata_perm).storage_perm.is_init(),
872            old(metadata_perm).storage_perm.id() == self.storage.id(),
873            old(metadata_perm).vtable_ptr_perm.is_init(),
874            old(metadata_perm).vtable_ptr_perm.pptr() == self.vtable_ptr,
875        ensures
876            final(metadata_perm).storage_perm.is_uninit(),
877            final(metadata_perm).storage_perm.id() == old(metadata_perm).storage_perm.id(),
878            final(metadata_perm).vtable_ptr_perm.is_uninit(),
879            final(metadata_perm).vtable_ptr_perm.pptr()
880                == old(metadata_perm).vtable_ptr_perm.pptr(),
881    )]
882    pub(super) unsafe fn drop_meta_in_place(&self) {
883        let paddr = self.frame_paddr();
884
885        // SAFETY: We have exclusive access to the frame metadata.
886        let vtable_ptr: *const core::ptr::DynMetadata<dyn AnyFrameMeta> = unimplemented!();
887        // SAFETY: The frame metadata is initialized and valid.
888        let vtable_ptr = unsafe { *vtable_ptr };
889
890        let storage_ptr: *mut () = unimplemented!();
891        let meta_ptr: *mut dyn AnyFrameMeta = core::ptr::from_raw_parts_mut(
892            storage_ptr,
893            vtable_ptr,
894        );
895
896        // SAFETY: The implementer of the frame metadata decides that if the
897        // frame is safe to be read or not.
898        let mut reader: VmReader<'_, Infallible> = unimplemented!();
899
900        // SAFETY: `ptr` points to the metadata storage which is valid to be
901        // mutably borrowed under `vtable_ptr` because the metadata is valid,
902        // the vtable is correct, and we have exclusive access.
903        let regions: Tracked<&mut MetaRegionOwners> = Tracked::assume_new();
904        let vm_io_owner: Tracked<&mut crate::specs::mm::io::VmIoOwner> = Tracked::assume_new();
905        unsafe {
906            // Invoke the custom `on_drop` handler.
907            (*meta_ptr).on_drop(&mut reader, regions, vm_io_owner);
908            // Drop the frame metadata.
909            core::ptr::drop_in_place(meta_ptr);
910        }
911    }
912}
913
914/// The metadata of frames that holds metadata of frames.
915#[derive(Debug, Default)]
916pub struct MetaPageMeta {}
917
918//impl_frame_meta_for!(MetaPageMeta);
919/*
920/// Initializes the metadata of all physical frames.
921///
922/// The function returns a list of `Frame`s containing the metadata.
923///
924/// # Safety
925///
926/// This function should be called only once and only on the BSP,
927/// before any APs are started.
928pub(crate) unsafe fn init() -> Segment<MetaPageMeta> {
929    let max_paddr = {
930        let regions = &crate::boot::EARLY_INFO.get().unwrap().memory_regions;
931        regions
932            .iter()
933            .filter(|r| r.typ() == MemoryRegionType::Usable)
934            .map(|r| r.base() + r.len())
935            .max()
936            .unwrap()
937    };
938
939    info!(
940        "Initializing frame metadata for physical memory up to {:x}",
941        max_paddr
942    );
943
944    // In RISC-V, the boot page table has mapped the 512GB memory,
945    // so we don't need to add temporary linear mapping.
946    // In LoongArch, the DWM0 has mapped the whole memory,
947    // so we don't need to add temporary linear mapping.
948    #[cfg(target_arch = "x86_64")]
949    add_temp_linear_mapping(max_paddr);
950
951    let tot_nr_frames = max_paddr / page_size::<PagingConsts>(1);
952    let (nr_meta_pages, meta_pages) = alloc_meta_frames(tot_nr_frames);
953
954    // Map the metadata frames.
955    boot_pt::with_borrow(|boot_pt| {
956        for i in 0..nr_meta_pages {
957            let frame_paddr = meta_pages + i * PAGE_SIZE;
958            let vaddr = frame_to_meta::<PagingConsts>(0) + i * PAGE_SIZE;
959            let prop = PageProperty {
960                flags: PageFlags::RW,
961                cache: CachePolicy::Writeback,
962                priv_flags: PrivilegedPageFlags::GLOBAL,
963            };
964            // SAFETY: we are doing the metadata mappings for the kernel.
965            unsafe { boot_pt.map_base_page(vaddr, frame_paddr / PAGE_SIZE, prop) };
966        }
967    })
968    .unwrap();
969
970    // Now the metadata frames are mapped, we can initialize the metadata.
971    super::MAX_PADDR.store(max_paddr, Ordering::Relaxed);
972
973    let meta_page_range = meta_pages..meta_pages + nr_meta_pages * PAGE_SIZE;
974
975    let (range_1, range_2) = allocator::EARLY_ALLOCATOR
976        .lock()
977        .as_ref()
978        .unwrap()
979        .allocated_regions();
980    for r in range_difference(&range_1, &meta_page_range) {
981        let early_seg = Segment::from_unused(r, |_| EarlyAllocatedFrameMeta).unwrap();
982        let _ = ManuallyDrop::new(early_seg);
983    }
984    for r in range_difference(&range_2, &meta_page_range) {
985        let early_seg = Segment::from_unused(r, |_| EarlyAllocatedFrameMeta).unwrap();
986        let _ = ManuallyDrop::new(early_seg);
987    }
988
989    mark_unusable_ranges();
990
991    Segment::from_unused(meta_page_range, |_| MetaPageMeta {}).unwrap()
992}
993
994/// Returns whether the global frame allocator is initialized.
995pub(in crate::mm) fn is_initialized() -> bool {
996    // `init` sets it with relaxed ordering somewhere in the middle. But due
997    // to the safety requirement of the `init` function, we can assume that
998    // there is no race conditions.
999    super::MAX_PADDR.load(Ordering::Relaxed) != 0
1000}
1001
1002fn alloc_meta_frames(tot_nr_frames: usize) -> (usize, Paddr) {
1003    let nr_meta_pages = tot_nr_frames
1004        .checked_mul(size_of::<MetaSlot>())
1005        .unwrap()
1006        .div_ceil(PAGE_SIZE);
1007    let start_paddr = allocator::early_alloc(
1008        Layout::from_size_align(nr_meta_pages * PAGE_SIZE, PAGE_SIZE).unwrap(),
1009    )
1010    .unwrap();
1011
1012    let slots = paddr_to_vaddr(start_paddr) as *mut MetaSlot;
1013
1014    // Initialize the metadata slots.
1015    for i in 0..tot_nr_frames {
1016        // SAFETY: The memory is successfully allocated with `tot_nr_frames`
1017        // slots so the index must be within the range.
1018        let slot = unsafe { slots.add(i) };
1019        // SAFETY: The memory is just allocated so we have exclusive access and
1020        // it's valid for writing.
1021        unsafe {
1022            slot.write(MetaSlot {
1023                storage: UnsafeCell::new(MetaSlotStorage::Empty([0; FRAME_METADATA_MAX_SIZE - 1])),
1024                ref_count: AtomicU64::new(REF_COUNT_UNUSED),
1025                vtable_ptr: UnsafeCell::new(MaybeUninit::uninit()),
1026                in_list: AtomicU64::new(0),
1027            })
1028        };
1029    }
1030
1031    (nr_meta_pages, start_paddr)
1032}
1033
1034/// Unusable memory metadata. Cannot be used for any purposes.
1035#[derive(Debug)]
1036pub struct UnusableMemoryMeta;
1037impl_frame_meta_for!(UnusableMemoryMeta);
1038
1039/// Reserved memory metadata. Maybe later used as I/O memory.
1040#[derive(Debug)]
1041pub struct ReservedMemoryMeta;
1042impl_frame_meta_for!(ReservedMemoryMeta);
1043
1044/// The metadata of physical pages that contains the kernel itself.
1045#[derive(Debug, Default)]
1046pub struct KernelMeta;
1047impl_frame_meta_for!(KernelMeta);
1048
1049macro_rules! mark_ranges {
1050    ($region: expr, $typ: expr) => {{
1051        debug_assert!($region.base() % PAGE_SIZE == 0);
1052        debug_assert!($region.len() % PAGE_SIZE == 0);
1053
1054        let seg = Segment::from_unused($region.base()..$region.end(), |_| $typ).unwrap();
1055        let _ = ManuallyDrop::new(seg);
1056    }};
1057}
1058
1059fn mark_unusable_ranges() {
1060    let regions = &crate::boot::EARLY_INFO.get().unwrap().memory_regions;
1061
1062    for region in regions
1063        .iter()
1064        .rev()
1065        .skip_while(|r| r.typ() != MemoryRegionType::Usable)
1066    {
1067        match region.typ() {
1068            MemoryRegionType::BadMemory => mark_ranges!(region, UnusableMemoryMeta),
1069            MemoryRegionType::Unknown => mark_ranges!(region, ReservedMemoryMeta),
1070            MemoryRegionType::NonVolatileSleep => mark_ranges!(region, UnusableMemoryMeta),
1071            MemoryRegionType::Reserved => mark_ranges!(region, ReservedMemoryMeta),
1072            MemoryRegionType::Kernel => mark_ranges!(region, KernelMeta),
1073            MemoryRegionType::Module => mark_ranges!(region, UnusableMemoryMeta),
1074            MemoryRegionType::Framebuffer => mark_ranges!(region, ReservedMemoryMeta),
1075            MemoryRegionType::Reclaimable => mark_ranges!(region, UnusableMemoryMeta),
1076            MemoryRegionType::Usable => {} // By default it is initialized as usable.
1077        }
1078    }
1079}
1080
1081/// Adds a temporary linear mapping for the metadata frames.
1082///
1083/// We only assume boot page table to contain 4G linear mapping. Thus if the
1084/// physical memory is huge we end up depleted of linear virtual memory for
1085/// initializing metadata.
1086#[cfg(target_arch = "x86_64")]
1087fn add_temp_linear_mapping(max_paddr: Paddr) {
1088    const PADDR4G: Paddr = 0x1_0000_0000;
1089
1090    if max_paddr <= PADDR4G {
1091        return;
1092    }
1093
1094    // TODO: We don't know if the allocator would allocate from low to high or
1095    // not. So we prepare all linear mappings in the boot page table. Hope it
1096    // won't drag the boot performance much.
1097    let end_paddr = max_paddr.align_up(PAGE_SIZE);
1098    let prange = PADDR4G..end_paddr;
1099    let prop = PageProperty {
1100        flags: PageFlags::RW,
1101        cache: CachePolicy::Writeback,
1102        priv_flags: PrivilegedPageFlags::GLOBAL,
1103    };
1104
1105    // SAFETY: we are doing the linear mapping for the kernel.
1106    unsafe {
1107        boot_pt::with_borrow(|boot_pt| {
1108            for paddr in prange.step_by(PAGE_SIZE) {
1109                let vaddr = LINEAR_MAPPING_BASE_VADDR + paddr;
1110                boot_pt.map_base_page(vaddr, paddr / PAGE_SIZE, prop);
1111            }
1112        })
1113        .unwrap();
1114    }
1115}
1116*/
1117} // verus!