-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathmod.rs
More file actions
3859 lines (3499 loc) · 195 KB
/
Copy pathmod.rs
File metadata and controls
3859 lines (3499 loc) · 195 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MPL-2.0
//! The page table cursor for mapping and querying over the page table.
//!
//! # The page table lock protocol
//!
//! We provide a fine-grained ranged mutual-exclusive lock protocol to allow
//! concurrent accesses to non-overlapping virtual ranges in the page table.
//!
//! [`CursorMut::new`] will lock a range in the virtual space and all the
//! operations on the range with the cursor will be atomic as a transaction.
//!
//! The guarantee of the lock protocol is that, if two cursors' ranges overlap,
//! all of one's operation must be finished before any of the other's
//! operation. The order depends on the scheduling of the threads. If a cursor
//! is ordered after another cursor, it will see all the changes made by the
//! previous cursor.
//!
//! The implementation of the lock protocol resembles two-phase locking (2PL).
//! [`CursorMut::new`] accepts an address range, which indicates the page table
//! entries that may be visited by this cursor. Then, [`CursorMut::new`] finds
//! an intermediate page table (not necessarily the last-level or the top-
//! level) which represents an address range that fully contains the whole
//! specified address range. Then it locks all the nodes in the sub-tree rooted
//! at the intermediate page table node, with a pre-order DFS order. The cursor
//! will only be able to access the page table entries in the locked range.
//! Upon destruction, the cursor will release the locks in the reverse order of
//! acquisition.
mod locking;
use vstd::prelude::*;
use vstd::arithmetic::power2::pow2;
use vstd::math::abs;
use vstd::simple_pptr::*;
use vstd_extra::arithmetic::*;
use vstd_extra::drop_tracking::ManuallyDrop;
use vstd_extra::ghost_tree::*;
use vstd_extra::ownership::*;
use crate::mm::frame::Frame;
use crate::mm::page_table::*;
use crate::mm::{Paddr, Vaddr, MAX_NR_LEVELS, MAX_PADDR};
use crate::specs::arch::kspace::FRAME_METADATA_RANGE;
use crate::specs::mm::frame::mapping::{
frame_to_index, frame_to_index_spec, frame_to_meta, max_meta_slots,
meta_addr, meta_to_frame, META_SLOT_SIZE
};
use crate::specs::mm::frame::meta_owners::{MetaSlotOwner, REF_COUNT_MAX, REF_COUNT_UNUSED};
use crate::specs::mm::frame::meta_region_owners::MetaRegionOwners;
use crate::specs::mm::page_table::cursor::page_size_lemmas::*;
use core::{fmt::Debug, marker::PhantomData, ops::Range};
use align_ext::AlignExt;
use crate::{
mm::{page_prop::PageProperty, page_table::is_valid_range},
specs::task::InAtomicMode,
};
use super::{
pte_index, Child, ChildRef, Entry, EntryOwner, FrameView, PageTable, PageTableConfig,
PageTableError, PageTableGuard, PageTablePageMeta, PagingConstsTrait, PagingLevel,
};
verus! {
/// The state of virtual pages represented by a page table.
///
/// This is the return type of the [`Cursor::query`] method.
pub type PagesState<C> = (Range<Vaddr>, Option<<C as PageTableConfig>::Item>);
/// The cursor for traversal over the page table.
///
/// A slot is a PTE at any levels, which correspond to a certain virtual
/// memory range sized by the "page size" of the current level.
///
/// A cursor is able to move to the next slot, to read page properties,
/// and even to jump to a virtual address directly.
pub struct Cursor<'rcu, C: PageTableConfig, A: InAtomicMode> {
/// The current path of the cursor.
///
/// The level 1 page table lock guard is at index 0, and the level N page
/// table lock guard is at index N - 1.
pub path: [Option<PPtr<PageTableGuard<'rcu, C>>>; NR_LEVELS],
/// The cursor should be used in a RCU read side critical section.
pub rcu_guard: &'rcu A,
/// The level of the page table that the cursor currently points to.
pub level: PagingLevel,
/// The top-most level that the cursor is allowed to access.
///
/// From `level` to `guard_level`, the nodes are held in `path`.
pub guard_level: PagingLevel,
/// The virtual address that the cursor currently points to.
pub va: Vaddr,
/// The virtual address range that is locked.
pub barrier_va: Range<Vaddr>,
pub _phantom: PhantomData<&'rcu PageTable<C>>,
}
/// The cursor of a page table that is capable of map, unmap or protect pages.
///
/// It has all the capabilities of a [`Cursor`], which can navigate over the
/// page table corresponding to the address range. A virtual address range
/// in a page table can only be accessed by one cursor, regardless of the
/// mutability of the cursor.
pub struct CursorMut<'rcu, C: PageTableConfig, A: InAtomicMode> {
pub inner: Cursor<'rcu, C, A>,
}
impl<C: PageTableConfig, A: InAtomicMode> Iterator for Cursor<'_, C, A> {
type Item = PagesState<C>;
#[verifier::external_body]
fn next(&mut self) -> Option<Self::Item> {
unimplemented!()
}
}
pub open spec fn page_size_spec(level: PagingLevel) -> usize {
(PAGE_SIZE * pow2(
(nr_subpage_per_huge::<PagingConsts>().ilog2() * (level - 1)) as nat,
)) as usize
}
/// The page size at a given level.
#[verifier::when_used_as_spec(page_size_spec)]
#[verifier::external_body]
pub fn page_size(level: PagingLevel) -> (ret: usize)
requires
1 <= level <= NR_LEVELS + 1,
ensures
ret == page_size_spec(level),
exists|e| ret == pow2(e),
ret >= PAGE_SIZE,
{
PAGE_SIZE << (nr_subpage_per_huge::<PagingConsts>().ilog2() as usize * (level as usize - 1))
}
/// Borrows a live `PageTableNode` as a `PageTableNodeRef` without requiring
/// `raw_count == 1`.
///
/// ## Justification
/// `Child::from_pte` (called inside `Entry::replace`) invokes `PageTableNode::from_raw`,
/// which sets `regions.slot_owners[idx].raw_count = 0` and marks the entry owner
/// `in_scope = true`. Consequently `metaregion_sound` reports `raw_count == 0`, but
/// `Frame::borrow` / `FrameRef::borrow_paddr` require `raw_count == 1`.
///
/// This function bridges that gap: we have unique ownership of the live frame `pt`
/// (just returned from `Entry::replace`), so borrowing it as a `PageTableNodeRef`
/// is semantically sound. The `raw_count == 1` requirement in `borrow_paddr` is an
/// accounting invariant designed for *forgotten* frames stored in PTEs; it does not
/// apply to live frames held directly.
///
/// ## Fix path
/// The proper fix is:
/// 1. Add `ensures old(owner).is_node() ==> regions.slots.contains_key(...)` to
/// `Entry::replace` (derivable from `Child::from_pte`'s `from_pte_regions_spec`).
/// 2. Replace this call with `pt.into_raw()` + `PageTableNodeRef::borrow_paddr()`.
/// A fragment of a page table that can be taken out of the page table.
pub enum PageTableFrag<C: PageTableConfig> {
/// A mapped page table item.
Mapped { va: Vaddr, item: C::Item },
/// A sub-tree of a page table that is taken out of the page table.
///
/// The caller is responsible for dropping it after TLB coherence.
StrayPageTable {
pt: Frame<PageTablePageMeta<C>>, // TODO: this was a dyn AnyFrameMeta, but we can't support that...
va: Vaddr,
len: usize,
num_frames: usize,
},
}
impl<C: PageTableConfig> PageTableFrag<C> {
#[cfg(ktest)]
pub fn va_range(&self) -> Range<Vaddr> {
match self {
PageTableFrag::Mapped { va, item } => {
let (pa, level, prop) = C::item_into_raw(item.clone());
// SAFETY: All the arguments match those returned from the previous call
// to `item_into_raw`, and we are taking ownership of the cloned item.
drop(unsafe { C::item_from_raw(pa, level, prop) });
*va..*va + page_size(level)
},
PageTableFrag::StrayPageTable { va, len, .. } => *va..*va + *len,
}
}
}
#[verus_verify]
impl<'rcu, C: PageTableConfig, A: InAtomicMode> Cursor<'rcu, C, A> {
#[verus_spec(
with Tracked(slot_perm): Tracked<&PointsTo<MetaSlot>>,
Tracked(rc_perm): Tracked<&mut PermissionU64>)]
pub fn clone_item(item: &C::Item) -> (res: C::Item)
requires
item.clone_requires(*slot_perm, *old(rc_perm)),
old(rc_perm).is_for(slot_perm.value().ref_count),
old(rc_perm).value() < u64::MAX,
ensures
res == *item,
final(rc_perm).value() == old(rc_perm).value() + 1,
final(rc_perm).id() == old(rc_perm).id(),
{
item.clone(Tracked(slot_perm), Tracked(rc_perm))
}
/// Creates a cursor claiming exclusive access over the given range.
///
/// The cursor created will only be able to query or jump within the given
/// range. Out-of-bound accesses will result in panics or errors as return values,
/// depending on the access method.
#[verus_spec(r =>
with Tracked(pt_own): Tracked<PageTableOwner<C>>,
Tracked(guard_perm): Tracked<PointsTo<PageTableGuard<'rcu, C>>>,
Tracked(regions): Tracked<&mut MetaRegionOwners>,
Tracked(guards): Tracked<&mut Guards<'rcu, C>>
requires
pt_own.inv(),
ensures
Self::cursor_new_success_conditions(va) ==> {
&&& r is Ok
&&& r.unwrap().0.invariants(*r.unwrap().1, *final(regions), *final(guards))
&&& r.unwrap().1.metaregion_correct(*final(regions))
&&& r.unwrap().1.in_locked_range()
&&& r.unwrap().0.level < r.unwrap().0.guard_level
&&& r.unwrap().0.va < r.unwrap().0.barrier_va.end
&&& r.unwrap().0.va == va.start
&&& r.unwrap().0.barrier_va == *va
},
!Self::cursor_new_success_conditions(va) ==> r is Err,
forall|idx: usize| #![trigger final(regions).slot_owners[idx].path_if_in_pt]
final(regions).slot_owners[idx].path_if_in_pt == old(regions).slot_owners[idx].path_if_in_pt,
forall|item: C::Item| #![trigger CursorMut::<C, A>::item_not_mapped(item, *old(regions))]
CursorMut::<C, A>::item_not_mapped(item, *old(regions)) ==>
CursorMut::<C, A>::item_not_mapped(item, *final(regions)),
)]
pub fn new(pt: &'rcu PageTable<C>, guard: &'rcu A, va: &Range<Vaddr>)
-> Result<(Self, Tracked<CursorOwner<'rcu, C>>), PageTableError>
{
let valid = is_valid_range::<C>(va);
if !valid || va.start >= va.end {
return Err(PageTableError::InvalidVaddrRange(va.start, va.end));
}
if va.start % C::BASE_PAGE_SIZE() != 0 || va.end % C::BASE_PAGE_SIZE() != 0 {
return Err(PageTableError::UnalignedVaddr);
}
// const { assert!(C::NR_LEVELS() as usize <= MAX_NR_LEVELS) };
proof {
assert(pt_own.0.value.is_node());
assert(pt_own.0.inv_children());
assert forall|i: int| 0 <= i < NR_ENTRIES implies pt_own.0.children[i] is Some by {
if pt_own.0.children[i] is None {
assert(<EntryOwner<C> as TreeNodeValue<INC_LEVELS>>::rel_children(pt_own.0.value, i, None));
}
};
}
Ok(
#[verus_spec(with Tracked(pt_own), Tracked(guard_perm), Tracked(regions), Tracked(guards))]
locking::lock_range(pt, guard, va),
)
}
/// Gets the current virtual address.
pub fn virt_addr(&self) -> Vaddr
returns
self.va,
{
self.va
}
/// Queries the mapping at the current virtual address.
///
/// If the cursor is pointing to a valid virtual address that is locked,
/// it will return the virtual address range and the item at that slot.
///
/// # Verified Properties
/// ## Preconditions
/// - **Safety Invariants**: the global safety invariants ([Self::invariants])
/// must hold before the call.
/// ## Postconditions
/// - **Safety Invariants**: the global safety invariants hold after the call
/// - **Correctness**: if the cursor is within the locked range, the result will be `Ok`;
/// otherwise it will be an error.
/// - **Correctness**: if there is a mapping present ([Self::query_some_condition]),
/// then the second field of the result will `Some(item)`, where `item` is the mapping,
/// and the first field will give its range.
/// - **Correctness**: if there is no mapping present, then the second field of the result will be
/// 'None'.
/// - **Safety**: all frames' relations with the metadata region are preserved.
/// ## Safety
/// - The global invariants ensure that the first node we pass through is already locked,
/// and the loop invariant makes the same guarantee for subsequent nodes.
/// - This function does not change anything in the metadata region except for incrementing
/// the reference counts of nodes when it descends into them.
#[verus_spec(res =>
with Tracked(owner): Tracked<&mut CursorOwner<'rcu, C>>,
Tracked(regions): Tracked<&mut MetaRegionOwners>,
Tracked(guards): Tracked<&mut Guards<'rcu, C>>
requires
old(self).invariants(*old(owner), *old(regions), *old(guards)),
old(owner).in_locked_range(),
ensures
final(self).invariants(*final(owner), *final(regions), *final(guards)),
old(owner).metaregion_correct(*old(regions)) ==> final(owner).metaregion_correct(*final(regions)),
old(owner).in_locked_range() ==> res is Ok,
res matches Ok(state) ==>
final(self).query_some_condition(*final(owner)) ==>
final(self).query_some_ensures(*final(owner), state),
res matches Ok(state) ==>
!final(self).query_some_condition(*final(owner)) ==>
final(self).query_none_ensures(*final(owner), state),
old(owner)@.mappings == final(owner)@.mappings,
forall |e:EntryOwner<C>| #[trigger] e.inv() && e.metaregion_sound(*old(regions)) ==> e.metaregion_sound(*final(regions)),
)]
#[verifier::rlimit(100)]
pub fn query(&mut self) -> Result<PagesState<C>, PageTableError> {
if self.va >= self.barrier_va.end {
proof {
owner.va.reflect_prop(self.va);
}
return Err(PageTableError::InvalidVaddr(self.va));
}
let rcu_guard = self.rcu_guard;
let ghost initial_va = self.va;
loop
invariant
self.invariants(*owner, *regions, *guards),
owner.in_locked_range(),
old(owner).metaregion_correct(*old(regions)) ==> owner.metaregion_correct(*regions),
self.va == initial_va,
old(owner)@.mappings == owner@.mappings,
regions.slot_owners.dom() == old(regions).slot_owners.dom(),
forall|idx: usize| #![trigger regions.slot_owners[idx]]
old(regions).slot_owners.contains_key(idx) ==> {
&&& regions.slot_owners[idx].path_if_in_pt == old(regions).slot_owners[idx].path_if_in_pt
&&& regions.slot_owners[idx].self_addr == old(regions).slot_owners[idx].self_addr
&&& regions.slot_owners[idx].usage == old(regions).slot_owners[idx].usage
&&& regions.slot_owners[idx].raw_count == old(regions).slot_owners[idx].raw_count
&&& regions.slot_owners[idx].inner_perms.ref_count.id()
== old(regions).slot_owners[idx].inner_perms.ref_count.id()
&&& regions.slot_owners[idx].inner_perms.ref_count.value()
>= old(regions).slot_owners[idx].inner_perms.ref_count.value()
&&& regions.slot_owners[idx].inner_perms.ref_count.value() != REF_COUNT_UNUSED
|| old(regions).slot_owners[idx].inner_perms.ref_count.value() == REF_COUNT_UNUSED
&&& regions.slot_owners[idx].inner_perms.storage.id()
== old(regions).slot_owners[idx].inner_perms.storage.id()
&&& regions.slot_owners[idx].inner_perms.vtable_ptr.pptr()
== old(regions).slot_owners[idx].inner_perms.vtable_ptr.pptr()
&&& regions.slot_owners[idx].inner_perms.in_list.id()
== old(regions).slot_owners[idx].inner_perms.in_list.id()
},
forall|k: usize| old(regions).slots.contains_key(k)
==> #[trigger] regions.slots.contains_key(k),
forall|k: usize| old(regions).slots.contains_key(k)
==> old(regions).slots[k] == #[trigger] regions.slots[k],
decreases self.level,
{
let cur_va = self.va;
let level = self.level;
#[verus_spec(with Tracked(owner), Tracked(regions))]
let entry = self.cur_entry();
let ghost owner_snap = *owner;
let tracked mut continuation = owner.continuations.tracked_remove(owner.level - 1);
let ghost cont0 = continuation;
let tracked child_owner = continuation.take_child();
let tracked parent_owner = continuation.entry_own.node.tracked_borrow();
let ghost regions_before_ref = *regions;
#[verus_spec(with Tracked(&child_owner.value), Tracked(&parent_owner), Tracked(regions), Tracked(&continuation.guard_perm) )]
let cur_child = entry.to_ref();
proof {
continuation.put_child(child_owner);
cont0.take_put_child();
owner.continuations.tracked_insert(owner.level - 1, continuation);
owner.metaregion_slot_owners_preserved(regions_before_ref, *regions);
}
let item = match cur_child {
ChildRef::PageTable(pt) => {
let tracked mut continuation = owner.continuations.tracked_remove(owner.level - 1);
let tracked mut child_owner = continuation.take_child();
let tracked mut child_node = child_owner.value.node.tracked_take();
proof_decl! {
let tracked mut guard_perm: Tracked<GuardPerm<'rcu, C>>;
}
let ghost guards0 = *guards;
// SAFETY: The `pt` must be locked and no other guards exist.
#[verus_spec(with Tracked(&child_node), Tracked(guards) => Tracked(guard_perm))]
let guard = pt.make_guard_unchecked(rcu_guard);
proof {
child_owner.value.node = Some(child_node);
continuation.put_child(child_owner);
owner.continuations.tracked_insert(owner.level - 1, continuation);
owner.map_children_implies(
CursorOwner::node_unlocked(guards0),
CursorOwner::node_unlocked_except(*guards, child_node.meta_perm.addr()),
);
owner.cur_entry_node_implies_level_gt_1();
}
#[verus_spec(with Tracked(owner), Tracked(guard_perm), Tracked(regions), Tracked(guards))]
self.push_level(guard);
continue ;
},
ChildRef::None => {
proof { owner.cur_entry_absent_not_present(); }
None
},
ChildRef::Frame(pa, ch_level, prop) => {
proof { owner.cur_entry_frame_present(); }
// debug_assert_eq!(ch_level, level);
// SAFETY:
// This is part of (if `split_huge` happens) a page table item mapped
// with a previous call to `C::item_into_raw`, where:
// - The physical address and the paging level match it;
// - The item part is still mapped so we don't take its ownership.
//
// For page table configs that require the `AVAIL1` flag to be kept
// (currently, only kernel page tables), the callers of the unsafe
// `protect_next` method uphold this invariant.
let item = /*ManuallyDrop::new(unsafe {*/
C::item_from_raw(pa, level, prop) /*})*/
;
proof {
C::item_roundtrip(item, pa, level, prop);
}
assert(pa == owner.cur_entry_owner().frame.unwrap().mapped_pa);
let idx = frame_to_index(pa);
let ghost old_regions = *regions;
let tracked slot_perm = regions.slots.tracked_borrow(idx);
let tracked mut slot_own = regions.slot_owners.tracked_remove(idx);
assert(item.clone_requires(*slot_perm, slot_own.inner_perms.ref_count)) by {
owner.cur_frame_clone_requires(item, pa, level, prop, old_regions);
};
#[verus_spec(with Tracked(slot_perm), Tracked(&mut slot_own.inner_perms.ref_count))]
let cloned = Self::clone_item(&item);
proof {
assert(slot_own.inner_perms.ref_count.id() ==
old_regions.slot_owners[idx].inner_perms.ref_count.id());
// Ref count bounds for clone:
// - 0 < rc: frames in the page table are always in active use,
// never in UNDER_CONSTRUCTION (rc=0). Currently not tracked in
// metaregion_sound — would require strengthening the invariant.
// - rc + 1 < REF_COUNT_MAX: increment doesn't overflow into the
// reserved REF_COUNT_MAX..=REF_COUNT_UNUSED range. Requires either
// a global cardinality argument on shared count or runtime check.
// TODO: track these via either a strengthened metaregion_sound
// invariant or a runtime check at the clone call site.
assume(0 < old_regions.slot_owners[idx].inner_perms.ref_count.value()
&& old_regions.slot_owners[idx].inner_perms.ref_count.value() + 1 < REF_COUNT_MAX);
regions.slot_owners.tracked_insert(idx, slot_own);
owner.clone_item_preserves_invariants(old_regions, *regions, idx);
assert(regions.inv());
assert(owner.metaregion_sound(*regions));
// metaregion_correct: conditionally preserved from clone_item_preserves_invariants
assert(regions.slot_owners.dom() =~= old_regions.slot_owners.dom());
}
Some(cloned)
},
};
let size = page_size(level);
proof {
if owner.cur_entry_owner().is_frame() {
owner.cur_entry_frame_present();
owner.cur_va_range_reflects_view();
}
assert forall |e: EntryOwner<C>|
#[trigger] e.inv() && e.metaregion_sound(*old(regions)) implies e.metaregion_sound(*regions)
by {
if e.is_node() || e.is_frame() {
regions.inv_implies_correct_addr(e.meta_slot_paddr().unwrap());
}
if e.is_frame() && e.parent_level > 1 {
// For any 4KB sub-page j > 0 of e, the sub-page slot at sub_idx is either:
// - equal to the cursor's idx: rc went from rc to rc+1, still != UNUSED.
// - different from idx: slot is entirely unchanged.
// Either way the sub-page validity conditions hold in *regions.
let pa = e.frame.unwrap().mapped_pa;
let nr_pages = page_size(e.parent_level) / PAGE_SIZE;
assert forall |j: usize| #![trigger frame_to_index((pa + j * PAGE_SIZE) as usize)]
0 < j < nr_pages implies {
let sub_idx = frame_to_index((pa + j * PAGE_SIZE) as usize);
&&& regions.slots.contains_key(sub_idx)
&&& regions.slot_owners[sub_idx].inner_perms.ref_count.value() != REF_COUNT_UNUSED
} by {
let sub_idx = frame_to_index((pa + j * PAGE_SIZE) as usize);
assert(old(regions).slots.contains_key(sub_idx));
assert(old(regions).slot_owners[sub_idx].inner_perms.ref_count.value() != REF_COUNT_UNUSED);
assert(regions.slots.contains_key(sub_idx));
assert(regions.slot_owners[sub_idx].inner_perms.ref_count.value() != REF_COUNT_UNUSED);
}
}
};
}
return Ok(
(#[verus_spec(with Tracked(owner))]
self.cur_va_range(), item),
);
}
}
/// Moves the cursor forward to the next mapped virtual address.
///
/// Scans forward from the cursor's current position through up to `len`
/// bytes looking for a mapped (non-absent) leaf entry. If one is found,
/// returns `Some(va)` where `va` is that entry's address and the cursor
/// stops there. Otherwise returns `None` and the cursor advances past
/// the search window.
///
/// This is equivalent to [`find_next_impl`](Self::find_next_impl) with
/// `find_unmap_subtree = false` and `split_huge = false`: the cursor only
/// stops at leaf (frame) entries and never splits huge pages.
///
/// # Panics
///
/// Panics if:
/// - the length is longer than the remaining range of the cursor;
/// - the length is not page-aligned.
///
/// # Verified Properties
/// ## Preconditions
/// - **Safety Invariants**: the global safety invariants ([Self::invariants]) must hold.
/// - **Liveness**: the function will panic if `len` is not page aligned or exceeds
/// the remaining locked range ([Self::find_next_panic_condition]).
/// ## Postconditions
/// - **Safety Invariants**: the global safety invariants hold after the call.
/// - **Correctness**: if a frame is found, the returned address equals the cursor's
/// current position, the owner is within the locked range, and the cursor level
/// is below the guard level.
/// - **Correctness**: the found entry is always a frame (never a node or absent).
/// If the old entry at the same VA was also a frame, its `prop` field is preserved.
/// - **Correctness**: if no entry is found, the cursor advances at least `len` bytes
/// past its starting position.
#[verus_spec(
with Tracked(owner): Tracked<&mut CursorOwner<'rcu, C>>,
Tracked(regions): Tracked<&mut MetaRegionOwners>,
Tracked(guards): Tracked<&mut Guards<'rcu, C>>
)]
pub fn find_next(&mut self, len: usize) -> (res: Option<Vaddr>)
requires
old(self).invariants(*old(owner), *old(regions), *old(guards)),
!old(self).find_next_panic_condition(len),
ensures
final(self).invariants(*final(owner), *final(regions), *final(guards)),
old(owner).metaregion_correct(*old(regions)) ==> final(owner).metaregion_correct(*final(regions)),
res is Some ==> {
&&& res.unwrap() == final(self).va
&&& final(owner).level < final(owner).guard_level
&&& final(owner).in_locked_range()
},
res is Some ==> Self::find_not_unmap_subtree_ensures(*old(owner), *final(owner)),
res is None ==> {
&&& final(self).va >= old(self).va + len
},
{
#[verus_spec(with Tracked(owner), Tracked(regions), Tracked(guards))]
self.find_next_impl(len, false, false)
}
pub open spec fn find_not_unmap_subtree_ensures(old_owner: CursorOwner<C>, new_owner: CursorOwner<C>) -> bool
{
let old_cur_entry = old_owner.cur_entry_owner();
let new_cur_entry = new_owner.cur_entry_owner();
{
&&& new_cur_entry.is_frame()
&&& old_cur_entry.is_frame() ==>
new_cur_entry.frame.unwrap().prop == old_cur_entry.frame.unwrap().prop
}
}
/// Moves the cursor forward to the next fragment in the range.
///
/// See [`Self::find_next`] for more details. Other than the semantics
/// provided by [`Self::find_next`], this method also supports finding non-
/// leaf entries and splitting huge pages if necessary.
///
/// `find_unmap_subtree` specifies whether the cursor should stop at the
/// highest possible level for unmapping. If `false`, the cursor will only
/// stop at leaf entries.
///
/// `split_huge` specifies whether the cursor should split huge pages when
/// it finds a huge page that is mapped over the required range (`len`).
///
/// # Verified Properties
/// ## Preconditions
/// - **Safety Invariants**: the global safety invariants ([Self::invariants]) must hold.
/// - **Liveness**: the function will panic if `len` is not page aligned or exceeds
/// the remaining locked range ([Self::find_next_panic_condition]).
/// ## Postconditions
/// - **Safety Invariants**: the global safety invariants hold after the call.
/// - **Safety**: the cursor's VA never decreases.
/// - **Correctness**: the returned address reflects the cursor's position after the call.
/// - **Correctness**: if the result is `Some`, then the current entry is not absent.
/// - **Correctness**: the `split_huge` flag ensures that the current entry fits the remaining
/// range, and the cursor position is aligned to `page_size(level)`.
/// - **Correctness**: if the `split_huge` flag was used, the mappings in the page table
/// are updated by splitting the next frame to the appropriate size.
/// - **Correctness**: if the `find_unmap_subtree` flag is false, the found entry is a frame
/// - **Correctness**: if the `find_unmap_subtree` flag is false, the found frame has the same
/// `prop` field as the previous frame in that va (even if it is the result of a split).
/// - **Correctness**: mappings in the page table are preserved except for the possible split.
/// - **Correctness**: if no entry is found, the cursor advances at least `len` bytes past its starting position.
/// - **Correctness**: no mappings exist prior to the found entry within the search range. If no
/// entry is found, then no mappings exist in the search range at all.
/// - **Liveness**: The cursor is within the locked range, at a safe level, and properly aligned,
/// ready to map or protect a new frame.
/// ## Safety
/// - This function never accesses nodes outside the locked range, because it is impossible to
/// create a cursor below the range, and if the cursor is above the range this function will always panic.
#[verifier::rlimit(400)]
#[verus_spec(res =>
with Tracked(owner): Tracked<&mut CursorOwner<'rcu, C>>,
Tracked(regions): Tracked<&mut MetaRegionOwners>,
Tracked(guards): Tracked<&mut Guards<'rcu, C>>
requires
old(self).invariants(*old(owner), *old(regions), *old(guards)),
!old(self).find_next_panic_condition(len),
ensures
final(self).invariants(*final(owner), *final(regions), *final(guards)),
final(self).barrier_va == old(self).barrier_va,
final(self).guard_level == old(self).guard_level,
final(self).va >= old(self).va,
old(owner).metaregion_correct(*old(regions)) ==> final(owner).metaregion_correct(*final(regions)),
res is Some ==> {
&&& res.unwrap() == final(self).va
&&& final(owner).level < final(owner).guard_level
&&& final(owner).in_locked_range()
&&& final(self).va < old(self).va + len
},
res is Some ==> !final(owner).cur_entry_owner().is_absent(),
// VA alignment: when split_huge, the found entry's VA is aligned to page_size(level).
// split_huge forces cur_entry_fits_range at the Frame return, meaning cur_va == align_down(cur_va, page_size).
res is Some && split_huge ==> {
&&& final(owner)@.mappings =~= old(owner)@.split_while_huge(page_size_spec(final(self).level)).mappings
&&& final(self).va + page_size_spec(final(self).level) <= old(self).va + len
&&& nat_align_down(final(self).va as nat, page_size_spec(final(self).level) as nat) as usize == final(self).va
},
res is Some && !find_unmap_subtree ==> Self::find_not_unmap_subtree_ensures(*old(owner), *final(owner)),
res is Some && final(owner).cur_entry_owner().is_node() ==>
final(owner)@.mappings =~= old(owner)@.mappings,
old(owner)@.mappings.filter(|m: Mapping|
old(self).va <= m.va_range.start < final(self).va) =~= Set::<Mapping>::empty(),
res is None ==> {
&&& final(self).va >= old(self).va + len
&&& final(owner)@.mappings == old(owner)@.mappings
},
// If the found entry is past old_va, old_va was not covered by any mapping.
res is Some && final(self).va > old(self).va ==> !old(owner)@.present(),
)]
fn find_next_impl(&mut self, len: usize, find_unmap_subtree: bool, split_huge: bool) -> Option<Vaddr>
{
let end = self.va + len;
let ghost barrier_va = self.barrier_va;
assert(barrier_va == old(self).barrier_va);
let rcu_guard = self.rcu_guard;
proof {
owner.va.reflect_prop(self.va);
owner.view_preserves_inv();
}
let ghost old_owner_cur_va: Vaddr = owner@.cur_va;
// Track whether a split occurred during the loop.
// If a split occurred, the next iteration returns Some (never None).
let ghost mut split_happened: bool = false;
while self.va < end
invariant
owner.inv(),
self.inv(),
self.wf(*owner),
regions.inv(),
self.inv(),
old(owner)@.inv(),
owner.in_locked_range() || self.va >= end,
self.va >= old(self).va,
end == old(self).va + len,
end % PAGE_SIZE == 0,
end <= self.barrier_va.end,
self.barrier_va == barrier_va,
barrier_va == old(self).barrier_va,
self.guard_level == old(self).guard_level,
owner.children_not_locked(*guards),
owner.nodes_locked(*guards),
owner.metaregion_sound(*regions),
old(owner).metaregion_correct(*old(regions)) ==> owner.metaregion_correct(*regions),
!owner.popped_too_high,
old_owner_cur_va == old(owner)@.cur_va,
old_owner_cur_va == old(self).va,
// Mapping preservation: if no split happened, mappings are unchanged.
!split_happened ==> owner@.mappings == old(owner)@.mappings,
!split_happened ==> owner@.mappings.filter(|m: Mapping|
old(self).va <= m.va_range.start < self.va) =~= Set::<Mapping>::empty(),
old(owner)@.mappings.filter(|m: Mapping|
old(self).va <= m.va_range.start < self.va) =~= Set::<Mapping>::empty(),
split_happened ==> owner.cur_entry_owner().is_frame(),
split_happened ==> self.va < end,
split_happened && old(owner).cur_entry_owner().is_frame() ==>
owner.cur_entry_owner().frame.unwrap().prop
== old(owner).cur_entry_owner().frame.unwrap().prop,
split_happened ==>
owner@.mappings =~= old(owner)@.split_while_huge(page_size_spec(self.level)).mappings,
!split_happened && old(owner).cur_entry_owner().is_frame() ==>
owner.cur_entry_owner().is_frame() &&
owner.cur_entry_owner().frame.unwrap().prop
== old(owner).cur_entry_owner().frame.unwrap().prop,
(self.va > old(self).va && !split_happened) ==> !old(owner)@.present(),
split_happened ==> self.va == old(self).va,
decreases owner.max_steps(),
{
proof {
owner.in_locked_range_level_lt_nr_levels();
}
let ghost owner0 = *owner;
let cur_va = self.va;
#[verus_spec(with Tracked(owner))]
let cur_va_range = self.cur_va_range();
let cur_entry_fits_range = cur_va == cur_va_range.start && cur_va_range.end <= end;
#[verus_spec(with Tracked(owner), Tracked(regions))]
let mut cur_entry = self.cur_entry();
assert(cur_entry.idx == owner0.index());
let tracked mut continuation = owner.continuations.tracked_remove(owner.level - 1);
let ghost cont0 = continuation;
let tracked child_owner = continuation.take_child();
let tracked node_owner = continuation.entry_own.node.tracked_borrow();
let ghost regions_before_ref = *regions;
#[verus_spec(with Tracked(&child_owner.value), Tracked(&node_owner), Tracked(regions), Tracked(&continuation.guard_perm))]
let cur_child = cur_entry.to_ref();
proof {
continuation.put_child(child_owner);
assert(continuation.children == cont0.children);
owner.continuations.tracked_insert(owner.level - 1, continuation);
assert(owner.continuations == owner0.continuations);
owner.metaregion_slot_owners_preserved(regions_before_ref, *regions);
}
match cur_child {
ChildRef::PageTable(pt) => {
if find_unmap_subtree && cur_entry_fits_range && (C::TOP_LEVEL_CAN_UNMAP
|| self.level != C::NR_LEVELS()) {
proof {
owner.va.reflect_prop(self.va);
if split_huge {
if self.va as usize == old(self).va as usize {
owner.split_while_huge_at_level_noop();
}
owner.in_locked_range_level_lt_nr_levels();
owner.va.align_down_inv(self.level as int);
owner.va.align_down_concrete(self.level as int);
owner.va.align_down(self.level as int).reflect_prop(
nat_align_down(self.va as nat, page_size_spec(self.level) as nat) as Vaddr);
}
// !present postcondition: split_happened ==> self.va == old(self).va,
// so self.va > old(self).va ==> !split_happened ==> !old(owner)@.present().
}
return Some(cur_va);
}
assert(owner.children_not_locked(*guards));
let tracked mut continuation = owner.continuations.tracked_remove(owner.level - 1);
let ghost cont0 = continuation;
let tracked mut child_owner = continuation.take_child();
let tracked mut parent_node_owner = continuation.entry_own.node.tracked_take();
let tracked mut child_node_owner = child_owner.value.node.tracked_take();
proof_decl! {
let tracked mut guard_perm: Tracked<GuardPerm<'rcu, C>>;
}
let ghost guards0 = *guards;
// SAFETY: The `pt` must be locked and no other guards exist.
#[verus_spec(with Tracked(&child_node_owner), Tracked(guards) => Tracked(guard_perm))]
let pt_guard = pt.make_guard_unchecked(rcu_guard);
#[verus_spec(with Tracked(&mut child_node_owner))]
let nr_children = pt_guard.borrow(Tracked(&guard_perm)).nr_children();
proof {
child_owner.value.node = Some(child_node_owner);
continuation.put_child(child_owner);
continuation.entry_own.node = Some(parent_node_owner);
assert(cont0.children == continuation.children);
owner.continuations.tracked_insert(self.level - 1, continuation);
assert(owner.continuations == owner0.continuations);
owner.map_children_implies(
CursorOwner::node_unlocked(guards0),
CursorOwner::node_unlocked_except(*guards, child_node_owner.meta_perm.addr()));
}
assert(owner.only_current_locked(*guards));
if (nr_children != 0) {
proof { owner.cur_entry_node_implies_level_gt_1(); }
#[verus_spec(with Tracked(owner), Tracked(guard_perm), Tracked(regions), Tracked(guards))]
self.push_level(pt_guard);
} else {
let ghost guards_before_drop = *guards;
let ghost locked_addr = child_node_owner.meta_perm.addr();
let _ = ManuallyDrop::new(pt_guard.take(Tracked(&mut guard_perm)), Tracked(guards));
proof {
owner.map_children_implies(
CursorOwner::node_unlocked_except(guards_before_drop, locked_addr),
CursorOwner::node_unlocked(*guards));
owner.move_forward_increases_va();
owner.move_forward_not_popped_too_high();
let ghost subtree = owner.cur_subtree();
PageTableOwner(subtree).view_rec_nr_children_zero_empty(subtree.value.path);
owner.cur_subtree_eq_filtered_mappings();
}
let ghost cur_slot_size = page_size_spec(self.level);
let ghost owner_before_move = *owner;
proof {
owner.va.reflect_prop(self.va);
}
let ghost va_before_move = self.va;
#[verus_spec(with Tracked(owner), Tracked(regions), Tracked(guards))]
self.move_forward();
proof {
owner.va.reflect_prop(self.va);
assert(*owner == owner_before_move.move_forward_owner_spec());
owner_before_move.move_forward_owner_preserves_mappings();
// Empty filter proof (same pattern as ChildRef::None case):
if !split_happened {
assert(owner@.mappings == old(owner)@.mappings);
let ghost aligned_start = nat_align_down(va_before_move as nat, cur_slot_size as nat) as Vaddr;
// From cur_subtree_eq_filtered_mappings: subtree mappings (empty) ==
// mappings.filter(aligned_start <= start < aligned_start + ps)
assert(old(owner)@.mappings.filter(|m: Mapping|
aligned_start <= m.va_range.start < aligned_start + cur_slot_size as usize)
=~= Set::<Mapping>::empty());
// self.va == nat_align_up(va_before_move, ps) <= aligned_start + ps
owner_before_move.va.align_up_concrete(owner_before_move.level as int);
owner_before_move.va.align_up(owner_before_move.level as int).reflect_prop(
nat_align_up(va_before_move as nat, cur_slot_size as nat) as Vaddr);
assert(self.va == nat_align_up(va_before_move as nat, cur_slot_size as nat) as Vaddr);
lemma_nat_align_up_sound(va_before_move as nat, cur_slot_size as nat);
lemma_nat_align_down_sound(va_before_move as nat, cur_slot_size as nat);
assert(self.va <= aligned_start + cur_slot_size as usize);
assert(owner@.mappings.filter(|m: Mapping|
old(self).va <= m.va_range.start < self.va)
=~= Set::<Mapping>::empty()) by {
assert forall |m: Mapping|
!(#[trigger] old(owner)@.mappings.contains(m)
&& old(self).va <= m.va_range.start
&& m.va_range.start < self.va) by {
if old(owner)@.mappings.contains(m)
&& old(self).va <= m.va_range.start
&& m.va_range.start < self.va {
if m.va_range.start < va_before_move {
assert(old(owner)@.mappings.filter(|m2: Mapping|
old(self).va <= m2.va_range.start < va_before_move)
.contains(m));
} else {
assert(old(owner)@.mappings.filter(|m2: Mapping|
aligned_start <= m2.va_range.start < aligned_start + cur_slot_size as usize)
.contains(m));
}
}
};
};
if va_before_move as usize == old(self).va as usize {
owner_before_move.cur_subtree_empty_not_present();
}
}
}
}
continue ;
},
ChildRef::None => {
let ghost cur_slot_size = page_size_spec(self.level);
proof {
owner.move_forward_increases_va();
owner.move_forward_not_popped_too_high();
let ghost subtree = owner.cur_subtree();
PageTableOwner(subtree).view_rec_absent_empty(subtree.value.path);
owner.cur_subtree_eq_filtered_mappings();
}
let ghost owner_before_move = *owner;
proof {
owner.va.reflect_prop(self.va);
}
let ghost va_before_move = self.va;
#[verus_spec(with Tracked(owner), Tracked(regions), Tracked(guards))]
self.move_forward();
proof {
owner.va.reflect_prop(self.va);
assert(*owner == owner_before_move.move_forward_owner_spec());
owner_before_move.move_forward_owner_preserves_mappings();
if !split_happened {
assert(owner@.mappings == old(owner)@.mappings);
let ghost aligned_start = nat_align_down(va_before_move as nat, cur_slot_size as nat) as Vaddr;
assert(old(owner)@.mappings.filter(|m: Mapping|
aligned_start <= m.va_range.start < aligned_start + cur_slot_size as usize)
=~= Set::<Mapping>::empty());
// self.va == nat_align_up(va_before_move, ps) <= aligned_start + ps
owner_before_move.va.align_up_concrete(owner_before_move.level as int);
owner_before_move.va.align_up(owner_before_move.level as int).reflect_prop(
nat_align_up(va_before_move as nat, cur_slot_size as nat) as Vaddr);
assert(self.va == nat_align_up(va_before_move as nat, cur_slot_size as nat) as Vaddr);
lemma_nat_align_up_sound(va_before_move as nat, cur_slot_size as nat);
lemma_nat_align_down_sound(va_before_move as nat, cur_slot_size as nat);
assert(self.va <= aligned_start + cur_slot_size as usize);
assert(owner@.mappings.filter(|m: Mapping|
old(self).va <= m.va_range.start < self.va)
=~= Set::<Mapping>::empty()) by {
assert forall |m: Mapping|
!(#[trigger] old(owner)@.mappings.contains(m)
&& old(self).va <= m.va_range.start
&& m.va_range.start < self.va) by {
if old(owner)@.mappings.contains(m)
&& old(self).va <= m.va_range.start
&& m.va_range.start < self.va {
if m.va_range.start < va_before_move {
assert(old(owner)@.mappings.filter(|m2: Mapping|
old(self).va <= m2.va_range.start < va_before_move)
.contains(m));
} else {
assert(old(owner)@.mappings.filter(|m2: Mapping|
aligned_start <= m2.va_range.start < aligned_start + cur_slot_size as usize)
.contains(m));
}
}
};
};
if va_before_move as usize == old(self).va as usize {
owner_before_move.cur_entry_absent_not_present();
}
}
}
continue ;
},
ChildRef::Frame(_, _, _) => {
assert(owner.max_steps() == owner0.max_steps());
if cur_entry_fits_range || !split_huge {
assert(!find_unmap_subtree && old(owner).cur_entry_owner().is_frame() ==>
owner.cur_entry_owner().frame.unwrap().prop
== old(owner).cur_entry_owner().frame.unwrap().prop) by {
if !find_unmap_subtree && old(owner).cur_entry_owner().is_frame() {
if !split_happened {
assert(owner.continuations == owner0.continuations);
assert(owner.level == owner0.level);
}
}
};
proof {
if split_huge {
if !split_happened && self.va as usize == old(self).va as usize {