Skip to main content

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

1use vstd::{
2    arithmetic::{
3        div_mod::{lemma_div_non_zero, lemma_fundamental_div_mod},
4        mul::{lemma_mul_inequality, lemma_mul_is_commutative},
5        power2::pow2,
6    },
7    prelude::*,
8    seq_lib::*,
9    set::lemma_set_contains_len,
10};
11use vstd_extra::{
12    arithmetic::lemma_nat_align_down_within_block,
13    drop_tracking::*,
14    ghost_tree::*,
15    ownership::*,
16    panic::allowed_to_panic_if,
17    prelude::*,
18    seq_extra::{forall_seq, lemma_forall_seq_index},
19};
20
21use crate::specs::{
22    arch::*,
23    mm::{
24        frame::{
25            mapping::{frame_to_index, index_to_meta},
26            meta_owners::MetaSlotStorage,
27            meta_region_owners::MetaRegionOwners,
28        },
29        page_table::{owners::*, vaddr_range_proofs::*, *},
30    },
31};
32
33use crate::mm::{
34    MAX_USERSPACE_VADDR, Paddr, PagingConstsTrait, PagingLevel, Vaddr,
35    frame::{
36        Frame,
37        meta::{REF_COUNT_MAX, REF_COUNT_UNIQUE, REF_COUNT_UNUSED},
38    },
39    nr_subpage_per_huge,
40    page_prop::PageProperty,
41    page_size,
42    page_table::*,
43};
44use core::{marker::PhantomData, ops::Range};
45
46verus! {
47
48broadcast use group_ghost_tree_lemmas;
49
50pub tracked struct CursorContinuation<'rcu, C: PageTableConfig> {
51    pub entry_own: EntryOwner<C>,
52    pub ghost idx: usize,
53    pub ghost tree_level: nat,
54    pub children: Seq<Option<OwnerSubtree<C>>>,
55    pub ghost guard: PageTableGuard<'rcu, C>,
56}
57
58impl<'rcu, C: PageTableConfig> CursorContinuation<'rcu, C> {
59    pub open spec fn path(self) -> TreePath<NR_ENTRIES> {
60        self.entry_own.path
61    }
62
63    pub open spec fn child(self) -> OwnerSubtree<C> {
64        self.children[self.idx as int]->0
65    }
66
67    pub open spec fn take_child(self) -> (OwnerSubtree<C>, Self) {
68        let child = self.children[self.idx as int]->0;
69        let cont = Self {
70            children: self.children.remove(self.idx as int).insert(self.idx as int, None),
71            ..self
72        };
73        (child, cont)
74    }
75
76    pub proof fn tracked_take_child(tracked &mut self) -> (tracked res: OwnerSubtree<C>)
77        requires
78            old(self).inv(),
79            old(self).idx < old(self).children.len(),
80            old(self).children[old(self).idx as int] is Some,
81        ensures
82            res == old(self).take_child().0,
83            *final(self) == old(self).take_child().1,
84            res.inv(),
85    {
86        let tracked child = self.children.tracked_remove(old(self).idx as int).tracked_unwrap();
87        self.children.tracked_insert(old(self).idx as int, None);
88        child
89    }
90
91    pub open spec fn put_child(self, child: OwnerSubtree<C>) -> Self {
92        Self {
93            children: self.children.remove(self.idx as int).insert(self.idx as int, Some(child)),
94            ..self
95        }
96    }
97
98    pub proof fn tracked_put_child(tracked &mut self, tracked child: OwnerSubtree<C>)
99        requires
100            old(self).idx < old(self).children.len(),
101            old(self).children[old(self).idx as int] is None,
102        ensures
103            *final(self) == old(self).put_child(child),
104    {
105        let _ = self.children.tracked_remove(old(self).idx as int);
106        self.children.tracked_insert(old(self).idx as int, Some(child));
107    }
108
109    pub proof fn take_put_child(self)
110        requires
111            self.idx < self.children.len(),
112            self.children[self.idx as int] is Some,
113        ensures
114            self.take_child().1.put_child(self.take_child().0) == self,
115    {
116        let child = self.take_child().0;
117        let cont = self.take_child().1;
118        assert(cont.put_child(child).children == self.children);
119    }
120
121    /// Taking a child preserves the continuation invariant.
122    pub proof fn take_child_preserves_inv(self)
123        requires
124            self.inv(),
125            self.idx < self.children.len(),
126            self.children[self.idx as int] is Some,
127        ensures
128            self.take_child().1.inv(),
129    {
130    }
131
132    pub open spec fn make_cont(self, idx: usize, guard: PageTableGuard<'rcu, C>) -> (Self, Self) {
133        let child = Self {
134            entry_own: self.children[self.idx as int]->0.value(),
135            tree_level: (self.tree_level + 1) as nat,
136            idx: idx,
137            children: self.children[self.idx as int]->0.children(),
138            guard: guard,
139        };
140        let cont = Self { children: self.children.update(self.idx as int, None), ..self };
141        (child, cont)
142    }
143
144    pub proof fn tracked_make_cont(
145        tracked &mut self,
146        idx: usize,
147        guard: PageTableGuard<'rcu, C>,
148    ) -> (tracked res: Self)
149        requires
150            old(self).all_some(),
151            old(self).children.len() == NR_ENTRIES,
152            old(self).idx < NR_ENTRIES,
153            idx < NR_ENTRIES,
154        ensures
155            res == old(self).make_cont(idx, guard).0,
156            *final(self) == old(self).make_cont(idx, guard).1,
157    {
158        lemma_update_is_remove_insert(self.children, old(self).idx as int, None);
159        let tracked child = self.children.tracked_remove(old(self).idx as int).tracked_unwrap();
160        self.children.tracked_insert(old(self).idx as int, None);
161        let tracked (entry_own, children) = child.tracked_into_parts();
162        Self { entry_own, tree_level: (old(self).tree_level + 1) as nat, idx, children, guard }
163    }
164
165    pub open spec fn restore(self, child: Self) -> (Self, PageTableGuard<'rcu, C>) {
166        let child_node = OwnerSubtree::new(child.entry_own, child.tree_level, child.children);
167        (
168            Self { children: self.children.update(self.idx as int, Some(child_node)), ..self },
169            child.guard,
170        )
171    }
172
173    pub proof fn tracked_restore(tracked &mut self, tracked child: Self) -> (guard: PageTableGuard<
174        'rcu,
175        C,
176    >)
177        requires
178            old(self).idx < old(self).children.len(),
179        ensures
180            *final(self) == old(self).restore(child).0,
181            guard == old(self).restore(child).1,
182    {
183        let tracked child_node = OwnerSubtree::tracked_new(
184            child.entry_own,
185            child.tree_level,
186            child.children,
187        );
188        lemma_update_is_remove_insert(self.children, self.idx as int, Some(child_node));
189        let _ = self.children.tracked_remove(self.idx as int);
190        self.children.tracked_insert(self.idx as int, Some(child_node));
191        child.guard
192    }
193
194    pub open spec fn new(
195        owner_subtree: OwnerSubtree<C>,
196        idx: usize,
197        guard: PageTableGuard<'rcu, C>,
198    ) -> Self {
199        Self {
200            entry_own: owner_subtree.value(),
201            idx: idx,
202            tree_level: owner_subtree.level(),
203            children: owner_subtree.children(),
204            guard: guard,
205        }
206    }
207
208    pub proof fn tracked_new(
209        tracked owner_subtree: OwnerSubtree<C>,
210        idx: usize,
211        guard: PageTableGuard<'rcu, C>,
212    ) -> tracked Self
213        returns
214            Self::new(owner_subtree, idx, guard),
215    {
216        C::lemma_paging_consts_properties();
217        C::lemma_page_table_config_constant_properties();
218        let ghost tree_level = owner_subtree.level();
219        let tracked (entry_own, children) = owner_subtree.tracked_into_parts();
220        Self { entry_own, idx, tree_level, children, guard }
221    }
222
223    /// Every present child subtree satisfies `f` at its corresponding tree path.
224    #[verifier::opaque]
225    pub open spec fn map_children(
226        self,
227        f: spec_fn(EntryOwner<C>, TreePath<NR_ENTRIES>) -> bool,
228    ) -> bool {
229        forall|i: int|
230            #![trigger(self.children[i])]
231            0 <= i < self.children.len() ==> self.children[i] is Some
232                ==> self.children[i]->0.subtree_satisfies(self.path().push_tail(i), f)
233    }
234
235    /// Extracts one child's property without exposing the sibling quantifier.
236    pub proof fn lemma_map_children_unroll(
237        self,
238        f: spec_fn(EntryOwner<C>, TreePath<NR_ENTRIES>) -> bool,
239        i: int,
240    )
241        requires
242            self.map_children(f),
243            0 <= i < self.children.len(),
244            self.children[i] is Some,
245        ensures
246            self.children[i]->0.subtree_satisfies(self.path().push_tail(i), f),
247    {
248        reveal(CursorContinuation::map_children);
249    }
250
251    // map_children_lift, lemma_map_children_lift_skip_idx, as_subtree_restore
252    // have been moved to tree_lemmas.rs.
253    pub open spec fn level(self) -> PagingLevel {
254        self.entry_own.node().level()
255    }
256
257    pub open spec fn inv_children(self) -> bool {
258        self.children.all(|child: Option<OwnerSubtree<C>>| child is Some ==> child->0.inv())
259    }
260
261    pub proof fn lemma_inv_children_unroll(self, i: int)
262        requires
263            self.inv_children(),
264            0 <= i < self.children.len(),
265            self.children[i] is Some,
266        ensures
267            self.children[i]->0.inv(),
268    {
269        let pred = |child: Option<OwnerSubtree<C>>| child is Some ==> child.unwrap().inv();
270        assert(pred(self.children[i]));
271    }
272
273    pub proof fn lemma_inv_children_unroll_all(self)
274        requires
275            self.inv_children(),
276        ensures
277            forall|i: int|
278                #![auto]
279                0 <= i < self.children.len() ==> self.children[i] is Some
280                    ==> self.children[i]->0.inv(),
281    {
282        let pred = |child: Option<OwnerSubtree<C>>| child is Some ==> child.unwrap().inv();
283        assert forall|i: int|
284            0 <= i < self.children.len()
285                && #[trigger] self.children[i] is Some implies self.children[i].unwrap().inv() by {
286            self.lemma_inv_children_unroll(i)
287        }
288    }
289
290    pub open spec fn inv_children_rel_pred(self) -> spec_fn(int, Option<OwnerSubtree<C>>) -> bool {
291        |i: int, child: Option<OwnerSubtree<C>>|
292            {
293                child is Some ==> {
294                    &&& child->0.value().is_node() ==> child->0.value().node_permission is Some
295                    &&& child->0.value().parent_level == self.level()
296                    &&& child->0.level() == self.tree_level + 1
297                    &&& child->0.value().path.len() == self.entry_own.node().tree_level + 1
298                    &&& child->0.value().match_pte(
299                        self.entry_own.node().children_perm.value()[i],
300                        self.entry_own.node().level(),
301                    )
302                    &&& child->0.value().path == self.path().push_tail(i)
303                }
304            }
305    }
306
307    pub open spec fn inv_children_rel(self) -> bool {
308        forall_seq(self.children, self.inv_children_rel_pred())
309    }
310
311    pub open spec fn pt_inv_children_pred() -> spec_fn(int, Option<OwnerSubtree<C>>) -> bool {
312        |i: int, child: Option<OwnerSubtree<C>>| child is Some ==> PageTableOwner(child->0).pt_inv()
313    }
314
315    pub open spec fn pt_inv_children(self) -> bool {
316        forall_seq(self.children, Self::pt_inv_children_pred())
317    }
318
319    pub proof fn lemma_pt_inv_children_unroll(self, i: int)
320        requires
321            self.pt_inv_children(),
322            0 <= i < self.children.len(),
323            self.children[i] is Some,
324        ensures
325            PageTableOwner(self.children[i]->0).pt_inv(),
326    {
327    }
328
329    pub proof fn lemma_inv_children_rel_unroll(self, i: int)
330        requires
331            self.inv_children_rel(),
332            0 <= i < self.children.len(),
333            self.children[i] is Some,
334        ensures
335            self.children[i]->0.value().is_node()
336                ==> self.children[i]->0.value().node_permission is Some,
337            self.children[i]->0.value().parent_level == self.level(),
338            self.children[i]->0.level() == self.tree_level + 1,
339            self.children[i]->0.value().path.len() == self.entry_own.node().tree_level + 1,
340            self.children[i]->0.value().match_pte(
341                self.entry_own.node().children_perm.value()[i],
342                self.entry_own.node().level(),
343            ),
344            self.children[i]->0.value().path == self.path().push_tail(i),
345    {
346    }
347
348    pub open spec fn inv(self) -> bool {
349        &&& self.children.len() == NR_ENTRIES
350        &&& 0 <= self.idx < NR_ENTRIES
351        &&& self.inv_children()
352        &&& self.inv_children_rel()
353        &&& self.pt_inv_children()
354        &&& self.entry_own.is_node()
355        &&& self.entry_own.inv()
356        &&& self.tree_level > 0 ==> self.entry_own.node_permission is Some
357        &&& self.entry_own.node().relate_guard(self.guard)
358        &&& self.tree_level == tree_level_for::<C>(self.level())
359        &&& self.tree_level < C::NR_LEVELS
360        &&& self.path().len() == self.tree_level
361    }
362
363    pub open spec fn all_some(self) -> bool {
364        forall|i: int| 0 <= i < NR_ENTRIES ==> self.children[i] is Some
365    }
366
367    pub open spec fn all_but_index_some(self) -> bool {
368        &&& forall|i: int| 0 <= i < self.idx ==> self.children[i] is Some
369        &&& forall|i: int| self.idx < i < NR_ENTRIES ==> self.children[i] is Some
370        &&& self.children[self.idx as int] is None
371    }
372
373    pub open spec fn inc_index(self) -> Self {
374        Self { idx: (self.idx + 1) as usize, ..self }
375    }
376
377    pub proof fn do_inc_index(tracked &mut self)
378        requires
379            old(self).idx + 1 < NR_ENTRIES,
380        ensures
381            *final(self) == old(self).inc_index(),
382    {
383        self.idx = (self.idx + 1) as usize;
384    }
385
386    pub open spec fn node_locked(self, guards: Guards) -> bool {
387        guards.lock_held(self.guard.inner.slot_vaddr())
388    }
389
390    pub open spec fn view_mappings(self) -> Set<Mapping> {
391        self.children.map(
392            |i, child: Option<OwnerSubtree<C>>|
393                if child is Some {
394                    PageTableOwner(child->0).view_rec(self.path().push_tail(i))
395                } else {
396                    Set::empty()
397                },
398        ).to_set().flatten()
399    }
400
401    pub broadcast proof fn lemma_view_mappings_contains(self)
402        ensures
403            #![trigger self.view_mappings()]
404            forall|m: Mapping| #[trigger]
405                self.view_mappings().contains(m) ==> exists|i: int|
406                    #![trigger self.children[i]]
407                    0 <= i < self.children.len() && self.children[i] is Some && PageTableOwner(
408                        self.children[i]->0,
409                    ).view_rec(self.path().push_tail(i)).contains(m),
410    {
411        broadcast use vstd::seq_lib::group_seq_properties;
412
413    }
414
415    pub broadcast proof fn lemma_view_mappings_intro(self, m: Mapping, i: int)
416        requires
417            0 <= i < self.children.len(),
418            self.children[i] is Some,
419            #[trigger] PageTableOwner(self.children[i]->0).view_rec(
420                self.path().push_tail(i),
421            ).contains(m),
422        ensures
423            self.view_mappings().contains(m),
424    {
425        broadcast use vstd::seq_lib::group_seq_properties;
426
427        let mapped = self.children.map(
428            |i, child: Option<OwnerSubtree<C>>|
429                if child is Some {
430                    PageTableOwner(child->0).view_rec(self.path().push_tail(i))
431                } else {
432                    Set::empty()
433                },
434        );
435        assert(mapped.to_set().contains(mapped[i]));
436    }
437
438    pub open spec fn as_subtree(self) -> OwnerSubtree<C> {
439        OwnerSubtree::new(self.entry_own, self.tree_level, self.children)
440    }
441
442    pub open spec fn as_page_table_owner(self) -> PageTableOwner<C> {
443        PageTableOwner(self.as_subtree())
444    }
445
446    pub open spec fn view_mappings_take_child_spec(self) -> Set<Mapping> {
447        PageTableOwner(self.children[self.idx as int]->0).view_rec(
448            self.path().push_tail(self.idx as int),
449        )
450    }
451
452    /// Proves `rel_children` for a child that was taken from the continuation, modified
453    /// (by protect, alloc_if_none, or split_if_mapped_huge), and placed back at the same index.
454    ///
455    /// The key inputs are:
456    /// - `node_matching` from the operation's postcondition (provides `match_pte`)
457    /// - The child's path and path length (preserved by the operation)
458    /// - The entry's path (unchanged through the reconstruction)
459    /// Proves `rel_children` from `node_matching`. After taking a child from a continuation,
460    /// modifying it (protect/alloc/split), and restoring `entry_own.node = Some(parent_owner)`,
461    /// `rel_children` holds for any `entry_own` that has `node == Some(parent_owner)` and the
462    /// correct `path`.
463    pub proof fn lemma_rel_children_from_node_matching(
464        entry: &Entry<'_, 'rcu, C>,
465        child_value: EntryOwner<C>,
466        parent_owner: NodeOwner<C>,
467        guard: PageTableGuard<'rcu, C>,
468        entry_own: EntryOwner<C>,
469        idx: usize,
470    )
471        requires
472            entry.node_matching(child_value, parent_owner, guard),
473            entry.idx == idx,
474            entry_own.is_node(),
475            entry_own.node() == parent_owner,
476            child_value.path == entry_own.path.push_tail(idx as int),
477            child_value.path.len() == parent_owner.tree_level + 1,
478        ensures
479            child_value.is_node() ==> child_value.node_permission is Some,
480            child_value.path.len() == parent_owner.tree_level + 1,
481            child_value.match_pte(
482                parent_owner.children_perm.value()[idx as int],
483                parent_owner.level(),
484            ),
485            child_value.path == entry_own.path.push_tail(idx as int),
486            child_value.parent_level == parent_owner.level(),
487    {
488    }
489
490    /// After restoring `entry_own.node = Some(parent_owner)` and putting the child back
491    /// at `idx`, the continuation invariant holds.
492    ///
493    /// Caller passes the pre-modification continuation `cont_old` and its
494    /// parent_owner `parent_old` so we can recover the per-`j != idx`
495    /// `inv_children_rel`/`pt_inv_children` facts from `cont_old.inv()`.
496    /// Operations that take/restore (alloc_if_none, split_if_mapped_huge,
497    /// protect, replace) all preserve the parent's other PTEs and the
498    /// children at `j != idx`.
499    pub proof fn lemma_continuation_inv_holds_after_child_restore(
500        self,
501        cont_old: Self,
502        parent_old: NodeOwner<C>,
503    )
504        requires
505    // Old continuation was inv with parent_old wired in
506
507            cont_old.inv(),
508            cont_old.entry_own.is_node(),
509            cont_old.entry_own.node() == parent_old,
510            // Frozen fields shared with cont_old
511            self.children.len() == cont_old.children.len(),
512            self.idx == cont_old.idx,
513            self.tree_level == cont_old.tree_level,
514            self.guard == cont_old.guard,
515            // entry_own changed only by the Node payload and otherwise keeps
516            // the surrounding owner metadata.
517            self.entry_own.is_absent() == cont_old.entry_own.is_absent(),
518            self.entry_own.path == cont_old.entry_own.path,
519            self.entry_own.parent_level == cont_old.entry_own.parent_level,
520            self.entry_own.node_permission == cont_old.entry_own.node_permission,
521            // entry_own's new parent is well-formed and structurally matches the old
522            self.entry_own.is_node(),
523            self.entry_own.inv(),
524            self.entry_own.node().relate_guard(self.guard),
525            self.entry_own.node().level() == parent_old.level(),
526            self.entry_own.node().tree_level == parent_old.tree_level,
527            // Other PTEs preserved (operation only touched the entry at idx)
528            forall|j: int|
529                0 <= j < NR_ENTRIES && j != self.idx
530                    ==> #[trigger] self.entry_own.node().children_perm.value()[j]
531                    == parent_old.children_perm.value()[j],
532            // Children at j != idx untouched
533            forall|j: int|
534                0 <= j < NR_ENTRIES && j != self.idx ==> #[trigger] self.children[j]
535                    == cont_old.children[j],
536            // Standard size/index facts (also implied by cont_old.inv()
537            // + frozen fields, but stated directly to avoid extra unrolls).
538            self.children.len() == NR_ENTRIES,
539            0 <= self.idx < NR_ENTRIES,
540            self.tree_level == tree_level_for::<C>(self.level()),
541            self.tree_level < C::NR_LEVELS,
542            self.path().len() == self.tree_level,
543            // The new child at idx is well-formed
544            self.children[self.idx as int] is Some,
545            self.children[self.idx as int]->0.inv(),
546            self.children[self.idx as int]->0.value().is_node()
547                ==> self.children[self.idx as int]->0.value().node_permission is Some,
548            self.children[self.idx as int]->0.value().parent_level == self.level(),
549            self.children[self.idx as int]->0.value().path == self.path().push_tail(
550                self.idx as int,
551            ),
552            self.children[self.idx as int]->0.level() == self.tree_level + 1,
553            self.children[self.idx as int]->0.value().path.len() == self.entry_own.node().tree_level
554                + 1,
555            self.children[self.idx as int]->0.value().match_pte(
556                self.entry_own.node().children_perm.value()[self.idx as int],
557                self.entry_own.node().level(),
558            ),
559            // The new child satisfies the PT-specific tree invariant. This is
560            // operation-specific (alloc_if_none/protect/split_if_mapped_huge/
561            // replace each establish it differently) so it's lifted to a
562            // precondition rather than discharged here.
563            PageTableOwner(self.children[self.idx as int]->0).pt_inv(),
564        ensures
565            self.inv(),
566    {
567    }
568
569    pub proof fn tracked_new_child(
570        tracked &self,
571        paddr: Paddr,
572        prop: PageProperty,
573        tracked permission: Option<C::Perm>,
574        tracked regions: &mut MetaRegionOwners,
575    ) -> (tracked res: OwnerSubtree<C>)
576        requires
577            self.inv(),
578            self.level() <= C::NR_LEVELS,
579            old(regions).slots.contains_key(frame_to_index(paddr)),
580            valid_frame_paddr(paddr),
581            paddr % page_size::<C>(self.level()) == 0,
582            paddr + page_size::<C>(self.level()) <= MAX_PADDR,
583            C::raw_item_well_formed((paddr, self.level(), prop, Tracked(permission))),
584            C::E::new_page_req(paddr, self.level(), prop),
585            self.path().push_tail(self.idx as int).inv(),
586        ensures
587            final(regions).slot_owners == old(regions).slot_owners,
588            final(regions).slots == old(regions).slots,
589            // Allocating a child doesn't touch the segment obligation ledger.
590            res.value() == EntryOwner::<C>::new_frame(
591                paddr,
592                self.path().push_tail(self.idx as int),
593                self.level(),
594                prop,
595                permission,
596            ),
597            res.inv(),
598            res.level() == self.tree_level + 1,
599            res == OwnerSubtree::new_val(res.value(), res.level() as nat),
600    {
601        C::lemma_paging_consts_properties();
602        C::lemma_page_table_config_constant_properties();
603        let tracked mut owner = EntryOwner::<C>::tracked_new_frame(
604            paddr,
605            self.path().push_tail(self.idx as int),
606            self.level(),
607            prop,
608            permission,
609        );
610        OwnerSubtree::tracked_new_val(owner, self.tree_level + 1)
611    }
612
613    pub broadcast group group_lemmas {
614        CursorContinuation::lemma_view_mappings_contains,
615        CursorContinuation::lemma_view_mappings_intro,
616    }
617}
618
619pub tracked struct CursorOwner<'rcu, C: PageTableConfig> {
620    pub ghost level: PagingLevel,
621    pub continuations: Map<int, CursorContinuation<'rcu, C>>,
622    pub ghost va: Vaddr,
623    pub ghost barrier_va: Range<Vaddr>,
624    pub ghost guard_level: PagingLevel,
625    pub ghost prefix: Vaddr,
626    pub ghost popped_too_high: bool,
627}
628
629impl<'rcu, C: PageTableConfig> Inv for CursorOwner<'rcu, C> {
630    open spec fn inv(self) -> bool {
631        &&& self.va % C::BASE_PAGE_SIZE == 0
632        &&& 1 <= self.level <= C::NR_LEVELS
633        &&& 1 <= self.guard_level
634            <= C::NR_LEVELS
635        // A terminal cursor may equal the managed range's exclusive end.
636        &&& page_table_managed_start_spec::<C>() <= self.va <= page_table_managed_end_spec::<C>()
637        &&& self.locked_range().start <= self.barrier_va.start < self.barrier_va.end
638            <= self.locked_range().end
639        &&& self.barrier_va.start % C::BASE_PAGE_SIZE == 0
640        &&& self.barrier_va.end % C::BASE_PAGE_SIZE == 0
641        &&& is_valid_range_spec::<C>(self.barrier_va)
642        &&& self.barrier_va.end + page_size::<C>(self.guard_level)
643            <= page_table_coverage_end_spec::<
644            C,
645        >()
646        // End states may retain a cursor level above the guard.
647        &&& self.popped_too_high ==> self.level >= self.guard_level
648        &&& !self.popped_too_high ==> self.level <= self.guard_level
649            || self.at_or_past_barrier_end()
650        &&& self.continuations[self.level - 1].all_some()
651        &&& forall|i: int|
652            self.level <= i < C::NR_LEVELS ==> {
653                (#[trigger] self.continuations[i]).all_but_index_some()
654            }
655        &&& self.level <= C::NR_LEVELS - 1 ==> {
656            &&& C::TOP_LEVEL_INDEX_RANGE.start <= self.continuations[C::NR_LEVELS - 1].idx
657                < C::TOP_LEVEL_INDEX_RANGE.end
658        }
659        &&& forall|j: int|
660            #![trigger self.continuations[C::NR_LEVELS - 1].children[j]]
661            0 <= j < NR_ENTRIES && !(C::TOP_LEVEL_INDEX_RANGE.start <= j
662                < C::TOP_LEVEL_INDEX_RANGE.end) ==> {
663                self.continuations[C::NR_LEVELS - 1].children[j] matches Some(child) ==> {
664                    child.value().is_borrowed() || child.value().is_absent()
665                }
666            }
667        &&& self.prefix % C::BASE_PAGE_SIZE == 0
668        &&& self.prefix <= self.va
669        &&& forall|i: int|
670            1 <= i <= self.guard_level ==> #[trigger] pte_index_spec::<C>(
671                self.prefix,
672                i as PagingLevel,
673            ) == 0
674        &&& self.guard_level < C::NR_LEVELS ==> page_table_managed_start_spec::<C>() <= self.prefix
675            < page_table_managed_end_spec::<C>()
676        &&& vaddr_leading_part_spec::<C>(self.va) == vaddr_leading_part_spec::<C>(self.prefix)
677        &&& vaddr_leading_part_spec::<C>(self.prefix) == page_table_coverage_start_spec::<C>()
678        &&& self.level <= self.guard_level ==> forall|i: int|
679            #![trigger self.continuations[i].idx]
680            self.guard_level <= i < C::NR_LEVELS ==> self.continuations[i].idx == pte_index_spec::<
681                C,
682            >(self.prefix, (i + 1) as PagingLevel)
683        &&& !self.popped_too_high && (self.in_locked_range() || self.level < self.guard_level)
684            ==> forall|i: int|
685            self.guard_level <= i < C::NR_LEVELS ==> #[trigger] pte_index_spec::<C>(
686                self.va,
687                (i + 1) as PagingLevel,
688            ) == pte_index_spec::<C>(
689                self.prefix,
690                (i + 1) as PagingLevel,
691            )
692        // Extending MAX_NR_LEVELS requires more clauses here and in Cursor::wf.
693        &&& self.level <= 4 <= C::NR_LEVELS ==> {
694            &&& self.continuations.contains_key(3)
695            &&& self.continuations[3].inv()
696            &&& self.continuations[3].level() == 4
697            &&& self.continuations[3].entry_own.parent_level
698                == 5
699            // After leaving the guard node, its continuations retain their old indices.
700            &&& self.in_locked_range() ==> pte_index_spec::<C>(self.va, 4)
701                == self.continuations[3].idx
702        }
703        &&& self.level <= 3 <= C::NR_LEVELS ==> {
704            &&& self.continuations.contains_key(2)
705            &&& self.continuations[2].inv()
706            &&& self.continuations[2].level() == 3
707            &&& self.continuations[2].entry_own.parent_level == 4
708            &&& self.in_locked_range() ==> pte_index_spec::<C>(self.va, 3)
709                == self.continuations[2].idx
710            &&& 4 <= C::NR_LEVELS ==> self.continuations[2].guard.inner.slot_vaddr()
711                != self.continuations[3].guard.inner.slot_vaddr()
712            &&& 3 < C::NR_LEVELS ==> {
713                // Path consistency: child path = parent path pushed with parent's index
714                &&& self.continuations[2].path() == self.continuations[3].path().push_tail(
715                    self.continuations[3].idx as int,
716                )
717                // PTE consistency
718                &&& self.continuations[2].entry_own.path.len()
719                    == self.continuations[3].entry_own.node().tree_level + 1
720                &&& self.continuations[2].entry_own.match_pte(
721                    self.continuations[3].entry_own.node().children_perm.value()[self.continuations[3].idx as int],
722                    self.continuations[3].entry_own.node().level(),
723                )
724                &&& self.continuations[2].entry_own.parent_level
725                    == self.continuations[3].entry_own.node().level()
726            }
727        }
728        &&& self.level <= 2 <= C::NR_LEVELS ==> {
729            &&& self.continuations.contains_key(1)
730            &&& self.continuations[1].inv()
731            &&& self.continuations[1].level() == 2
732            &&& self.continuations[1].entry_own.parent_level == 3
733            &&& self.in_locked_range() ==> pte_index_spec::<C>(self.va, 2)
734                == self.continuations[1].idx
735            &&& 3 <= C::NR_LEVELS ==> self.continuations[1].guard.inner.slot_vaddr()
736                != self.continuations[2].guard.inner.slot_vaddr()
737            &&& 4 <= C::NR_LEVELS ==> self.continuations[1].guard.inner.slot_vaddr()
738                != self.continuations[3].guard.inner.slot_vaddr()
739            &&& 2 < C::NR_LEVELS ==> {
740                // Path consistency: child path = parent path pushed with parent's index
741                &&& self.continuations[1].path() == self.continuations[2].path().push_tail(
742                    self.continuations[2].idx as int,
743                )
744                // PTE consistency
745                &&& self.continuations[1].entry_own.path.len()
746                    == self.continuations[2].entry_own.node().tree_level + 1
747                &&& self.continuations[1].entry_own.match_pte(
748                    self.continuations[2].entry_own.node().children_perm.value()[self.continuations[2].idx as int],
749                    self.continuations[2].entry_own.node().level(),
750                )
751                &&& self.continuations[1].entry_own.parent_level
752                    == self.continuations[2].entry_own.node().level()
753            }
754        }
755        &&& self.level <= 1 <= C::NR_LEVELS ==> {
756            &&& self.continuations.contains_key(0)
757            &&& self.continuations[0].inv()
758            &&& self.continuations[0].level() == 1
759            &&& self.continuations[0].entry_own.parent_level == 2
760            &&& self.in_locked_range() ==> pte_index_spec::<C>(self.va, 1)
761                == self.continuations[0].idx
762            &&& 2 <= C::NR_LEVELS ==> self.continuations[0].guard.inner.slot_vaddr()
763                != self.continuations[1].guard.inner.slot_vaddr()
764            &&& 3 <= C::NR_LEVELS ==> self.continuations[0].guard.inner.slot_vaddr()
765                != self.continuations[2].guard.inner.slot_vaddr()
766            &&& 4 <= C::NR_LEVELS ==> self.continuations[0].guard.inner.slot_vaddr()
767                != self.continuations[3].guard.inner.slot_vaddr()
768            &&& 1 < C::NR_LEVELS ==> {
769                // Path consistency: child path = parent path pushed with parent's index
770                &&& self.continuations[0].path() == self.continuations[1].path().push_tail(
771                    self.continuations[1].idx as int,
772                )
773                // PTE consistency
774                &&& self.continuations[0].entry_own.path.len()
775                    == self.continuations[1].entry_own.node().tree_level + 1
776                &&& self.continuations[0].entry_own.match_pte(
777                    self.continuations[1].entry_own.node().children_perm.value()[self.continuations[1].idx as int],
778                    self.continuations[1].entry_own.node().level(),
779                )
780                &&& self.continuations[0].entry_own.parent_level
781                    == self.continuations[1].entry_own.node().level()
782            }
783        }
784    }
785}
786
787impl<'rcu, C: PageTableConfig> CursorOwner<'rcu, C> {
788    pub open spec fn node_unlocked(guards: Guards) -> (spec_fn(
789        EntryOwner<C>,
790        TreePath<NR_ENTRIES>,
791    ) -> bool) {
792        |owner: EntryOwner<C>, path: TreePath<NR_ENTRIES>|
793            owner.is_node() ==> guards.unlocked(owner.node().slot_vaddr())
794    }
795
796    pub open spec fn node_unlocked_except(guards: Guards, addr: usize) -> (spec_fn(
797        EntryOwner<C>,
798        TreePath<NR_ENTRIES>,
799    ) -> bool) {
800        |owner: EntryOwner<C>, path: TreePath<NR_ENTRIES>|
801            owner.is_node() ==> owner.node().slot_vaddr() != addr ==> guards.unlocked(
802                owner.node().slot_vaddr(),
803            )
804    }
805
806    pub open spec fn map_full_tree(
807        self,
808        f: spec_fn(EntryOwner<C>, TreePath<NR_ENTRIES>) -> bool,
809    ) -> bool {
810        forall|i: int|
811            #![trigger self.continuations[i]]
812            self.level - 1 <= i < C::NR_LEVELS ==> { self.continuations[i].map_children(f) }
813    }
814
815    pub open spec fn children_not_locked(self, guards: Guards) -> bool {
816        self.map_full_tree(Self::node_unlocked(guards))
817    }
818
819    pub proof fn lemma_children_not_locked_unroll(self, guards: Guards)
820        requires
821            self.children_not_locked(guards),
822        ensures
823            forall|i: int|
824                #![trigger self.continuations[i]]
825                self.level - 1 <= i < C::NR_LEVELS ==> self.continuations[i].map_children(
826                    Self::node_unlocked(guards),
827                ),
828    {
829        C::lemma_paging_consts_properties();
830        C::lemma_page_table_config_constant_properties();
831    }
832
833    pub open spec fn only_current_locked(self, guards: Guards) -> bool {
834        self.map_full_tree(
835            Self::node_unlocked_except(guards, self.cur_entry_owner().node().slot_vaddr()),
836        )
837    }
838
839    pub proof fn lemma_never_drop_restores_children_not_locked(
840        self,
841        guard: PageTableGuard<'rcu, C>,
842        guards0: Guards,
843        guards1: Guards,
844    )
845        requires
846            self.inv(),
847            self.only_current_locked(guards0),
848            guards0.lock_held(guard.inner.slot_vaddr()),
849            guards1.guards == guards0.guards.remove(guard.inner.slot_vaddr()),
850            self.cur_entry_owner().is_node(),
851            guard.inner.slot_vaddr() == self.cur_entry_owner().node().slot_vaddr(),
852        ensures
853            self.children_not_locked(guards1),
854    {
855        let current_addr = self.cur_entry_owner().node().slot_vaddr();
856        let f = Self::node_unlocked_except(guards0, current_addr);
857        let g = Self::node_unlocked(guards1);
858
859        self.lemma_map_children_implies(f, g);
860    }
861
862    pub open spec fn nodes_locked(self, guards: Guards) -> bool {
863        forall|i: int|
864            #![trigger self.continuations[i]]
865            self.level - 1 <= i < self.guard_level ==> { self.continuations[i].node_locked(guards) }
866    }
867
868    pub open spec fn index(self) -> usize {
869        self.continuations[self.level - 1].idx
870    }
871
872    pub open spec fn inc_index(self) -> Self {
873        Self {
874            continuations: self.continuations.insert(
875                self.level - 1,
876                self.continuations[self.level - 1].inc_index(),
877            ),
878            va: vaddr_replace_pte_index_spec::<C>(
879                self.va,
880                self.level,
881                self.continuations[self.level - 1].inc_index().idx as int,
882            ),
883            popped_too_high: false,
884            ..self
885        }
886    }
887
888    /// Advances to the next slot boundary in one ghost update, without exposing an unaligned intermediate VA.
889    #[verifier::spinoff_prover]
890    pub proof fn do_inc_index_and_zero(tracked &mut self)
891        requires
892            old(self).inv(),
893            old(self).level <= old(self).guard_level,
894            old(self).in_barrier_va(),
895            old(self).continuations[old(self).level - 1].idx + 1 < NR_ENTRIES,
896            old(self).level == C::NR_LEVELS ==> (old(self).continuations[old(self).level - 1].idx
897                + 1) <= C::TOP_LEVEL_INDEX_RANGE.end,
898        ensures
899            final(self).inv(),
900            *final(self) == old(self).inc_index().zero_below_level(),
901    {
902        C::lemma_paging_consts_properties();
903        C::lemma_page_table_config_constant_properties();
904        lemma_page_table_managed_index_bounds::<C>(old(self).va);
905        old(self).lemma_cur_pte_index();
906        lemma_inc_slot_indices::<C>(old(self).va, old(self).level);
907        old(self).lemma_inc_index_va();
908        old(self).inc_and_zero_increases_va();
909        lemma_align_down_indices::<C>(old(self).inc_index().va, old(self).level);
910        lemma_page_size_divides::<C>(old(self).level, C::NR_LEVELS);
911        lemma_nat_align_down_within_block(
912            old(self).va as nat,
913            page_size::<C>(old(self).level) as nat,
914            page_size::<C>(C::NR_LEVELS) as nat,
915        );
916        let level = old(self).level;
917        let next = old(self).inc_index().va;
918        assert(next == old(self).va + page_size::<C>(level));
919        assert(old(self).inc_index().zero_below_level().va == nat_align_down(
920            next as nat,
921            page_size::<C>(level) as nat,
922        ) as Vaddr);
923        self.popped_too_high = false;
924        let tracked mut cont = self.continuations.tracked_remove(self.level - 1);
925        cont.do_inc_index();
926        self.va = old(self).inc_index().zero_below_level().va;
927        lemma_page_table_managed_index_bounds::<C>(self.va);
928        self.continuations.tracked_insert(self.level - 1, cont);
929        assert(self.continuations == old(self).continuations.insert(self.level - 1, cont));
930        if self.in_barrier_va() {
931            old(self).lemma_barrier_va_bounds(self.va);
932        }
933        assert forall|i: PagingLevel|
934            level <= i <= C::NR_LEVELS implies #[trigger] pte_index_spec::<C>(self.va, i)
935            == pte_index_spec::<C>(old(self).va, i) + if i == level {
936            1int
937        } else {
938            0int
939        } by {
940            lemma_inc_slot_indices::<C>(old(self).va, level);
941            assert(pte_index_spec::<C>(next, i) == pte_index_spec::<C>(old(self).va, i) + if i
942                == level {
943                1int
944            } else {
945                0int
946            });
947            lemma_align_down_indices::<C>(next, level);
948            assert(self.va == vstd_extra::arithmetic::nat_align_down(
949                next as nat,
950                page_size::<C>(level) as nat,
951            ) as Vaddr);
952            assert(pte_index_spec::<C>(self.va, i) == pte_index_spec::<C>(next, i));
953        };
954        if self.level <= 1 <= C::NR_LEVELS {
955            assert(self.in_locked_range() ==> pte_index_spec::<C>(self.va, 1)
956                == self.continuations[0].idx);
957        }
958        if self.level <= 2 <= C::NR_LEVELS {
959            assert(self.in_locked_range() ==> pte_index_spec::<C>(self.va, 2)
960                == self.continuations[1].idx);
961        }
962        if self.level <= 3 <= C::NR_LEVELS {
963            assert(self.in_locked_range() ==> pte_index_spec::<C>(self.va, 3)
964                == self.continuations[2].idx);
965        }
966        if self.level <= 4 <= C::NR_LEVELS {
967            assert(self.in_locked_range() ==> pte_index_spec::<C>(self.va, 4)
968                == self.continuations[3].idx);
969        }
970    }
971
972    pub proof fn lemma_inv_continuation(self, i: int)
973        requires
974            self.inv(),
975            self.level - 1 <= i <= C::NR_LEVELS - 1,
976        ensures
977            self.continuations.contains_key(i),
978            self.continuations[i].inv(),
979            self.continuations[i].children.len() == NR_ENTRIES,
980    {
981        C::lemma_paging_consts_properties();
982        C::lemma_page_table_config_constant_properties();
983    }
984
985    pub open spec fn view_mappings(self) -> Set<Mapping> {
986        self.continuations.filter_keys(|k| self.level - 1 <= k < C::NR_LEVELS).map_values(
987            |cont: CursorContinuation<'rcu, C>| cont.view_mappings(),
988        ).values().flatten()
989    }
990
991    pub broadcast proof fn lemma_view_mappings_contains(self)
992        requires
993            1 <= self.level <= C::NR_LEVELS,
994        ensures
995            #![trigger self.view_mappings()]
996            forall|m: Mapping| #[trigger]
997                self.view_mappings().contains(m) ==> exists|i: int|
998                    #![trigger self.continuations[i]]
999                    self.level - 1 <= i < C::NR_LEVELS
1000                        && self.continuations[i].view_mappings().contains(m),
1001    {
1002        broadcast use vstd::map_lib::group_map_properties;
1003
1004    }
1005
1006    pub broadcast proof fn lemma_view_mappings_intro(self, m: Mapping, i: int)
1007        requires
1008            1 <= self.level <= C::NR_LEVELS,
1009            self.level - 1 <= i < C::NR_LEVELS,
1010            self.continuations.contains_key(i),
1011            #[trigger] self.continuations[i].view_mappings().contains(m),
1012        ensures
1013            self.view_mappings().contains(m),
1014    {
1015        broadcast use vstd::map_lib::group_map_properties;
1016
1017        let filtered = self.continuations.filter_keys(|k| self.level - 1 <= k < C::NR_LEVELS);
1018        let mapped = filtered.map_values(|cont: CursorContinuation<'rcu, C>| cont.view_mappings());
1019        let values = mapped.values();
1020        assert(values.contains(mapped[i]));
1021    }
1022
1023    pub open spec fn as_page_table_owner(self) -> PageTableOwner<C> {
1024        self.restore_to_level(C::NR_LEVELS).as_page_table_owner()
1025    }
1026
1027    /// Reassembles the cursor chain through an actual page-table level.
1028    pub open spec fn restore_to_level(self, level: PagingLevel) -> CursorContinuation<'rcu, C>
1029        decreases level,
1030    {
1031        if level <= self.level {
1032            self.continuations[self.level - 1]
1033        } else {
1034            self.continuations[level - 1].restore(
1035                self.restore_to_level((level - 1) as PagingLevel),
1036            ).0
1037        }
1038    }
1039
1040    pub open spec fn cur_entry_owner(self) -> EntryOwner<C> {
1041        self.cur_subtree().value()
1042    }
1043
1044    pub open spec fn cur_subtree(self) -> OwnerSubtree<C> {
1045        self.continuations[self.level - 1].children[self.index() as int]->0
1046    }
1047
1048    /// Proves `clone_requires` for the item reconstructed from the current frame entry.
1049    pub proof fn lemma_cur_frame_clone_requires(
1050        self,
1051        item: C::Item,
1052        pa: Paddr,
1053        level: PagingLevel,
1054        prop: PageProperty,
1055        regions: MetaRegionOwners,
1056    )
1057        requires
1058            self.inv(),
1059            regions.inv(),
1060            self.metaregion_sound(regions),
1061            self.cur_entry_owner().is_frame(),
1062            pa == self.cur_entry_owner().frame().mapped_pa,
1063            C::item_from_raw(pa, level, prop, C::item_into_raw(item).3) == item,
1064            C::item_into_raw(item).3@ == self.cur_entry_owner().frame_permission(),
1065            valid_frame_paddr(pa),
1066            C::raw_item_well_formed((pa, level, prop, C::item_into_raw(item).3)),
1067            // The recorded entry trackedness matches the item being cloned.
1068            (C::item_into_raw(item).3@ is Some) == self.cur_entry_owner().frame_is_tracked(),
1069            // Saturation aborts (Arc-style) via `inc_ref_count`'s diverging panic.
1070            allowed_to_panic_if(
1071                (C::item_into_raw(item).3@ is Some) && regions.slot_owner(pa).ref_count()
1072                    >= REF_COUNT_MAX,
1073            ),
1074        ensures
1075            item.clone_requires(regions),
1076    {
1077        C::lemma_paging_consts_properties();
1078        C::lemma_page_table_config_constant_properties();
1079        let cont = self.continuations[self.level - 1];
1080        cont.lemma_map_children_unroll(
1081            PageTableOwner::<C>::metaregion_sound_pred(regions),
1082            cont.idx as int,
1083        );
1084        C::lemma_clone_requires_concrete(item, pa, level, prop, regions);
1085    }
1086
1087    /// Incrementing the ref count of the current frame preserves `regions.inv()` and
1088    /// `self.metaregion_sound(new_regions)`.
1089    pub proof fn lemma_clone_item_preserves_invariants(
1090        self,
1091        old_regions: MetaRegionOwners,
1092        new_regions: MetaRegionOwners,
1093        idx: int,
1094    )
1095        requires
1096            self.inv(),
1097            self.metaregion_sound(old_regions),
1098            old_regions.inv(),
1099            self.cur_entry_owner().is_frame(),
1100            idx == frame_to_index(self.cur_entry_owner().frame().mapped_pa),
1101            old_regions.slot_owners.contains_key(idx),
1102            new_regions.slot_owners.contains_key(idx),
1103            // rc at idx is incremented by 1
1104            new_regions.ref_count(idx) == old_regions.ref_count(idx) + 1,
1105            // All other inner_perms fields at idx are identical (same tracked object)
1106            new_regions.slot_owners[idx].ref_count_perm.id()
1107                == old_regions.slot_owners[idx].ref_count_perm.id(),
1108            new_regions.slot_owners[idx].metadata_perm.id()
1109                == old_regions.slot_owners[idx].metadata_perm.id(),
1110            new_regions.slot_owners[idx].metadata_perm()
1111                == old_regions.slot_owners[idx].metadata_perm(),
1112            new_regions.slot_owners[idx].metadata_perm.frac() + 1
1113                == old_regions.slot_owners[idx].metadata_perm.frac(),
1114            new_regions.slot_owners[idx].in_list_perm == old_regions.slot_owners[idx].in_list_perm,
1115            // Other MetaSlotOwner fields at idx unchanged
1116            new_regions.slot_owners[idx].paths_in_pt == old_regions.slot_owners[idx].paths_in_pt,
1117            new_regions.slot_owners[idx].slot_vaddr == old_regions.slot_owners[idx].slot_vaddr,
1118            new_regions.slot_owners[idx].usage == old_regions.slot_owners[idx].usage,
1119            // All other slot_owners unchanged
1120            new_regions.slot_owners.dom() == old_regions.slot_owners.dom(),
1121            forall|i: int|
1122                #![trigger new_regions.slot_owners[i]]
1123                i != idx && old_regions.slot_owners.contains_key(i) ==> new_regions.slot_owners[i]
1124                    == old_regions.slot_owners[i],
1125            // slots map unchanged
1126            new_regions.slots == old_regions.slots,
1127            new_regions.inv(),
1128            // obligation ledger unchanged (clone bumps a ref count only)
1129            // rc overflow guard: old rc is a normal shared count; the bumped rc fits
1130            // in the valid `[1, REF_COUNT_MAX]` range. The `<=` form (vs strict `<`)
1131            // matches what callers actually have: post-`clone_item`, the new rc is
1132            // bounded by the slot's `inv()` (which permits `rc == REF_COUNT_MAX`).
1133            0 < old_regions.ref_count(idx),
1134            old_regions.ref_count(idx) + 1 <= REF_COUNT_MAX,
1135        ensures
1136            new_regions.inv(),
1137            self.metaregion_sound(new_regions),
1138    {
1139        self.lemma_metaregion_slot_owners_rc_increment(old_regions, new_regions, idx);
1140    }
1141
1142    /// A new frame subtree at the current position has mappings equal to the singleton
1143    /// mapping covering the current slot range.
1144    pub proof fn lemma_new_child_mappings_eq_target(
1145        self,
1146        new_subtree: OwnerSubtree<C>,
1147        pa: Paddr,
1148        level: PagingLevel,
1149        prop: PageProperty,
1150    )
1151        requires
1152            self.inv(),
1153            self.in_barrier_va(),
1154            level == self.level,
1155            new_subtree.inv(),
1156            new_subtree.value().is_frame(),
1157            new_subtree.value().path == self.continuations[self.level - 1].path().push_tail(
1158                self.continuations[self.level - 1].idx as int,
1159            ),
1160            new_subtree.value().frame().mapped_pa == pa,
1161            new_subtree.value().frame().prop == prop,
1162        ensures
1163            PageTableOwner(new_subtree)@.mappings
1164                == set![Mapping {
1165                va_range: self@.cur_slot_range(page_size::<C>(level)),
1166                pa_range: pa..(pa + page_size::<C>(level)) as usize,
1167                page_size: page_size::<C>(level),
1168                property: prop,
1169            }],
1170    {
1171        C::lemma_paging_consts_properties();
1172        C::lemma_page_table_config_constant_properties();
1173        self.cur_va_in_subtree_range();
1174    }
1175
1176    /// VA interval covered by the locked node at `guard_level`, starting at `prefix`.
1177    /// Integer endpoints can represent the end of the address space.
1178    pub open spec fn locked_range(self) -> Range<int> {
1179        let size = page_size::<C>((self.guard_level + 1) as PagingLevel) as int;
1180        Range { start: self.prefix as int, end: self.prefix as int + size }
1181    }
1182
1183    /// Whether the current VA lies in the guard node's VA interval.
1184    pub open spec fn in_locked_range(self) -> bool {
1185        self.locked_range().start <= self.va < self.locked_range().end
1186    }
1187
1188    /// Whether the current VA belongs to the range requested when creating the cursor.
1189    pub open spec fn in_barrier_va(self) -> bool {
1190        self.barrier_va.start <= self.va < self.barrier_va.end
1191    }
1192
1193    /// Whether the current VA has reached or passed the requested range's end.
1194    pub open spec fn at_or_past_barrier_end(self) -> bool {
1195        self.va >= self.barrier_va.end
1196    }
1197
1198    /// Active cursor addresses select a root entry in the configured index range.
1199    pub proof fn lemma_in_barrier_va_top_index_bounds(self)
1200        requires
1201            self.inv(),
1202            self.in_barrier_va(),
1203            !self.popped_too_high,
1204        ensures
1205            C::TOP_LEVEL_INDEX_RANGE.start <= pte_index_spec::<C>(self.va, C::NR_LEVELS)
1206                < C::TOP_LEVEL_INDEX_RANGE.end,
1207    {
1208        self.lemma_barrier_va_bounds(self.va);
1209    }
1210
1211    pub proof fn lemma_in_barrier_va_level_le_guard_level(self)
1212        requires
1213            self.inv(),
1214            self.in_barrier_va(),
1215            !self.popped_too_high,
1216        ensures
1217            self.level <= self.guard_level,
1218    {
1219    }
1220
1221    /// The structural locked range spans the full guard node.
1222    pub proof fn lemma_locked_range_span(self)
1223        requires
1224            self.inv(),
1225        ensures
1226            self.locked_range().start == self.prefix,
1227            self.locked_range().end == self.prefix + page_size::<C>(
1228                (self.guard_level + 1) as PagingLevel,
1229            ),
1230            self.prefix % page_size::<C>((self.guard_level + 1) as PagingLevel) == 0,
1231    {
1232        C::lemma_paging_consts_properties();
1233        C::lemma_page_table_config_constant_properties();
1234        lemma_lower_indices_aligned::<C>(self.prefix, (self.guard_level + 1) as PagingLevel);
1235    }
1236
1237    pub proof fn lemma_prefix_aligned_to_guard_level(self)
1238        requires
1239            self.inv(),
1240        ensures
1241            self.prefix as nat % page_size::<C>(self.guard_level) as nat == 0,
1242    {
1243        C::lemma_paging_consts_properties();
1244        C::lemma_page_table_config_constant_properties();
1245        lemma_lower_indices_aligned::<C>(self.prefix, self.guard_level);
1246    }
1247
1248    pub proof fn lemma_in_node_holds_at_top(self, self_va: Vaddr, va: Vaddr, node_size: usize)
1249        requires
1250            self.inv(),
1251            self_va == self.va,
1252            self.guard_level == C::NR_LEVELS,
1253            node_size == page_size::<C>((C::NR_LEVELS + 1) as PagingLevel),
1254            self.locked_range().start <= va < self.locked_range().end,
1255        ensures
1256            nat_align_down(self_va as nat, node_size as nat) <= va as nat,
1257            (va as nat) - nat_align_down(self_va as nat, node_size as nat) < node_size as nat,
1258    {
1259        C::lemma_paging_consts_properties();
1260        C::lemma_page_table_config_constant_properties();
1261        self.lemma_locked_range_span();
1262        let body_level = (C::NR_LEVELS + 1) as PagingLevel;
1263        lemma_page_size_is_pow2_pte_index_bit_offset::<C>(body_level);
1264        lemma_page_size_next::<C>(self.guard_level);
1265        lemma_usize_shr_is_div(self_va, nr_page_table_coverage_bits_spec::<C>());
1266        lemma_fundamental_div_mod(self_va as int, node_size as int);
1267        lemma_mul_is_commutative(self_va as int / node_size as int, node_size as int);
1268        lemma_nat_align_down_sound(self_va as nat, node_size as nat);
1269        assert(nat_align_down(self_va as nat, node_size as nat) == vaddr_leading_part_spec::<C>(
1270            self_va,
1271        ));
1272
1273        lemma_vaddr_leading_part_is_align_down::<C>(self_va);
1274        lemma_vaddr_leading_part_is_align_down::<C>(self.prefix);
1275        lemma_lower_indices_aligned::<C>(self.prefix, body_level);
1276        lemma_usize_shr_is_div(self.prefix, nr_page_table_coverage_bits_spec::<C>());
1277        lemma_fundamental_div_mod(self.prefix as int, node_size as int);
1278        assert(nat_align_down(self_va as nat, node_size as nat) == self.prefix);
1279    }
1280
1281    /// Guard-level headroom bounds active slot arithmetic without excluding the final top-level slot.
1282    pub proof fn lemma_va_plus_page_size_no_overflow(self, level: PagingLevel)
1283        requires
1284            self.inv(),
1285            self.in_barrier_va(),
1286            1 <= level <= self.guard_level,
1287        ensures
1288            self.va + page_size::<C>(level) <= usize::MAX,
1289            self.va + page_size::<C>(level) < page_table_coverage_end_spec::<C>(),
1290    {
1291        C::lemma_paging_consts_properties();
1292        C::lemma_page_table_config_constant_properties();
1293        lemma_leading_bits_properties::<C>();
1294        lemma_page_size_is_pow2_pte_index_bit_offset::<C>((C::NR_LEVELS + 1) as PagingLevel);
1295        lemma_page_size_monotone::<C>(level, self.guard_level);
1296        vstd::arithmetic::power2::lemma2_to64();
1297        vstd::layout::unsigned_int_max_values();
1298    }
1299
1300    pub proof fn lemma_locked_range_page_aligned(self)
1301        requires
1302            self.inv(),
1303        ensures
1304            self.locked_range().end % (PAGE_SIZE as int) == 0,
1305            self.locked_range().start % (PAGE_SIZE as int) == 0,
1306    {
1307        self.lemma_locked_range_span();
1308        lemma_page_size_base::<C>();
1309        C::lemma_paging_consts_properties();
1310        C::lemma_page_table_config_constant_properties();
1311        lemma_page_size_divides::<C>(1, (self.guard_level + 1) as PagingLevel);
1312        lemma_fundamental_div_mod(
1313            page_size::<C>((self.guard_level + 1) as PagingLevel) as int,
1314            PAGE_SIZE as int,
1315        );
1316        assert(self.locked_range().start % (PAGE_SIZE as int) == 0);
1317        assert(page_size::<C>((self.guard_level + 1) as PagingLevel) % PAGE_SIZE == 0);
1318        vstd::arithmetic::div_mod::lemma_add_mod_noop(
1319            self.prefix as int,
1320            page_size::<C>((self.guard_level + 1) as PagingLevel) as int,
1321            PAGE_SIZE as int,
1322        );
1323    }
1324
1325    pub proof fn lemma_cur_subtree_inv(self)
1326        requires
1327            self.inv(),
1328        ensures
1329            self.cur_subtree().inv(),
1330    {
1331        C::lemma_paging_consts_properties();
1332        C::lemma_page_table_config_constant_properties();
1333        let cont = self.continuations[self.level - 1];
1334        cont.lemma_inv_children_unroll(cont.idx as int)
1335    }
1336
1337    /// Constructs an absent subtree that fits the cursor's current slot.
1338    pub proof fn tracked_new_absent_subtree(self) -> (tracked res: OwnerSubtree<C>)
1339        requires
1340            self.inv(),
1341        ensures
1342            res.inv(),
1343            res.value().is_absent(),
1344            res.level() == self.continuations[self.level - 1].tree_level + 1,
1345            res.value().path.len() <= C::NR_LEVELS,
1346            res.value().parent_level == self.continuations[self.level
1347                - 1].child().value().parent_level,
1348            res.value().path == self.continuations[self.level - 1].path().push_tail(
1349                self.continuations[self.level - 1].idx as int,
1350            ),
1351            res == OwnerSubtree::new_val(res.value(), res.level() as nat),
1352    {
1353        C::lemma_paging_consts_properties();
1354        C::lemma_page_table_config_constant_properties();
1355        let cont = self.continuations[self.level - 1];
1356        self.lemma_inv_continuation(self.level - 1);
1357
1358        cont.lemma_inv_children_unroll(cont.idx as int);
1359        cont.lemma_inv_children_rel_unroll(cont.idx as int);
1360
1361        let tracked entry = EntryOwner::tracked_new_absent(self.cur_entry_owner().path, self.level);
1362
1363        let tracked subtree = OwnerSubtree::tracked_new_val(entry, cont.tree_level + 1);
1364        subtree
1365    }
1366
1367    /// If the current entry is absent, `!self@.present()`.
1368    pub proof fn lemma_cur_entry_absent_not_present(self)
1369        requires
1370            self.inv(),
1371            self.in_barrier_va(),
1372            self.cur_entry_owner().is_absent(),
1373        ensures
1374            !self@.present(),
1375    {
1376        C::lemma_paging_consts_properties();
1377        C::lemma_page_table_config_constant_properties();
1378        let cur_va = self.cur_va();
1379
1380        assert forall|m: Mapping| self.view_mappings().contains(m) implies !(m.va_range.start
1381            <= cur_va < m.va_range.end) by {
1382            if m.va_range.start <= cur_va < m.va_range.end {
1383                self.mapping_covering_cur_va_from_cur_subtree(m);
1384            }
1385        };
1386
1387        let filtered = self@.mappings.filter(
1388            |m: Mapping| m.va_range.start <= self@.cur_va < m.va_range.end,
1389        );
1390        assert(filtered == set![]) by {};
1391    }
1392
1393    /// Generalises `lemma_cur_entry_absent_not_present` to any empty subtree.
1394    pub proof fn lemma_cur_subtree_empty_not_present(self)
1395        requires
1396            self.inv(),
1397            self.in_barrier_va(),
1398            PageTableOwner(self.cur_subtree()).view_rec(self.cur_subtree().value().path) =~= set![],
1399        ensures
1400            !self@.present(),
1401    {
1402        let cur_va = self.cur_va();
1403
1404        assert forall|m: Mapping| self.view_mappings().contains(m) implies !(m.va_range.start
1405            <= cur_va < m.va_range.end) by {
1406            if m.va_range.start <= cur_va < m.va_range.end {
1407                self.mapping_covering_cur_va_from_cur_subtree(m);
1408            }
1409        };
1410
1411        let filtered = self@.mappings.filter(
1412            |m: Mapping| m.va_range.start <= self@.cur_va < m.va_range.end,
1413        );
1414        assert(filtered == set![]) by {};
1415    }
1416
1417    pub proof fn lemma_cur_entry_frame_present(self)
1418        requires
1419            self.inv(),
1420            self.in_barrier_va(),
1421            self.cur_entry_owner().is_frame(),
1422        ensures
1423            self@.present(),
1424            self@.query(
1425                self.cur_entry_owner().frame().mapped_pa,
1426                page_size::<C>(self.cur_entry_owner().parent_level),
1427                self.cur_entry_owner().frame().prop,
1428            ),
1429    {
1430        C::lemma_paging_consts_properties();
1431        C::lemma_page_table_config_constant_properties();
1432        self.view_preserves_inv();
1433        let subtree = self.cur_subtree();
1434        let path = subtree.value().path;
1435        let frame = self.cur_entry_owner().frame();
1436        let pt_level = C::NR_LEVELS + 1 - path.len();
1437        let cont = self.continuations[self.level - 1];
1438
1439        let m = Mapping {
1440            va_range: Range {
1441                start: vaddr_of::<C>(path) as int,
1442                end: vaddr_of::<C>(path) + page_size::<C>(pt_level as PagingLevel),
1443            },
1444            pa_range: Range {
1445                start: frame.mapped_pa,
1446                end: (frame.mapped_pa + page_size::<C>(pt_level as PagingLevel)) as Paddr,
1447            },
1448            page_size: page_size::<C>(pt_level as PagingLevel),
1449            property: frame.prop,
1450        };
1451        cont.lemma_view_mappings_intro(m, cont.idx as int);
1452        self.lemma_view_mappings_intro(m, self.level - 1);
1453        assert(m.va_range.start <= self@.cur_va < m.va_range.end) by {
1454            self.cur_va_in_subtree_range();
1455        };
1456
1457        let filtered = self@.mappings.filter(
1458            |m2: Mapping| m2.va_range.start <= self@.cur_va < m2.va_range.end,
1459        );
1460        lemma_set_contains_len(filtered, m);
1461        // Non-overlap makes the covering mapping unique, so `choose` returns this frame.
1462        let queried = self@.query_mapping();
1463        assert(filtered.contains(queried));
1464        assert(queried == m);
1465    }
1466
1467    /// The entry_own at each continuation level satisfies `metaregion_sound`.
1468    #[verifier::opaque]
1469    pub open spec fn path_metaregion_sound(self, regions: MetaRegionOwners) -> bool {
1470        forall|i: int|
1471            #![trigger self.continuations[i]]
1472            self.level - 1 <= i < C::NR_LEVELS ==> self.continuations[i].entry_own.metaregion_sound(
1473                regions,
1474            )
1475    }
1476
1477    pub open spec fn metaregion_sound(self, regions: MetaRegionOwners) -> bool {
1478        &&& self.map_full_tree(
1479            |entry_owner: EntryOwner<C>, path: TreePath<NR_ENTRIES>|
1480                entry_owner.metaregion_sound(regions),
1481        )
1482        &&& self.path_metaregion_sound(regions)
1483    }
1484
1485    pub proof fn lemma_metaregion_preserved(
1486        self,
1487        other: Self,
1488        regions0: MetaRegionOwners,
1489        regions1: MetaRegionOwners,
1490    )
1491        requires
1492            self.inv(),
1493            self.metaregion_sound(regions0),
1494            self.level == other.level,
1495            self.continuations =~= other.continuations,
1496            OwnerSubtree::implies(
1497                PageTableOwner::<C>::metaregion_sound_pred(regions0),
1498                PageTableOwner::<C>::metaregion_sound_pred(regions1),
1499            ),
1500        ensures
1501            other.metaregion_sound(regions1),
1502    {
1503        C::lemma_paging_consts_properties();
1504        C::lemma_page_table_config_constant_properties();
1505        let f = PageTableOwner::metaregion_sound_pred(regions0);
1506        let g = PageTableOwner::metaregion_sound_pred(regions1);
1507
1508        assert forall|i: int| #![auto] self.level - 1 <= i < C::NR_LEVELS implies {
1509            other.continuations[i].map_children(g)
1510        } by {
1511            reveal(CursorContinuation::map_children);
1512            let cont = self.continuations[i];
1513            assert forall|j: int|
1514                0 <= j < NR_ENTRIES
1515                    && #[trigger] cont.children[j] is Some implies cont.children[j].unwrap().subtree_satisfies(
1516            cont.path().push_tail(j), g) by {
1517                cont.children[j].unwrap().lemma_subtree_satisfies_implies(
1518                    cont.path().push_tail(j),
1519                    f,
1520                    g,
1521                );
1522            };
1523        };
1524        assert(other.path_metaregion_sound(regions1)) by {
1525            reveal(CursorOwner::path_metaregion_sound);
1526            assert forall|i: int|
1527                #![trigger other.continuations[i]]
1528                self.level - 1 <= i
1529                    < C::NR_LEVELS implies other.continuations[i].entry_own.metaregion_sound(
1530                regions1,
1531            ) by {
1532                let eo = self.continuations[i].entry_own;
1533                assert(g(eo, self.continuations[i].path()));
1534            };
1535        };
1536    }
1537
1538    /// Transfers `metaregion_sound` when `slot_owners` is preserved.
1539    pub proof fn lemma_metaregion_slot_owners_preserved(
1540        self,
1541        regions0: MetaRegionOwners,
1542        regions1: MetaRegionOwners,
1543    )
1544        requires
1545            self.inv(),
1546            self.metaregion_sound(regions0),
1547            regions0.slot_owners =~= regions1.slot_owners,
1548            forall|k: int|
1549                regions0.slots.contains_key(k) ==> #[trigger] regions1.slots.contains_key(k),
1550            forall|k: int|
1551                regions0.slots.contains_key(k) ==> regions0.slots[k]
1552                    == #[trigger] regions1.slots[k],
1553        ensures
1554            self.metaregion_sound(regions1),
1555    {
1556        let f = PageTableOwner::<C>::metaregion_sound_pred(regions0);
1557        let g = PageTableOwner::<C>::metaregion_sound_pred(regions1);
1558        assert(OwnerSubtree::implies(f, g)) by {
1559            assert forall|entry: EntryOwner<C>, path: TreePath<NR_ENTRIES>|
1560                entry.inv() && f(entry, path) implies #[trigger] g(entry, path) by {
1561                entry.metaregion_sound_slot_owners_only(regions0, regions1);
1562            };
1563        };
1564        self.lemma_metaregion_preserved(self, regions0, regions1);
1565    }
1566
1567    pub proof fn lemma_metaregion_slot_owners_rc_increment(
1568        self,
1569        regions0: MetaRegionOwners,
1570        regions1: MetaRegionOwners,
1571        idx: int,
1572    )
1573        requires
1574            self.inv(),
1575            self.metaregion_sound(regions0),
1576            regions0.inv(),
1577            regions1.slots == regions0.slots,
1578            regions1.slot_owners.dom() == regions0.slot_owners.dom(),
1579            regions1.ref_count(idx) == regions0.ref_count(idx) + 1,
1580            regions1.slot_owners[idx].ref_count_perm.id()
1581                == regions0.slot_owners[idx].ref_count_perm.id(),
1582            regions1.slot_owners[idx].metadata_perm.id()
1583                == regions0.slot_owners[idx].metadata_perm.id(),
1584            regions1.slot_owners[idx].metadata_perm() == regions0.slot_owners[idx].metadata_perm(),
1585            regions1.slot_owners[idx].metadata_perm.frac() + 1
1586                == regions0.slot_owners[idx].metadata_perm.frac(),
1587            regions1.slot_owners[idx].in_list_perm == regions0.slot_owners[idx].in_list_perm,
1588            regions1.slot_owners[idx].paths_in_pt == regions0.slot_owners[idx].paths_in_pt,
1589            regions1.slot_owners[idx].slot_vaddr == regions0.slot_owners[idx].slot_vaddr,
1590            regions1.slot_owners[idx].usage == regions0.slot_owners[idx].usage,
1591            regions1.ref_count(idx) != REF_COUNT_UNUSED,
1592            // Bumped rc stays in the SHARED range (needed for the node branch).
1593            regions1.ref_count(idx) <= REF_COUNT_MAX,
1594            regions1.inv(),
1595            forall|i: int|
1596                #![trigger regions1.slot_owners[i]]
1597                i != idx && regions0.slot_owners.contains_key(i) ==> regions1.slot_owners[i]
1598                    == regions0.slot_owners[i],
1599        ensures
1600            self.metaregion_sound(regions1),
1601    {
1602        let f = PageTableOwner::<C>::metaregion_sound_pred(regions0);
1603        let g = PageTableOwner::<C>::metaregion_sound_pred(regions1);
1604        assert(OwnerSubtree::implies(f, g)) by {
1605            assert forall|entry: EntryOwner<C>, path: TreePath<NR_ENTRIES>|
1606                entry.inv() && f(entry, path) implies #[trigger] g(entry, path) by {
1607                if entry.is_frame() {
1608                    let pa = entry.frame().mapped_pa;
1609                    C::lemma_perm_well_formed_with_region_preserved(
1610                        pa,
1611                        Tracked(entry.frame_permission()),
1612                        regions0,
1613                        regions1,
1614                    );
1615                }
1616            };
1617        };
1618        self.lemma_metaregion_preserved(self, regions0, regions1);
1619    }
1620
1621    /// The continuation entry at `i` satisfies `metaregion_sound`.
1622    pub proof fn lemma_cont_entry_metaregion_at(self, regions: MetaRegionOwners, i: int)
1623        requires
1624            self.inv(),
1625            self.metaregion_sound(regions),
1626            self.level - 1 <= i < C::NR_LEVELS,
1627        ensures
1628            self.continuations[i].entry_own.metaregion_sound(regions),
1629    {
1630        C::lemma_paging_consts_properties();
1631        C::lemma_page_table_config_constant_properties();
1632        reveal(CursorOwner::path_metaregion_sound);
1633    }
1634
1635    pub open spec fn new(
1636        owner_subtree: OwnerSubtree<C>,
1637        barrier_va: Range<Vaddr>,
1638        guard: PageTableGuard<'rcu, C>,
1639    ) -> Self {
1640        let va = barrier_va.start;
1641        let idx = pte_index_spec::<C>(va, C::NR_LEVELS);
1642        Self {
1643            level: C::NR_LEVELS,
1644            continuations: Map::empty().insert(
1645                C::NR_LEVELS - 1,
1646                CursorContinuation::new(owner_subtree, idx, guard),
1647            ),
1648            va,
1649            barrier_va,
1650            guard_level: C::NR_LEVELS,
1651            prefix: nat_align_down(
1652                va as nat,
1653                page_size::<C>((C::NR_LEVELS + 1) as PagingLevel) as nat,
1654            ) as Vaddr,
1655            popped_too_high: false,
1656        }
1657    }
1658
1659    pub proof fn tracked_new(
1660        tracked owner_subtree: OwnerSubtree<C>,
1661        barrier_va: Range<Vaddr>,
1662        guard: PageTableGuard<'rcu, C>,
1663    ) -> tracked Self
1664        returns
1665            Self::new(owner_subtree, barrier_va, guard),
1666    {
1667        let ghost va = barrier_va.start;
1668        let ghost idx = pte_index_spec::<C>(va, C::NR_LEVELS);
1669        let tracked continuation = CursorContinuation::tracked_new(owner_subtree, idx, guard);
1670        let tracked mut continuations = Map::tracked_empty();
1671        continuations.tracked_insert(C::NR_LEVELS - 1, continuation);
1672        Self {
1673            level: C::NR_LEVELS,
1674            continuations,
1675            va,
1676            barrier_va,
1677            guard_level: C::NR_LEVELS,
1678            prefix: nat_align_down(
1679                va as nat,
1680                page_size::<C>((C::NR_LEVELS + 1) as PagingLevel) as nat,
1681            ) as Vaddr,
1682            popped_too_high: false,
1683        }
1684    }
1685
1686    pub broadcast group group_lemmas {
1687        CursorOwner::lemma_view_mappings_contains,
1688        CursorOwner::lemma_view_mappings_intro,
1689    }
1690}
1691
1692pub ghost struct CursorView<C: PageTableConfig> {
1693    pub cur_va: Vaddr,
1694    pub mappings: Set<Mapping>,
1695    pub phantom: PhantomData<C>,
1696}
1697
1698impl<'rcu, C: PageTableConfig> View for CursorOwner<'rcu, C> {
1699    type V = CursorView<C>;
1700
1701    open spec fn view(&self) -> Self::V {
1702        CursorView { cur_va: self.cur_va(), mappings: self.view_mappings(), phantom: PhantomData }
1703    }
1704}
1705
1706impl<C: PageTableConfig> Inv for CursorView<C> {
1707    open spec fn inv(self) -> bool {
1708        &&& mappings_well_formed(
1709            self.mappings,
1710        )
1711        // Config-aware VA range: user page tables live in `[0, 2^47)`,
1712        // kernel page tables in `[0xffff_8000_…, usize::MAX]`, etc.
1713        // Managed bounds account for the configured upper bits and top-level index range,
1714        // so `Mapping::inv` can stay config-agnostic.
1715        &&& forall|m: Mapping|
1716            #![auto]
1717            self.mappings.contains(m) ==> {
1718                &&& page_table_managed_start_spec::<C>() <= m.va_range.start
1719                &&& m.va_range.end <= page_table_managed_end_spec::<C>()
1720            }
1721        &&& self.non_overlapping()
1722    }
1723}
1724
1725impl<C: PageTableConfig> CursorView<C> {
1726    /// Mappings in the view are non-overlapping. This is a consequence of the
1727    /// page table tree structure: distinct paths map to disjoint VA ranges.
1728    pub open spec fn non_overlapping(self) -> bool {
1729        mappings_disjoint_vaddrs(self.mappings)
1730    }
1731}
1732
1733/// Every mapping in a cursor's view has its VA range within the page
1734/// table's managed range.
1735pub proof fn lemma_view_in_vaddr_range<'rcu, C: PageTableConfig>(owner: &CursorOwner<'rcu, C>)
1736    requires
1737        owner.inv(),
1738    ensures
1739        forall|m: Mapping|
1740            #![auto]
1741            owner.view_mappings().contains(m) ==> {
1742                &&& page_table_managed_start_spec::<C>() <= m.va_range.start
1743                &&& m.va_range.end <= page_table_managed_end_spec::<C>()
1744            },
1745{
1746    C::lemma_paging_consts_properties();
1747    C::lemma_page_table_config_constant_properties();
1748
1749    lemma_page_table_managed_bounds::<C>();
1750    let end = C::TOP_LEVEL_INDEX_RANGE.end as int;
1751
1752    assert forall|m: Mapping| #[trigger] owner.view_mappings().contains(m) implies {
1753        &&& page_table_managed_start_spec::<C>() <= m.va_range.start
1754        &&& m.va_range.end <= page_table_managed_end_spec::<C>()
1755    } by {
1756        let i = choose|i: int|
1757            owner.level - 1 <= i < C::NR_LEVELS && (
1758            #[trigger] owner.continuations[i]).view_mappings().contains(m);
1759        let cont = owner.continuations[i];
1760        let j = choose|j: int|
1761            0 <= j < cont.children.len() && #[trigger] cont.children[j] is Some && PageTableOwner(
1762                cont.children[j].unwrap(),
1763            ).view_rec(cont.path().push_tail(j)).contains(m);
1764        let child = PageTableOwner(cont.children[j].unwrap());
1765        let p = cont.path().push_tail(j);
1766        let pidx = p[0] as int;
1767        child.lemma_view_rec_top_index_va_bound(p, m, end);
1768        lemma_mul_inequality(
1769            C::TOP_LEVEL_INDEX_RANGE.start as int,
1770            pidx,
1771            page_size::<C>(C::NR_LEVELS) as int,
1772        );
1773    }
1774}
1775
1776/// Every mapping in a user cursor lies in `[0, 2^47)`, specializing the
1777/// generic cursor bound with the user configuration's address range.
1778pub proof fn lemma_view_in_vaddr_range_user<'rcu>(
1779    owner: &CursorOwner<'rcu, crate::mm::vm_space::UserPtConfig>,
1780)
1781    requires
1782        owner.inv(),
1783    ensures
1784        forall|m: Mapping|
1785            #![auto]
1786            owner.view_mappings().contains(m) ==> {
1787                &&& 0 <= m.va_range.start
1788                &&& m.va_range.end <= page_table_managed_end_spec::<
1789                    crate::mm::vm_space::UserPtConfig,
1790                >()
1791            },
1792{
1793    lemma_view_in_vaddr_range(owner);
1794    lemma_vaddr_range_spec_user();
1795}
1796
1797impl<'rcu, C: PageTableConfig> InvView for CursorOwner<'rcu, C> {
1798    proof fn view_preserves_inv(self) {
1799        self.view_non_overlapping();
1800        self.lemma_view_mapping_inv();
1801        lemma_view_in_vaddr_range::<C>(&self);
1802    }
1803}
1804
1805impl<'rcu, C: PageTableConfig> CursorOwner<'rcu, C> {
1806    /// The cursor's view has non-overlapping mappings.
1807    pub proof fn view_non_overlapping(self)
1808        requires
1809            self.inv(),
1810        ensures
1811            self@.non_overlapping(),
1812    {
1813        C::lemma_paging_consts_properties();
1814        C::lemma_page_table_config_constant_properties();
1815        self.as_page_table_owner_view_non_overlapping();
1816    }
1817}
1818
1819impl<'rcu, C: PageTableConfig> Inv for Cursor<'rcu, C> {
1820    open spec fn inv(self) -> bool {
1821        // `level <= guard_level + 1` (not `<= guard_level`) admits the
1822        // transient "popped one above the guard" state: `pop_level` at
1823        // `level == guard_level` legitimately yields `level == guard_level
1824        // + 1` (real Rust does not panic there — the guard-node lock slot
1825        // is still `Some`). The next `pop_level` on such a cursor reads a
1826        // `None` path slot (`level > guard_level`, by `wf`) and diverges,
1827        // so the state never propagates further.
1828        &&& 1 <= self.level <= self.guard_level + 1
1829        &&& self.guard_level <= C::NR_LEVELS
1830        &&& self.va >= self.barrier_va.start
1831        &&& self.va % PAGE_SIZE == 0
1832        &&& self.barrier_va.start < self.barrier_va.end
1833        &&& self.barrier_va.start % PAGE_SIZE == 0
1834        &&& self.barrier_va.end % PAGE_SIZE == 0
1835        &&& is_valid_range_spec::<C>(self.barrier_va)
1836        &&& self.barrier_va.end + page_size::<C>(self.guard_level)
1837            <= page_table_coverage_end_spec::<C>()
1838        &&& self.barrier_va.end - self.barrier_va.start <= page_size::<C>(
1839            (self.guard_level + 1) as PagingLevel,
1840        )
1841    }
1842}
1843
1844impl<'rcu, C: PageTableConfig> OwnerOf for Cursor<'rcu, C> {
1845    type Owner = CursorOwner<'rcu, C>;
1846
1847    open spec fn wf(self, owner: Self::Owner) -> bool {
1848        &&& owner.va == self.va
1849        &&& owner.barrier_va == self.barrier_va
1850        &&& self.level == owner.level
1851        &&& owner.guard_level == self.guard_level
1852        &&& owner.locked_range().start <= self.barrier_va.start
1853        &&& self.barrier_va.end
1854            <= owner.locked_range().end
1855        // `path` holds lock guards only for levels in `[self.level,
1856        // self.guard_level]` (see the `Cursor.path` doc comment and
1857        // `locking.rs`: `lock_range` only locks the subtree rooted at
1858        // `guard_level`). The ghost `continuations` chain still extends above
1859        // `guard_level` up to the root, but those ancestor nodes are NOT
1860        // locked, so their `path` slots are `None` and are not tied to a
1861        // continuation guard.
1862        &&& self.level <= 4 <= C::NR_LEVELS ==> {
1863            &&& 4 <= self.guard_level ==> {
1864                &&& self.path[3] is Some
1865                &&& owner.continuations.contains_key(3)
1866                &&& owner.continuations[3].guard == self.path[3]->0
1867            }
1868            &&& 4 > self.guard_level ==> self.path[3] is None
1869        }
1870        &&& self.level <= 3 <= C::NR_LEVELS ==> {
1871            &&& 3 <= self.guard_level ==> {
1872                &&& self.path[2] is Some
1873                &&& owner.continuations.contains_key(2)
1874                &&& owner.continuations[2].guard == self.path[2]->0
1875            }
1876            &&& 3 > self.guard_level ==> self.path[2] is None
1877        }
1878        &&& self.level <= 2 <= C::NR_LEVELS ==> {
1879            &&& 2 <= self.guard_level ==> {
1880                &&& self.path[1] is Some
1881                &&& owner.continuations.contains_key(1)
1882                &&& owner.continuations[1].guard == self.path[1]->0
1883            }
1884            &&& 2 > self.guard_level ==> self.path[1] is None
1885        }
1886        &&& self.level == 1 <= C::NR_LEVELS ==> {
1887            // `1 <= self.guard_level` always holds (`inv` gives
1888            // `guard_level >= 1`), so this clause is equivalent to the
1889            // original level-1 case; the `None` branch is vacuous.
1890            &&& 1 <= self.guard_level ==> {
1891                &&& self.path[0] is Some
1892                &&& owner.continuations.contains_key(0)
1893                &&& owner.continuations[0].guard == self.path[0]->0
1894            }
1895            &&& 1 > self.guard_level ==> self.path[0] is None
1896        }
1897    }
1898}
1899
1900} // verus!