Skip to main content

ostd/mm/page_table/node/
mod.rs

1// SPDX-License-Identifier: MPL-2.0
2//! This module defines page table node abstractions and the handle.
3//!
4//! The page table node is also frequently referred to as a page table in many architectural
5//! documentations. It is essentially a page that contains page table entries (PTEs) that map
6//! to child page tables nodes or mapped pages.
7//!
8//! This module leverages the page metadata to manage the page table pages, which makes it
9//! easier to provide the following guarantees:
10//!
11//! The page table node is not freed when it is still in use by:
12//!    - a parent page table node,
13//!    - or a handle to a page table node,
14//!    - or a processor.
15//!
16//! This is implemented by using a reference counter in the page metadata. If the above
17//! conditions are not met, the page table node is ensured to be freed upon dropping the last
18//! reference.
19//!
20//! One can acquire exclusive access to a page table node using merely the physical address of
21//! the page table node. This is implemented by a lock in the page metadata. Here the
22//! exclusiveness is only ensured for kernel code, and the processor's MMU is able to access the
23//! page table node while a lock is held. So the modification to the PTEs should be done after
24//! the initialization of the entity that the PTE points to. This is taken care in this module.
25//!
26mod child;
27mod entry;
28
29#[path = "../../../../specs/mm/page_table/node/child.rs"]
30mod child_specs;
31#[path = "../../../../specs/mm/page_table/node/entry.rs"]
32mod entry_specs;
33
34use vstd::{atomic::PAtomicU8, cell::pcell_maybe_uninit, prelude::*};
35use vstd_extra::{array_ptr, cast_ptr::*, ghost_tree::*, ownership::*};
36
37use crate::specs::mm::{
38    frame::{mapping::*, meta_owners::*, meta_region_owners::MetaRegionOwners},
39    page_table::node::owners::*,
40};
41
42use crate::mm::{
43    frame::meta::{MetaSlot, REF_COUNT_MAX, mapping::meta_to_frame},
44    page_table::*,
45};
46
47use core::{
48    //cell::SyncUnsafeCell,
49    marker::PhantomData,
50    ops::Deref,
51    sync::atomic::{AtomicU8, Ordering},
52};
53
54pub use self::{
55    child::{Child, ChildRef},
56    entry::Entry,
57};
58use super::{PageTableConfig, PageTableEntryTrait, nr_subpage_per_huge};
59use crate::{
60    mm::{
61        FrameAllocOptions, Infallible, PagingConstsTrait, PagingLevel, VmReader,
62        frame::{Frame, FrameRef, meta::AnyFrameMeta},
63        paddr_to_vaddr,
64        page_table::{load_pte, store_pte},
65    },
66    task::atomic_mode::InAtomicMode,
67};
68
69verus! {
70
71/// The metadata of any kinds of page table pages.
72/// Make sure the the generic parameters don't effect the memory layout.
73pub struct PageTablePageMeta<C: PageTableConfig> {
74    /// The number of valid PTEs. It is mutable if the lock is held.
75    pub nr_children: pcell_maybe_uninit::PCell<u16>,
76    /// If the page table is detached from its parent.
77    ///
78    /// A page table can be detached from its parent while still being accessed,
79    /// since we use a RCU scheme to recycle page tables. If this flag is set,
80    /// it means that the parent is recycling the page table.
81    pub stray: pcell_maybe_uninit::PCell<bool>,
82    /// The level of the page table page. A page table page cannot be
83    /// referenced by page tables of different levels.
84    pub level: PagingLevel,
85    /// The lock for the page table page.
86    pub lock: PAtomicU8,
87    pub _phantom: core::marker::PhantomData<C>,
88}
89
90/// A smart pointer to a page table node.
91///
92/// This smart pointer is an owner of a page table node. Thus creating and
93/// dropping it will affect the reference count of the page table node. If
94/// dropped it as the last reference, the page table node and subsequent
95/// children will be freed.
96///
97/// [`PageTableNode`] is read-only. To modify the page table node, lock and use
98/// [`PageTableGuard`].
99pub type PageTableNode<C> = Frame<PageTablePageMeta<C>>;
100
101unsafe impl<C: PageTableConfig> AnyFrameMeta for PageTablePageMeta<C> {
102    /// Caller invariants the PT-node `on_drop` body relies on:
103    /// - Reader well-formedness + `vm_io_owner` matching + read view
104    ///   initialized + at least `PAGE_SIZE` bytes remaining for the
105    ///   PT-node walk.
106    /// - Global region table invariant.
107    /// - Embedding ([`child_perms_embedding`]): for every paddr in
108    ///   `child_perms.dom()`, the slot and perm match `from_raw` /
109    ///   `VerifiedDrop::drop`'s expected shape.
110    /// - Walk coverage ([`walk_coverage_from_view`]): for every present
111    ///   non-last PTE in the page bytes, `frame_to_index(pte.paddr()) ∈
112    ///   child_perms.dom()`.
113    /// - Walk uniqueness ([`walk_uniqueness_from_view`]): distinct PTE
114    ///   positions with present non-last PTEs have distinct paddrs.
115    ///
116    /// Coverage and uniqueness retain the memory-safety premises needed by the
117    /// trusted destructor body, without storing item permissions in
118    /// [`VmIoOwner`](crate::specs::mm::io::VmIoOwner).
119    open spec fn on_drop_pre(
120        &self,
121        reader: crate::mm::VmReader<'_, crate::mm::Infallible>,
122        regions: crate::specs::mm::frame::meta_region_owners::MetaRegionOwners,
123        vm_io_owner: crate::specs::mm::io::VmIoOwner,
124    ) -> bool {
125        &&& reader.inv()
126        &&& reader.wf(vm_io_owner)
127        &&& reader.remain() >= crate::specs::arch::PAGE_SIZE
128        &&& reader.cursor.vaddr % core::mem::align_of::<C::E>() == 0
129        &&& vm_io_owner.inv()
130        &&& vm_io_owner.read_view_initialized()
131        &&& regions.inv()
132        &&& Self::child_perms_embedding(regions, vstd::set::Set::empty())
133        &&& self.walk_coverage_from_view(reader, vm_io_owner.read_view_of(), regions.slots.dom())
134        &&& self.walk_uniqueness_from_view(reader, vm_io_owner.read_view_of())
135    }
136
137    /// Drops the children of a page-table node.
138    ///
139    /// The permission handoff for recursively destroying page-table entries is
140    /// not modeled yet. Keep that trusted boundary local to this destructor;
141    /// `VmIoOwner` only supplies the memory view used by `reader`.
142    #[verifier::external_body]
143    fn on_drop(
144        &mut self,
145        reader: &mut crate::mm::VmReader<'_, crate::mm::Infallible>,
146        Tracked(regions): Tracked<
147            &mut crate::specs::mm::frame::meta_region_owners::MetaRegionOwners,
148        >,
149        Tracked(_vm_io_owner): Tracked<&mut crate::specs::mm::io::VmIoOwner>,
150    ) {
151        let level = self.level;
152        let range = if level == C::NR_LEVELS {
153            C::TOP_LEVEL_INDEX_RANGE
154        } else {
155            0..nr_subpage_per_huge::<C>()
156        };
157
158        reader.skip_in_place(range.start * core::mem::size_of::<C::E>());
159
160        for _ in range {
161            // Non-atomic read is OK because we have mutable access.
162            let pte = reader.read_once::<C::E>().unwrap();
163            if pte.is_present() {
164                let paddr = pte.paddr();
165                // As a fast path, we can ensure that the type of the child frame
166                // is `Self` if the PTE points to a child page table. Then we don't
167                // need to check the vtable for the drop method.
168                if !pte.is_last(level) {
169                    // SAFETY: The PTE points to a page table node. The ownership
170                    // of the child is transferred to the child then dropped.
171                    let frame = unsafe { Frame::<Self>::from_raw(paddr) };
172                    frame.drop(Tracked(regions));
173                } else {
174                    proof_decl! {
175                        let tracked item_perm: Option<C::Perm>;
176                    }
177                    // SAFETY: The PTE points to a mapped item. The ownership
178                    // of the item is transferred here then dropped.
179                    let _item = unsafe {
180                        C::item_from_raw(paddr, level, pte.prop(), Tracked(item_perm))
181                    };
182                }
183            }
184        }
185    }
186
187    fn is_untyped(&self) -> bool {
188        false
189    }
190
191    uninterp spec fn vtable_ptr(&self) -> usize;
192}
193
194#[verus_verify]
195impl<C: PageTableConfig> PageTableNode<C> {
196    /// Gets the level of a page table node.
197    /// # Verified Properties
198    /// ## Preconditions
199    /// - The node must have valid typed metadata, using either its own permission or one supplied by the caller.
200    /// ## Postconditions
201    /// - Returns the level stored in the node's metadata.
202    /// ## Safety
203    /// - The metadata permission ensures that this function is only called on a valid page table node.
204    #[verus_spec(
205        with
206            Tracked(metadata_perm): Tracked<Option<&MetadataPerm>>,
207    )]
208    pub(super) fn level(&self) -> PagingLevel
209        requires
210            metadata_perm matches Some(permission) ==> self.external_meta_wf(*permission),
211            metadata_perm is None ==> {
212                &&& self.inv()
213                &&& typed_meta_wf::<PageTablePageMeta<C>>(self.slot_perm(), self.metadata_perm())
214            },
215        returns
216            typed_meta_value::<PageTablePageMeta<C>>(
217                if metadata_perm is Some {
218                    *metadata_perm->0
219                } else {
220                    self.metadata_perm()
221                },
222            ).level,
223    {
224        #[verus_spec(with
225            Tracked(metadata_perm),
226        )]
227        let meta = self.meta();
228        meta.level
229    }
230
231    /// Allocates a new empty page table node.
232    #[verus_spec(res =>
233        with Tracked(regions): Tracked<&mut MetaRegionOwners>,
234             Tracked(guards): Tracked<&Guards>,
235                 -> owner: Tracked<OwnerSubtree<C>>,
236        requires
237            1 <= level < C::NR_LEVELS,
238            old(regions).inv(),
239        ensures
240            final(regions).inv(),
241            allocated_empty_node_owner(owner@, level),
242            allocated_empty_node_grandchildren_none(owner@),
243            res.slot_vaddr() == owner@.value().node().slot_vaddr(),
244            res.inv(),
245            owner@.value().node_permission is None,
246            owner@.value().node().matches_permission(res.frac_metadata_perm()),
247            typed_meta_wf::<PageTablePageMeta<C>>(res.slot_perm(), res.metadata_perm()),
248            res.tracked_slot_perm@ == final(regions).slots[owner@.value().node().slot_index],
249            guards.unlocked(owner@.value().node().slot_vaddr()),
250            MetaSlot::claim_unused_slot_region_spec(
251                meta_to_frame(owner@.value().node().slot_vaddr()),
252                false, *old(regions), *final(regions)),
253
254            old(regions).contains(meta_to_index(owner@.value().node().slot_vaddr())),
255
256            final(regions).slot_owners[owner@.value().node().slot_index].paths_in_pt.is_empty(),
257            owner@.value().match_pte(C::E::new_pt(meta_to_frame(owner@.value().node().slot_vaddr())), (level + 1) as PagingLevel),
258            final(regions).contains(owner@.value().node().slot_index),
259            owner@.value().node().metaregion_sound_node(*final(regions)),
260    )]
261    #[verifier::external_body]
262    pub fn alloc<'rcu>(level: PagingLevel) -> Self {
263        let tracked entry_owner = EntryOwner::tracked_new_absent(
264            TreePath::new(Seq::empty()),
265            level,
266        );
267
268        let tracked mut owner = OwnerSubtree::<C>::tracked_new_val(entry_owner, level as nat);
269        let meta = PageTablePageMeta::new(level);
270        let mut frame = FrameAllocOptions::new();
271        frame.zeroed(true);
272        let allocated_frame = frame.alloc_frame_with(meta).expect(
273            "Failed to allocate a page table node",
274        );
275        // The allocated frame is zeroed. Make sure zero is absent PTE.
276        //debug_assert_eq!(C::E::new_absent().as_usize(), 0);
277
278        proof_with!(|= Tracked(owner));
279
280        allocated_frame
281    }/*
282    /// Activates the page table assuming it is a root page table.
283    ///
284    /// Here we ensure not dropping an active page table by making a
285    /// processor a page table owner. When activating a page table, the
286    /// reference count of the last activated page table is decremented.
287    /// And that of the current page table is incremented.
288    ///
289    /// # Safety
290    ///
291    /// The caller must ensure that the page table to be activated has
292    /// proper mappings for the kernel and has the correct const parameters
293    /// matching the current CPU.
294    ///
295    /// # Panics
296    ///
297    /// Only top-level page tables can be activated using this function.
298    pub(crate) unsafe fn activate(&self) {
299        use crate::{
300            arch::mm::{activate_page_table, current_page_table_paddr},
301            mm::page_prop::CachePolicy,
302        };
303
304        #[cfg(feature = "allow_panic")]
305        assert_eq!(self.level(), C::NR_LEVELS);
306
307        let last_activated_paddr = current_page_table_paddr();
308        if last_activated_paddr == self.start_paddr() {
309            return;
310        }
311
312        // SAFETY: The safety is upheld by the caller.
313        unsafe { activate_page_table(self.clone().into_raw(), CachePolicy::Writeback) };
314
315        // Restore and drop the last activated page table.
316        // SAFETY: The physical address is valid and points to a forgotten page table node.
317        drop(unsafe { Self::from_raw(last_activated_paddr) });
318    }
319
320    /// Activates the (root) page table assuming it is the first activation.
321    ///
322    /// It will not try dropping the last activate page table. It is the same
323    /// with [`Self::activate()`] in other senses.
324    pub(super) unsafe fn first_activate(&self) {
325        use crate::{arch::mm::activate_page_table, mm::page_prop::CachePolicy};
326
327        // SAFETY: The safety is upheld by the caller.
328        unsafe { activate_page_table(self.clone().into_raw(), CachePolicy::Writeback) };
329    }*/
330
331}
332
333/// A reference to a page table node.
334pub type PageTableNodeRef<'a, C> = FrameRef<'a, PageTablePageMeta<C>>;
335
336#[verus_verify]
337impl<'a, C: PageTableConfig> PageTableNodeRef<'a, C> {
338    pub open spec fn locks_preserved_except<'rcu>(
339        addr: usize,
340        guards0: Guards,
341        guards1: Guards,
342    ) -> bool {
343        &&& OwnerSubtree::implies(
344            CursorOwner::<'rcu, C>::node_unlocked(guards0),
345            CursorOwner::<'rcu, C>::node_unlocked_except(guards1, addr),
346        )
347        &&& forall|i: usize| guards0.lock_held(i) ==> guards1.lock_held(i)
348        &&& forall|i: usize| guards0.unlocked(i) && i != addr ==> guards1.unlocked(i)
349    }
350
351    /// Locks the page table node.
352    ///
353    /// An atomic mode guard is required to
354    ///  1. prevent deadlocks;
355    ///  2. provide a lifetime (`'rcu`) that the nodes are guaranteed to outlive.
356    /// # Verification Design
357    /// As of when we verified this library, we didn't have a spin lock implementation, so we axiomatize
358    /// what happens when it's successful.
359    #[verifier::external_body]
360    #[verus_spec(res =>
361        with Tracked(guards): Tracked<&mut Guards>,
362            Tracked(metadata_perm): Tracked<&MetadataPerm>,
363        requires
364            self.external_meta_wf(*metadata_perm),
365            self@.tracked_metadata_perm@ is Some ==> self.inv(),
366            old(guards).unlocked(self.slot_vaddr()),
367        ensures
368            final(guards).lock_held(self.slot_vaddr()),
369            Self::locks_preserved_except(self.slot_vaddr(), *old(guards), *final(guards)),
370            res.inner == self,
371    )]
372    pub fn lock<'rcu>(self, _guard: &'rcu dyn InAtomicMode) -> PageTableGuard<'rcu, C> where
373        'a: 'rcu,
374     {
375        unimplemented!()
376    }
377
378    /// Creates a new [`PageTableGuard`] without checking if the page table lock is held.
379    ///
380    /// # Safety
381    ///
382    /// This function must be called if this task logically holds the lock.
383    ///
384    /// Calling this function when a guard is already created is undefined behavior
385    /// unless that guard was already forgotten.
386    #[verus_spec(res =>
387        with Tracked(guards): Tracked<&mut Guards>,
388        requires
389            self@.ptr_inv(),
390            self@.tracked_metadata_perm@ is Some ==> self.inv(),
391            old(guards).unlocked(self.slot_vaddr()),
392        ensures
393            final(guards).lock_held(self.slot_vaddr()),
394            Self::locks_preserved_except(self.slot_vaddr(), *old(guards), *final(guards)),
395            res.inner == self,
396    )]
397    pub unsafe fn make_guard_unchecked<'rcu>(
398        self,
399        _guard: &'rcu dyn InAtomicMode,
400    ) -> PageTableGuard<'rcu, C> where 'a: 'rcu {
401        let guard = PageTableGuard { inner: self };
402
403        proof {
404            guards.guards = guards.guards.insert(guard.inner.slot_vaddr());
405        }
406
407        guard
408    }
409}
410
411/// A guard that holds the lock of a page table node.
412pub struct PageTableGuard<'rcu, C: PageTableConfig> {
413    pub inner: PageTableNodeRef<'rcu, C>,
414}
415
416impl<'rcu, C: PageTableConfig> PageTableGuard<'rcu, C> {
417    /// Borrows an entry in the node at a given index.
418    ///
419    /// # Panics
420    ///
421    /// Panics if the index is not within the bound of
422    /// [`nr_subpage_per_huge<C>`].
423    #[verus_spec(res =>
424        with Tracked(owner): Tracked<&NodeOwner<C>>,
425             Tracked(child_owner): Tracked<&EntryOwner<C>>,
426             Tracked(regions): Tracked<&MetaRegionOwners>,
427        requires
428            owner.inv(),
429            child_owner.inv(),
430            owner.relate_guard(*old(self)),
431            child_owner.match_pte(
432                owner.children_perm.value()[idx as int],
433                child_owner.parent_level,
434            ),
435            regions.inv(),
436            regions.contains(owner.slot_index),
437            // Panic condition
438            idx < NR_ENTRIES,
439        ensures
440            res.wf(*child_owner),
441            res.idx == idx,
442            *res.node == *old(self),
443            *final(self) == *final(res.node),
444            owner.relate_guard(*res.node),
445    )]
446    pub fn entry<'a>(&'a mut self, idx: usize) -> Entry<'a, 'rcu, C> {
447        #[cfg(feature = "allow_panic")]
448        assert!(idx < nr_subpage_per_huge::<C>());
449        // SAFETY: The index is within the bound. `Entry::new_at` returns an
450        // entry whose node is the guard value we were handed.
451        unsafe {
452            #[verus_spec(with Tracked(child_owner), Tracked(owner), Tracked(regions))]
453            Entry::new_at(self, idx)
454        }
455    }
456
457    /// Gets the number of valid PTEs in a page table node.
458    /// # Verified Properties
459    /// ## Preconditions
460    /// - The node must be well-formed.
461    /// ## Postconditions
462    /// - Returns the number of valid PTEs in the node.
463    /// ## Safety
464    /// - We require the caller to provide a permission token to ensure that this function is only called on a valid page table node.
465    #[verus_spec(nr =>
466        with Tracked(nr_children_perm): Tracked<&pcell_maybe_uninit::PointsTo<u16>>,
467            Tracked(metadata_perm): Tracked<&MetadataPerm>,
468        requires
469            nr_children_perm.is_init(),
470            nr_children_perm.id() == typed_meta_value::<PageTablePageMeta<C>>(*metadata_perm).nr_children.id(),
471            self.inner.external_meta_wf(*metadata_perm),
472        returns
473            nr_children_perm.value(),
474    )]
475    pub fn nr_children(&self) -> u16 {
476        #[verus_spec(with
477            Tracked(Some(metadata_perm)),
478        )]
479        let meta = self.meta();
480
481        *meta.nr_children.borrow(Tracked(nr_children_perm))
482    }
483
484    /// Returns if the page table node is detached from its parent.
485    #[verus_spec(res =>
486        with
487            Tracked(metadata_perms): Tracked<&'a MetadataPerm>,
488            Ghost(stray_id): Ghost<vstd::cell::CellId>,
489        requires
490            old(self).inner.external_meta_wf(*metadata_perms),
491            typed_meta_value::<PageTablePageMeta<C>>(
492                *metadata_perms,
493            ).stray.id()
494                == stray_id,
495        ensures
496            res.id() == stray_id,
497            *final(self) == *old(self),
498    )]
499    pub(super) fn stray_mut<'a>(&'a mut self) -> &'a pcell_maybe_uninit::PCell<bool> {
500        // SAFETY: The lock is held so we have an exclusive access.
501        #[verus_spec(with
502            Tracked(Some(metadata_perms)),
503        )]
504        let meta = self.meta();
505        &meta.stray
506    }
507
508    /// Reads a non-owning PTE at the given index.
509    ///
510    /// A non-owning PTE means that it does not account for a reference count
511    /// of the a page if the PTE points to a page. The original PTE still owns
512    /// the child page.
513    ///
514    /// # Safety
515    ///
516    /// The caller must ensure that the index is within the bound.
517    #[verus_spec(
518        with Tracked(owner): Tracked<&NodeOwner<C>>,
519             Tracked(regions): Tracked<&MetaRegionOwners>,
520        requires
521            self.inner@.invariants(*owner),
522            regions.inv(),
523            regions.contains(owner.slot_index),
524            idx < NR_ENTRIES,
525        returns
526            owner.children_perm.value()[idx as int],
527    )]
528    pub unsafe fn read_pte(&self, idx: usize) -> C::E {
529        // debug_assert!(idx < nr_subpage_per_huge::<C>());
530        let ptr = vstd_extra::array_ptr::ArrayPtr::<C::E, NR_ENTRIES>::from_addr(
531            paddr_to_vaddr(self.start_paddr()),
532        );
533
534        // SAFETY:
535        // - The page table node is alive. The index is inside the bound, so the page table entry is valid.
536        // - All page table entries are aligned and accessed with atomic operations only.
537        unsafe {
538            #[verus_spec(with Tracked(&owner.children_perm))]
539            load_pte(ptr.add(idx), Ordering::Relaxed)
540        }
541    }
542
543    /// Writes a page table entry at a given index.
544    ///
545    /// This operation will leak the old child if the old PTE is present.
546    ///
547    /// # Safety
548    ///
549    /// The caller must ensure that:
550    ///  1. The index must be within the bound;
551    ///  2. The PTE must represent a valid [`Child`] whose level is compatible
552    ///     with the page table node.
553    ///  3. The page table node will have the ownership of the [`Child`]
554    ///     after this method.
555    #[verus_spec(
556        with Tracked(owner): Tracked<&mut NodeOwner<C>>,
557             Tracked(regions): Tracked<&MetaRegionOwners>,
558        requires
559            old(self).inner@.invariants(*old(owner)),
560            regions.inv(),
561            regions.contains(old(owner).slot_index),
562            idx < NR_ENTRIES,
563        ensures
564            final(owner).inv(),
565            final(owner).level() == old(owner).level(),
566            final(owner).meta_own == old(owner).meta_own,
567            final(owner).metadata == old(owner).metadata,
568            final(owner).metadata_id == old(owner).metadata_id,
569            final(owner).slot_index == old(owner).slot_index,
570            final(owner).tree_level == old(owner).tree_level,
571            final(owner).children_perm.value() == old(owner).children_perm.value().update(
572                idx as int,
573                pte,
574            ),
575            *final(self) == *old(self),
576    )]
577    pub unsafe fn write_pte(&mut self, idx: usize, pte: C::E) {
578        // debug_assert!(idx < nr_subpage_per_huge::<C>());
579        #[verusfmt::skip]
580        let ptr = vstd_extra::array_ptr::ArrayPtr::<C::E, NR_ENTRIES>::from_addr(
581            paddr_to_vaddr(self.start_paddr())
582        );
583
584        // SAFETY:
585        // - The page table node is alive. The index is inside the bound, so the page table entry is valid.
586        // - All page table entries are aligned and accessed with atomic operations only.
587        unsafe {
588            #[verus_spec(with Tracked(&mut owner.children_perm))]
589            store_pte(ptr.add(idx), pte, Ordering::Release)
590        }
591        proof {
592            assert(owner.children_perm.wf());
593        }
594    }
595
596    /// Gets the mutable reference to the number of valid PTEs in the node.
597    #[verus_spec(res =>
598        with
599            Tracked(metadata_perms): Tracked<&'a MetadataPerm>,
600            Ghost(nr_children_id): Ghost<vstd::cell::CellId>,
601        requires
602            old(self).inner.external_meta_wf(*metadata_perms),
603            typed_meta_value::<PageTablePageMeta<C>>(
604                *metadata_perms).nr_children.id()
605                == nr_children_id,
606        ensures
607            res.id() == nr_children_id,
608            *final(self) == *old(self),
609    )]
610    fn nr_children_mut<'a>(&'a mut self) -> &'a pcell_maybe_uninit::PCell<u16> {
611        // SAFETY: The lock is held so we have an exclusive access.
612        #[verus_spec(with
613            Tracked(Some(metadata_perms)),
614        )]
615        let meta = self.meta();
616        &meta.nr_children
617    }
618}
619
620impl<'rcu, C: PageTableConfig> Deref for PageTableGuard<'rcu, C> {
621    type Target = PageTableNodeRef<'rcu, C>;
622
623    #[verus_spec(ensures returns self.inner)]
624    fn deref(&self) -> &Self::Target {
625        &self.inner
626    }
627}
628
629/*impl<C: PageTableConfig> Drop for PageTableGuard<'_, C> {
630    fn drop(&mut self) {
631        self.inner.meta().lock.store(0, Ordering::Release);
632    }
633}*/
634
635impl<C: PageTableConfig> PageTablePageMeta<C> {
636    pub fn new(level: PagingLevel) -> Self {
637        Self {
638            nr_children: pcell_maybe_uninit::PCell::new(0).0,
639            stray: pcell_maybe_uninit::PCell::new(false).0,
640            level,
641            lock: PAtomicU8::new(0).0,
642            _phantom: PhantomData,
643        }
644    }
645
646    /// The PTE value that `read_once::<C::E>` would produce at cursor `c`
647    /// against the given memory view. Linked to `read_once` via
648    /// `pod_bytes(v) == read_view.read_bytes(...)` (strengthened ensures)
649    /// and the checked byte-decoding model.
650    pub open spec fn walk_pte_at_view(view: crate::specs::mm::virt_mem::MemView, c: usize) -> C::E {
651        ostd_pod::decode_pod::<C::E>(view.read_bytes(c, core::mem::size_of::<C::E>()))
652    }
653
654    /// Single-cursor projection of [`walk_coverage_from_view`]. Extracting
655    /// the forall body to a named predicate lets the body invoke
656    /// [`lemma_coverage_at`] for one specific `c` instead of relying on
657    /// auto-trigger matching across the loop invariant's `forall|c|`.
658    pub open spec fn walk_coverage_at(
659        self,
660        view: crate::specs::mm::virt_mem::MemView,
661        dom: vstd::set::Set<int>,
662        c: usize,
663    ) -> bool {
664        let pte = Self::walk_pte_at_view(view, c);
665        pte.is_present() && !pte.is_last(self.level) ==> dom.contains(frame_to_index(pte.paddr()))
666    }
667
668    /// Instantiate [`walk_coverage_from_view`]'s forall at one cursor.
669    pub proof fn lemma_coverage_at(
670        self,
671        reader: crate::mm::VmReader<'_, crate::mm::Infallible>,
672        view: crate::specs::mm::virt_mem::MemView,
673        dom: vstd::set::Set<int>,
674        c: usize,
675    )
676        requires
677            self.walk_coverage_from_view(reader, view, dom),
678            reader.cursor.vaddr <= c,
679            c + core::mem::size_of::<C::E>() <= reader.cursor.vaddr + reader.remain(),
680            (c - reader.cursor.vaddr) % core::mem::size_of::<C::E>() as int == 0,
681        ensures
682            self.walk_coverage_at(view, dom, c),
683    {
684    }
685
686    /// Caller-side dom-membership obligation: every present non-last PTE
687    /// position in the walk (over `view`) has its child-frame index in
688    /// `dom`. Phrased over a frozen `(view, dom)` pair so the body can
689    /// carry it as a loop invariant against an entry-state snapshot
690    /// while `vm_io_owner` advances per iteration.
691    pub open spec fn walk_coverage_from_view(
692        self,
693        reader: crate::mm::VmReader<'_, crate::mm::Infallible>,
694        view: crate::specs::mm::virt_mem::MemView,
695        dom: vstd::set::Set<int>,
696    ) -> bool {
697        forall|c: usize|
698            #![trigger Self::walk_pte_at_view(view, c)]
699            reader.cursor.vaddr <= c && c + core::mem::size_of::<C::E>() <= reader.cursor.vaddr
700                + reader.remain() && (c - reader.cursor.vaddr) % core::mem::size_of::<C::E>() as int
701                == 0 ==> {
702                let pte = Self::walk_pte_at_view(view, c);
703                pte.is_present() && !pte.is_last(self.level) ==> dom.contains(
704                    frame_to_index(pte.paddr()),
705                )
706            }
707    }
708
709    /// Caller-side uniqueness obligation: distinct cursor positions with
710    /// present non-last PTEs (in `view`) map to distinct paddrs.
711    pub open spec fn walk_uniqueness_from_view(
712        self,
713        reader: crate::mm::VmReader<'_, crate::mm::Infallible>,
714        view: crate::specs::mm::virt_mem::MemView,
715    ) -> bool {
716        forall|c1: usize, c2: usize|
717            #![trigger Self::walk_pte_at_view(view, c1), Self::walk_pte_at_view(view, c2)]
718            reader.cursor.vaddr <= c1 && c1 + core::mem::size_of::<C::E>() <= reader.cursor.vaddr
719                + reader.remain() && (c1 - reader.cursor.vaddr) % core::mem::size_of::<
720                C::E,
721            >() as int == 0 && reader.cursor.vaddr <= c2 && c2 + core::mem::size_of::<C::E>()
722                <= reader.cursor.vaddr + reader.remain() && (c2 - reader.cursor.vaddr)
723                % core::mem::size_of::<C::E>() as int == 0 && c1 != c2 ==> {
724                let pte1 = Self::walk_pte_at_view(view, c1);
725                let pte2 = Self::walk_pte_at_view(view, c2);
726                pte1.is_present() && !pte1.is_last(self.level) && pte2.is_present()
727                    && !pte2.is_last(self.level) ==> pte1.paddr() != pte2.paddr()
728            }
729    }
730
731    /// Caller-side shape obligation: every paddr in `child_perms.dom()`
732    /// has a slot perm matching the shape `from_raw` + `VerifiedDrop::drop`
733    /// expect (init, alignment, refcount within bounds, last-reference
734    /// shape when refcount == 1).
735    pub open spec fn child_perms_embedding(
736        regions: crate::specs::mm::frame::meta_region_owners::MetaRegionOwners,
737        excluded: vstd::set::Set<int>,
738    ) -> bool {
739        forall|paddr: crate::mm::Paddr|
740            #![trigger regions.slot_owner(paddr)]
741            regions.slots.dom().contains(frame_to_index(paddr)) && !excluded.contains(
742                frame_to_index(paddr),
743            ) ==> {
744                let idx = frame_to_index(paddr);
745                let so = regions.slot_owners[idx];
746                &&& <Frame<Self>>::from_raw_requires(regions, paddr)
747                &&& 0 < so.ref_count() <= REF_COUNT_MAX
748                &&& so.storage_perm().is_init()
749                &&& so.ref_count() == 1 ==> {
750                    &&& so.in_list_perm.value() == 0
751                    &&& so.paths_in_pt.is_empty()
752                }
753            }
754    }
755}
756
757} // verus!