Skip to main content

ostd/specs/mm/page_table/node/
owners.rs

1use vstd::{
2    cell::{self, pcell_maybe_uninit},
3    prelude::*,
4    resource::Loc,
5};
6use vstd_extra::{array_ptr, ownership::*};
7
8use crate::specs::{
9    arch::*,
10    mm::{
11        frame::{mapping::*, meta_owners::*, meta_region_owners::MetaRegionOwners},
12        page_table::owners::tree_level_for,
13    },
14};
15
16use crate::mm::{
17    Paddr, PagingConstsTrait, PagingLevel, Vaddr,
18    frame::meta::{META_SLOT_SIZE, MetaSlot, REF_COUNT_MAX, mapping::meta_to_frame},
19    kspace::{FRAME_METADATA_RANGE, LINEAR_MAPPING_BASE_VADDR, VMALLOC_BASE_VADDR},
20    paddr_to_vaddr,
21    page_table::{PageTableGuard, *},
22};
23
24verus! {
25
26// ─── Present-PTE counting ──────────────────────────────────────────────────────
27// The intended meaning of `nr_children`: the number of *present* PTEs in the
28// node's `children_perm` array. `metaregion_sound_node` ties `nr_children` to
29// `count_present(children_perm.value())` (a settled-node invariant), which lets
30// the `nr_children_*_slot_bound` boundary facts be proven rather than axiomatized.
31/// Number of present PTEs among the first `n` entries of `s`.
32pub open spec fn count_present_upto<E: PageTableEntryTrait>(s: Seq<E>, n: int) -> int
33    decreases n,
34{
35    if n <= 0 {
36        0
37    } else {
38        count_present_upto(s, n - 1) + if s[n - 1].is_present() {
39            1int
40        } else {
41            0int
42        }
43    }
44}
45
46/// Number of present PTEs in `s`.
47pub open spec fn count_present<E: PageTableEntryTrait>(s: Seq<E>) -> int {
48    count_present_upto(s, s.len() as int)
49}
50
51/// `count_present_upto` is between `0` and `n`.
52pub proof fn lemma_count_present_upto_bound<E: PageTableEntryTrait>(s: Seq<E>, n: int)
53    requires
54        0 <= n,
55    ensures
56        0 <= count_present_upto(s, n) <= n,
57    decreases n,
58{
59    if n > 0 {
60        lemma_count_present_upto_bound(s, n - 1);
61    }
62}
63
64/// An absent slot below `n` makes the count strictly less than `n`.
65pub proof fn lemma_count_present_upto_absent<E: PageTableEntryTrait>(s: Seq<E>, n: int, idx: int)
66    requires
67        0 <= idx < n,
68        !s[idx].is_present(),
69    ensures
70        count_present_upto(s, n) < n,
71    decreases n,
72{
73    lemma_count_present_upto_bound(s, n - 1);
74    if idx < n - 1 {
75        lemma_count_present_upto_absent(s, n - 1, idx);
76    }
77}
78
79/// A present slot below `n` makes the count at least `1`.
80pub proof fn lemma_count_present_upto_present<E: PageTableEntryTrait>(s: Seq<E>, n: int, idx: int)
81    requires
82        0 <= idx < n,
83        s[idx].is_present(),
84    ensures
85        count_present_upto(s, n) >= 1,
86    decreases n,
87{
88    lemma_count_present_upto_bound(s, n - 1);
89    if idx < n - 1 {
90        lemma_count_present_upto_present(s, n - 1, idx);
91    }
92}
93
94/// Updating slot `idx` (with `idx < n`) shifts the count by the change in that
95/// slot's present-indicator.
96pub proof fn lemma_count_present_upto_update<E: PageTableEntryTrait>(
97    s: Seq<E>,
98    n: int,
99    idx: int,
100    pte: E,
101)
102    requires
103        0 <= idx < n <= s.len(),
104    ensures
105        count_present_upto(s.update(idx, pte), n) == count_present_upto(s, n) - (
106        if s[idx].is_present() {
107            1int
108        } else {
109            0int
110        }) + (if pte.is_present() {
111            1int
112        } else {
113            0int
114        }),
115    decreases n,
116{
117    let s2 = s.update(idx, pte);
118    if n - 1 == idx {
119        // The first `idx` entries are unchanged.
120        assert(count_present_upto(s2, n - 1) == count_present_upto(s, n - 1)) by {
121            lemma_count_present_upto_unchanged(s, s2, n - 1);
122        }
123    } else {
124        lemma_count_present_upto_update(s, n - 1, idx, pte);
125    }
126}
127
128/// A zero present-count up to `n` means every slot below `n` is absent.
129pub proof fn lemma_count_present_upto_zero_all_absent<E: PageTableEntryTrait>(s: Seq<E>, n: int)
130    requires
131        count_present_upto(s, n) == 0,
132        0 <= n,
133    ensures
134        forall|k: int| 0 <= k < n ==> !#[trigger] s[k].is_present(),
135    decreases n,
136{
137    if n > 0 {
138        lemma_count_present_upto_bound(s, n - 1);
139        lemma_count_present_upto_zero_all_absent(s, n - 1);
140    }
141}
142
143/// If two sequences agree on `[0, n)`, their counts up to `n` are equal.
144pub proof fn lemma_count_present_upto_unchanged<E: PageTableEntryTrait>(
145    s: Seq<E>,
146    s2: Seq<E>,
147    n: int,
148)
149    requires
150        0 <= n,
151        forall|k: int| 0 <= k < n ==> s[k] == s2[k],
152    ensures
153        count_present_upto(s2, n) == count_present_upto(s, n),
154    decreases n,
155{
156    if n > 0 {
157        lemma_count_present_upto_unchanged(s, s2, n - 1);
158    }
159}
160
161pub tracked struct PageMetaOwner {
162    pub nr_children: pcell_maybe_uninit::PointsTo<u16>,
163    pub stray: pcell_maybe_uninit::PointsTo<bool>,
164}
165
166impl Inv for PageMetaOwner {
167    open spec fn inv(self) -> bool {
168        &&& self.nr_children.is_init()
169        &&& 0 <= self.nr_children.value() <= NR_ENTRIES
170        &&& self.stray.is_init()
171    }
172}
173
174impl<C: PageTableConfig> OwnerOf for PageTablePageMeta<C> {
175    type Owner = PageMetaOwner;
176
177    open spec fn wf(self, owner: Self::Owner) -> bool {
178        &&& self.nr_children.id() == owner.nr_children.id()
179        &&& self.stray.id() == owner.stray.id()
180        &&& 0 <= owner.nr_children.value() <= NR_ENTRIES
181    }
182}
183
184/// # Verification Design
185/// The owner type for a page table node. It contains:
186/// - `meta_own`, a `PageMetaOwner`, which holds the permissions for node-specific
187///   metadata fields, `nr_children` and `stray`
188/// - `children_perm` is an array permission for the underlying frame in which the node
189///   is allocated, interpreted as an array of `NR_ENTRIES` page table entries
190/// - `slot_index` identifies the underlying frame's index in the metadata region
191/// - `metadata` and `metadata_id` are identity snapshots, not permissions.
192///   The owning Frame or incoming PTE holds this node's counted token.
193/// - Each node is a page table with a level between 1 and 4 (on x86); `level` tracks
194///   the level of this node.
195/// - `tree_level` is the level field of the `ghost_tree::TreeNode` that carries this object.
196///   Carried here for convenience, though it can be computed from `level`.
197pub tracked struct NodeOwner<C: PageTableConfig> {
198    pub meta_own: PageMetaOwner,
199    /// Identity snapshots; the incoming PTE or owning Frame holds the token.
200    pub ghost metadata: MetadataPerm,
201    pub ghost metadata_id: Loc,
202    pub children_perm: array_ptr::PointsTo<C::E, NR_ENTRIES>,
203    pub ghost tree_level: int,
204    pub ghost slot_index: int,
205}
206
207impl<C: PageTableConfig> Inv for NodeOwner<C> {
208    open spec fn inv(self) -> bool {
209        &&& self.meta_own.inv()
210        &&& 1 <= self.level() <= C::NR_LEVELS
211        &&& self.children_perm.wf()
212        &&& self.children_perm.is_init_all()
213        &&& self.children_perm.addr() == paddr_to_vaddr(
214            meta_to_frame(index_to_meta(self.slot_index)),
215        )
216        &&& self.tree_level == tree_level_for::<C>(self.level())
217        &&& 0 <= self.slot_index < max_meta_slots()
218        &&& FRAME_METADATA_RANGE.start <= index_to_meta(self.slot_index) < FRAME_METADATA_RANGE.end
219        &&& index_to_meta(self.slot_index) % META_SLOT_SIZE == 0
220        &&& meta_to_frame(index_to_meta(self.slot_index)) < VMALLOC_BASE_VADDR
221            - LINEAR_MAPPING_BASE_VADDR
222        &&& meta_to_frame(index_to_meta(self.slot_index)) < MAX_PADDR
223    }
224}
225
226impl<C: PageTableConfig> NodeOwner<C> {
227    /// Relates an actual counted token to this non-owning node identity.
228    pub open spec fn matches_permission(self, permission: FracMetadataPerm) -> bool {
229        &&& permission.frac() == 1
230        &&& permission.id() == self.metadata_id
231        &&& permission.resource() == self.metadata
232    }
233
234    /// The meta address of this node's slot, computed from `slot_index`.
235    pub open spec fn slot_vaddr(self) -> Vaddr {
236        index_to_meta(self.slot_index)
237    }
238
239    pub open spec fn meta_wf(self, regions: MetaRegionOwners) -> bool {
240        typed_meta_wf::<PageTablePageMeta<C>>(*regions.slots[self.slot_index], self.metadata)
241    }
242
243    pub open spec fn meta_value(self) -> PageTablePageMeta<C> {
244        typed_meta_value::<PageTablePageMeta<C>>(self.metadata)
245    }
246
247    pub open spec fn level(self) -> PagingLevel {
248        self.meta_value().level
249    }
250
251    /// Regions-tied invariants that used to live in `NodeOwner::inv()` via
252    /// the now-removed `meta_perm` field. Establishes the bridge between
253    /// the NodeOwner and the slot perm parked in regions.
254    pub open spec fn metaregion_sound_node(self, regions: MetaRegionOwners) -> bool {
255        let idx = self.slot_index;
256        &&& regions.contains(idx)
257        &&& 0 < regions.ref_count(idx) <= REF_COUNT_MAX
258        &&& self.metadata_id == regions.slot_owners[idx].metadata_perm.id()
259        &&& self.metadata == regions.slot_owners[idx].metadata_perm()
260        &&& self.meta_wf(regions)
261        &&& self.meta_value().wf(self.meta_own)
262        &&& regions.slot_owners[self.slot_index].usage is PageTable
263        &&& self.count_consistent()
264    }
265
266    /// `nr_children` equals the number of present PTEs in `children_perm`.
267    pub open spec fn count_consistent(self) -> bool {
268        self.meta_own.nr_children.value() == count_present(self.children_perm.value())
269    }
270}
271
272impl<C: PageTableConfig> NodeOwner<C> {
273    /// If a slot in `children_perm` holds a non-present PTE, then
274    /// `nr_children < NR_ENTRIES`. Proven (no longer axiomatized) from the
275    /// `count_consistent` invariant: `nr_children` counts present PTEs, and an
276    /// absent slot means not all `NR_ENTRIES` slots are present.
277    pub proof fn lemma_nr_children_absent_slot_bound(self, idx: usize)
278        requires
279            self.inv(),
280            self.count_consistent(),
281            self.children_perm.value().len() == NR_ENTRIES,
282            idx < NR_ENTRIES,
283            !self.children_perm.value()[idx as int].is_present(),
284        ensures
285            self.meta_own.nr_children.value() < NR_ENTRIES,
286    {
287        lemma_count_present_upto_absent(self.children_perm.value(), NR_ENTRIES as int, idx as int);
288    }
289
290    /// If a slot in `children_perm` holds a present PTE, then `nr_children > 0`.
291    /// Dual of [`Self::lemma_nr_children_absent_slot_bound`]; proven from
292    /// `count_consistent`.
293    pub proof fn nr_children_present_slot_bound(self, idx: usize)
294        requires
295            self.inv(),
296            self.count_consistent(),
297            self.children_perm.value().len() == NR_ENTRIES,
298            idx < NR_ENTRIES,
299            self.children_perm.value()[idx as int].is_present(),
300        ensures
301            self.meta_own.nr_children.value() > 0,
302    {
303        lemma_count_present_upto_present(self.children_perm.value(), NR_ENTRIES as int, idx as int);
304    }
305}
306
307impl<'rcu, C: PageTableConfig> NodeOwner<C> {
308    pub open spec fn relate_guard(self, guard: PageTableGuard<'rcu, C>) -> bool {
309        &&& guard.inner@.wf(self)
310        &&& guard.inner.external_meta_wf(self.metadata)
311        &&& guard.inner@.tracked_metadata_perm@ matches Some(permission) ==> {
312            &&& guard.inner.inv()
313            &&& self.matches_permission(permission)
314        }
315    }
316}
317
318impl<C: PageTableConfig> OwnerOf for PageTableNode<C> {
319    type Owner = NodeOwner<C>;
320
321    open spec fn wf(self, owner: Self::Owner) -> bool {
322        &&& self.slot_vaddr() == owner.slot_vaddr()
323        &&& self.ptr_inv()
324    }
325}
326
327impl<C: PageTableConfig> PageTableNode<C> {
328    pub open spec fn invariants(self, owner: NodeOwner<C>) -> bool {
329        &&& owner.inv()
330        &&& self.wf(owner)
331    }
332}
333
334} // verus!