Skip to main content

ostd/mm/page_table/node/
child.rs

1// SPDX-License-Identifier: MPL-2.0
2//! This module specifies the type of the children of a page table node.
3use vstd::prelude::*;
4use vstd_extra::{cast_ptr::*, ownership::*};
5
6use crate::specs::{
7    arch::*,
8    mm::frame::{
9        frame_specs::FrameRawPerms,
10        mapping::{group_page_meta, meta_to_index},
11        meta_region_owners::MetaRegionOwners,
12    },
13    *,
14};
15
16use crate::mm::{
17    frame::{Frame, meta::mapping::meta_to_frame},
18    page_table::*,
19};
20
21use core::mem::ManuallyDrop;
22
23use super::{PageTableEntryTrait, PageTableNode, PageTableNodeRef};
24use crate::{
25    mm::{Paddr, PagingLevel, page_prop::PageProperty, page_table::PageTableConfig},
26    // sync::RcuDrop,
27};
28
29verus! {
30
31/// A page table entry that owns the child of a page table node if present.
32pub enum Child<C: PageTableConfig> {
33    /// A child page table node.
34    pub PageTable(PageTableNode<C>),
35    /// Physical address of a mapped physical frame.
36    ///
37    /// It is associated with the virtual page property and the level of the
38    /// mapping node, which decides the size of the frame.
39    pub Frame(Paddr, PagingLevel, PageProperty),
40    pub None,
41}
42
43#[verus_verify]
44impl<C: PageTableConfig> Child<C> {
45    /// Returns whether the child is not present.
46    #[vstd::contrib::auto_spec]
47    pub(in crate::mm) fn is_none(&self) -> (b: bool) {
48        matches!(self, Child::None)
49    }
50
51    /// # Verified Properties
52    /// ## Preconditions
53    /// - The child must match the supplied entry owner. For a page table node,
54    ///   the owning frame must hold the metadata permission and the
55    ///   entry owner's `node_permission` must be `None`.
56    /// - A mapped frame must satisfy the PTE implementation's
57    ///   [`new_page_req`](PageTableEntryTrait::new_page_req) requirements.
58    /// ## Postconditions
59    /// - For a page table node, its metadata permission moves into the
60    ///   entry owner's `node_permission`. All other owner fields are preserved;
61    ///   for a mapped frame or absent child, the owner is unchanged.
62    #[verus_spec(res =>
63        with Tracked(owner): Tracked<&mut EntryOwner<C>>,
64        requires
65            old(owner).inv(),
66            self.wf(*old(owner)),
67            self matches Child::Frame(paddr, level, prop) ==> C::E::new_page_req(paddr, level, prop),
68        ensures
69            final(owner).inv(),
70            final(owner).match_pte(res, final(owner).parent_level),
71            *final(owner) == old(owner).into_pte_owner_spec(self),
72            old(owner).is_node() ==> res == C::E::new_pt(
73                meta_to_frame(old(owner).node().slot_vaddr()),
74            ),
75    )]
76    pub fn into_pte(self) -> C::E {
77        proof {
78            C::E::lemma_page_table_entry_properties();
79        }
80
81        match self {
82            /* `mut` only permits transferring the erased token before forgetting the handle.
83             * Origin Rust: Child::PageTable(node) => {
84             */
85            Child::PageTable(mut node) => {
86                let paddr = node.start_paddr();
87                proof {
88                    owner.node_permission = Some(node.tracked_metadata_perm.tracked_take());
89                }
90                let _ = ManuallyDrop::new(node);
91                C::E::new_pt(paddr)
92            },
93            Child::Frame(paddr, level, prop) => { C::E::new_page(paddr, level, prop) },
94            Child::None => { C::E::new_absent() },
95        }
96    }
97
98    /// # Safety
99    ///
100    /// The provided PTE must be the output of [`Self::into_pte`], and the PTE:
101    ///  - must not be used to created a [`Child`] twice;
102    ///  - must not be referenced by a living [`ChildRef`].
103    ///
104    /// The level must match the original level of the child.
105    /// # Verified Properties
106    /// ## Preconditions
107    /// - The PTE, entry owner, and metadata region must satisfy
108    ///   [`EntryOwner::pte_invariants`], including ownership of the counted
109    ///   metadata permission for a page table node.
110    /// - `level` must equal the entry owner's parent level.
111    /// ## Postconditions
112    /// - For a page table node, the returned frame takes the entry owner's
113    ///   metadata permission, leaving `node_permission` as `None`.
114    ///   All other owner fields are preserved; for a mapped frame or absent
115    ///   entry, the owner is unchanged.
116    /// - The returned child satisfies [`Child::invariants`] with the updated
117    ///   entry owner and the supplied metadata region.
118    #[verus_spec(res =>
119        with Tracked(regions): Tracked<& MetaRegionOwners>,
120             Tracked(entry_own): Tracked<&mut EntryOwner<C>>,
121        requires
122            old(entry_own).pte_invariants(pte, *regions),
123            level == old(entry_own).parent_level,
124        ensures
125            res.invariants(*final(entry_own), *regions),
126            res == Child::<C>::from_pte_spec(pte, level, *regions, old(entry_own).node_permission),
127            *final(entry_own) == old(entry_own).from_pte_owner_spec(),
128    )]
129    pub unsafe fn from_pte(pte: C::E, level: PagingLevel) -> Self {
130        if !pte.is_present() {
131            return Child::None;
132        }
133        let paddr = pte.paddr();
134
135        if !pte.is_last(level) {
136            proof {
137                broadcast use group_page_meta;
138
139                regions.lemma_contains_valid_frame_paddr(paddr);
140            }
141            let tracked slot_perm = regions.tracked_borrow_slot(paddr);
142
143            let tracked permission = entry_own.tracked_take_node_permission();
144            // SAFETY: The caller ensures that this node was created by
145            // `into_pte`, so that restoring the forgotten reference is safe.
146            let node = unsafe {
147                #[verus_spec(with Tracked(FrameRawPerms {
148                    slot_perm,
149                    metadata_perm: permission,
150                }))]
151                PageTableNode::<C>::from_raw(paddr)
152            };
153
154            return Child::PageTable(node);
155        }
156        Child::Frame(paddr, level, pte.prop())
157    }
158}
159
160/// A reference to the child of a page table node.
161/// # Verification Design
162/// If the child is itself a page table node, it is represented by a [`PageTableNodeRef`],
163/// because a reference to it must be treated as a potentially shared reference of the appropriate lifetime.
164/// By contrast, a mapped frame can be referenced by just carrying its values, and an absent one is just a simple tag.
165pub enum ChildRef<'a, C: PageTableConfig> {
166    /// A child page table node.
167    PageTable(PageTableNodeRef<'a, C>),
168    /// Physical address of a mapped physical frame.
169    ///
170    /// It is associated with the virtual page property and the level of the
171    /// mapping node, which decides the size of the frame.
172    Frame(Paddr, PagingLevel, PageProperty),
173    None,
174}
175
176#[verus_verify]
177impl<'a, C: PageTableConfig> ChildRef<'a, C> {
178    /// Converts a PTE to a reference to a child.
179    ///
180    /// # Verified Properties
181    /// ## Preconditions
182    /// - **Safety Invariants**: the `PTE`'s [safety invariants](EntryOwner::pte_invariants) must hold.
183    /// - **Safety**: `level` must match the original level of the child.
184    /// ## Postconditions
185    /// - **Safety Invariants**: the [safety invariants](ChildRef::invariants) are preserved.
186    /// - **Correctness**: the `ChildRef` is equivalent to the original `PTE`.
187    /// - **Safety**: No frame other than the target entry's (if applicable) is impacted by the call.
188    /// ## Safety
189    /// - The caller guarantees the physical node remains alive for `'a`.
190    /// - A node result is a raw handle without a retained count borrow. Metadata
191    ///   access requires an actual external permission; it does not satisfy
192    ///   `FrameRef::inv()` by itself.
193    #[verus_spec(res =>
194        with Tracked(regions): Tracked<&MetaRegionOwners>,
195             Tracked(entry_owner): Tracked<&EntryOwner<C>>,
196        requires
197            entry_owner.pte_invariants(*pte, *regions),
198            level == entry_owner.parent_level,
199        ensures
200            res.invariants(*entry_owner, *regions),
201    )]
202    pub unsafe fn from_pte(pte: &C::E, level: PagingLevel) -> Self {
203        if !pte.is_present() {
204            return ChildRef::None;
205        }
206        let paddr = pte.paddr();
207
208        if !pte.is_last(level) {
209            proof {
210                broadcast use group_page_meta;
211
212            }
213
214            let tracked node_owner = entry_owner.tracked_borrow_node();
215            let tracked slot_perm = *regions.slots.tracked_borrow(node_owner.slot_index);
216            let node = unsafe {
217                #[verus_spec(with Tracked(slot_perm), Tracked(None))]
218                PageTableNodeRef::borrow_paddr(paddr)
219            };
220
221            return ChildRef::PageTable(node);
222        }
223        ChildRef::Frame(paddr, level, pte.prop())
224    }
225}
226
227} // verus!