Skip to main content

ostd/mm/page_table/
mod.rs

1// SPDX-License-Identifier: MPL-2.0
2use vstd::{arithmetic::power2::*, prelude::*, std_specs::clone::*};
3use vstd_extra::{assert, panic::allowed_to_panic_if, prelude::*};
4
5use crate::specs::{
6    arch::*,
7    mm::{
8        frame::{mapping::frame_to_index, meta_region_owners::MetaRegionOwners},
9        page_table::{
10            cursor::*,
11            vaddr_range_proofs::{lemma_leading_bits_properties, lemma_page_table_managed_bounds},
12            *,
13        },
14    },
15};
16
17use crate::mm::frame::meta::{
18    MetaSlot, REF_COUNT_MAX, REF_COUNT_UNIQUE, REF_COUNT_UNUSED, mapping::frame_to_meta,
19};
20
21use core::{
22    fmt::Debug,
23    intrinsics::transmute_unchecked,
24    ops::{Range, RangeInclusive},
25    sync::atomic::{AtomicUsize, Ordering},
26};
27
28use super::{
29    Paddr, PagingConstsTrait, PagingLevel, PodOnce, Vaddr, kspace::KernelPtConfig,
30    nr_subpage_per_huge, page_prop::PageProperty, page_size, vm_space::UserPtConfig,
31};
32use crate::{
33    Pod,
34    arch::mm::{NR_ENTRIES, NR_LEVELS, PAGE_SIZE, PageTableEntry, PagingConsts},
35    task::{atomic_mode::AsAtomicModeGuard, disable_preempt},
36};
37
38mod node;
39pub use node::*;
40mod cursor;
41
42pub(crate) use cursor::*;
43
44#[cfg(ktest)]
45mod test;
46
47//pub(crate) mod boot_pt;
48
49verus! {
50
51#[derive(Clone, Copy, PartialEq, Eq, Debug)]
52pub enum PageTableError {
53    /// The provided virtual address range is invalid.
54    InvalidVaddrRange(Vaddr, Vaddr),
55    /// The provided virtual address is invalid.
56    InvalidVaddr(Vaddr),
57    /// Using virtual address not aligned.
58    UnalignedVaddr,
59}
60
61pub trait RCClone: Sized {
62    spec fn clone_requires(self, perm: MetaRegionOwners) -> bool;
63
64    spec fn clone_ensures(
65        self,
66        old_perm: MetaRegionOwners,
67        new_perm: MetaRegionOwners,
68        res: Self,
69    ) -> bool;
70
71    fn clone(&self, Tracked(perm): Tracked<&mut MetaRegionOwners>) -> (res: Self)
72        requires
73            self.clone_requires(*old(perm)),
74        ensures
75            self.clone_ensures(*old(perm), *final(perm), res),
76            final(perm).inv(),
77            final(perm).slots == old(perm).slots,
78            final(perm).slot_owners.dom() == old(perm).slot_owners.dom(),
79    ;
80}
81
82/// The configurations of a page table.
83///
84/// It abstracts away both the usage and the architecture specifics from the
85/// general page table implementation. For examples:
86///  - the managed virtual address range;
87///  - the trackedness of physical mappings;
88///  - the PTE layout;
89///  - the number of page table levels, etc.
90///
91/// # Safety
92///
93/// The implementor must ensure that the `item_into_raw` and `item_from_raw`
94/// are implemented correctly so that:
95///  - `item_into_raw` consumes the ownership of the item;
96///  - if the provided raw form matches the item that was consumed by
97///    `item_into_raw`, `item_from_raw` restores the exact item that was
98///    consumed by `item_into_raw`.
99pub unsafe trait PageTableConfig: Clone + Debug + Send + Sync + 'static {
100    /// The index range at the top level (`C::NR_LEVELS`) page table.
101    ///
102    /// When configured with this value, the [`PageTable`] instance will only
103    /// be allowed to manage the virtual address range that is covered by
104    /// this range. The range can be smaller than the actual allowed range
105    /// specified by the hardware MMU (limited by `C::ADDRESS_WIDTH`).
106    const TOP_LEVEL_INDEX_RANGE: Range<usize>;
107
108    /// If we can remove the top-level page table entries.
109    ///
110    /// This is for the kernel page table, whose second-top-level page
111    /// tables need `'static` lifetime to be shared with user page tables.
112    /// Other page tables do not need to set this to `false`.
113    // Work around verus! dropping `open` on trait associated constants.
114    #[verus::internal(open)]
115    const TOP_LEVEL_CAN_UNMAP: bool = true;
116
117    /// The type of the page table entry.
118    type E: PageTableEntryTrait;
119
120    /// The paging constants.
121    type C: PagingConstsTrait;
122
123    /// The item that can be mapped into the virtual memory space using the
124    /// page table.
125    ///
126    /// Usually, this item is a [`crate::mm::Frame`], which we call a "tracked"
127    /// frame. The page table can also do "untracked" mappings that only maps
128    /// to certain physical addresses without tracking the ownership of the
129    /// mapped physical frame. The user of the page table APIs can choose by
130    /// defining this type and the corresponding methods [`item_into_raw`] and
131    /// [`item_from_raw`].
132    ///
133    /// [`item_from_raw`]: PageTableConfig::item_from_raw
134    /// [`item_into_raw`]: PageTableConfig::item_into_raw
135    type Item: RCClone;
136
137    /// Verification-only type of the permission carried by a tracked item.
138    /// An untracked item carries `None` in its raw representation.
139    type Perm;
140
141    spec fn item_into_raw_spec(item: Self::Item) -> (
142        Paddr,
143        PagingLevel,
144        PageProperty,
145        Tracked<Option<Self::Perm>>,
146    );
147
148    /// Consumes the item and returns the physical address, the paging level,
149    /// and the page property.
150    ///
151    /// The ownership of the item will be consumed, i.e., the item will be
152    /// forgotten after this function is called.
153    #[verifier::when_used_as_spec(item_into_raw_spec)]
154    fn item_into_raw(item: Self::Item) -> ((paddr, level, prop, perm): (
155        Paddr,
156        PagingLevel,
157        PageProperty,
158        Tracked<Option<Self::Perm>>,
159    ))
160        requires
161            Self::item_well_formed(item),
162        ensures
163            Self::raw_item_well_formed((paddr, level, prop, perm)),
164            1 <= level <= Self::C::NR_LEVELS,
165            valid_frame_paddr(paddr),
166            paddr % page_size::<Self::C>(level) == 0,
167            paddr + page_size::<Self::C>(level) <= MAX_PADDR,
168            Self::E::new_page_req(paddr, level, prop),
169        returns
170            Self::item_into_raw(item),
171    ;
172
173    spec fn item_from_raw_spec(
174        paddr: Paddr,
175        level: PagingLevel,
176        prop: PageProperty,
177        perm: Tracked<Option<Self::Perm>>,
178    ) -> Self::Item;
179
180    /// Restores the item from the physical address and the paging level.
181    ///
182    /// There could be transformations after [`PageTableConfig::item_into_raw`]
183    /// and before [`PageTableConfig::item_from_raw`], which include:
184    ///  - splitting and coalescing the items, for example, splitting one item
185    ///    into 512 `level - 1` items with and contiguous physical addresses;
186    ///  - protecting the items, for example, changing the page property.
187    ///
188    /// Splitting and coalescing maintains ownership rules, i.e., if one
189    /// physical address is within the range of one item, after splitting/
190    /// coalescing, there should be exactly one item that contains the address.
191    ///
192    /// # Safety
193    ///
194    /// The caller must ensure that:
195    ///  - the physical address and the paging level represent a page table
196    ///    item or part of it (as described above);
197    ///  - either the ownership of the item is properly transferred to the
198    ///    return value, or the return value is wrapped in a
199    ///    [`core::mem::ManuallyDrop`] that won't outlive the original item.
200    ///
201    /// A concrete trait implementation may require the caller to ensure that
202    ///  - the [`super::PageFlags::AVAIL1`] flag is the same as that returned
203    ///    from [`PageTableConfig::item_into_raw`].
204    #[verifier::when_used_as_spec(item_from_raw_spec)]
205    unsafe fn item_from_raw(
206        paddr: Paddr,
207        level: PagingLevel,
208        prop: PageProperty,
209        perm: Tracked<Option<Self::Perm>>,
210    ) -> (res: Self::Item)
211        requires
212            Self::raw_item_well_formed((paddr, level, prop, perm)),
213        ensures
214            Self::item_well_formed(res),
215        returns
216            Self::item_from_raw(paddr, level, prop, perm),
217    ;
218
219    /// Predicate that captures the well-formedness of the item.
220    spec fn item_well_formed(item: Self::Item) -> bool;
221
222    /// Predicate that captures the well-formedness of raw items.
223    spec fn raw_item_well_formed(
224        item: (Paddr, PagingLevel, PageProperty, Tracked<Option<Self::Perm>>),
225    ) -> bool;
226
227    /// Relates an item's optional permission to the global metadata region.
228    spec fn perm_well_formed_with_region(
229        pa: Paddr,
230        perm: Tracked<Option<Self::Perm>>,
231        regions: MetaRegionOwners,
232    ) -> bool;
233
234    /// An absent permission is the canonical untracked case and has no
235    /// metadata-region ownership obligation.
236    proof fn lemma_none_perm_well_formed(pa: Paddr, regions: MetaRegionOwners)
237        ensures
238            Self::perm_well_formed_with_region(pa, Tracked(None), regions),
239    ;
240
241    proof fn lemma_perm_well_formed_with_region_preserved(
242        pa: Paddr,
243        perm: Tracked<Option<Self::Perm>>,
244        old_regions: MetaRegionOwners,
245        new_regions: MetaRegionOwners,
246    )
247        requires
248            Self::perm_well_formed_with_region(pa, perm, old_regions),
249            old_regions.slots[frame_to_index(pa)] == new_regions.slots[frame_to_index(pa)],
250            old_regions.slot_owners[frame_to_index(pa)].metadata_perm.id()
251                == new_regions.slot_owners[frame_to_index(pa)].metadata_perm.id(),
252        ensures
253            Self::perm_well_formed_with_region(pa, perm, new_regions),
254    ;
255
256    /// Changing properties without changing trackedness preserves a canonical raw item.
257    proof fn lemma_raw_item_well_formed_preserved(
258        pa: Paddr,
259        level: PagingLevel,
260        old_prop: PageProperty,
261        new_prop: PageProperty,
262        perm: Tracked<Option<Self::Perm>>,
263    )
264        requires
265            valid_frame_paddr(pa),
266            Self::raw_item_well_formed((pa, level, old_prop, perm)),
267            (Self::item_into_raw(Self::item_from_raw(pa, level, new_prop, perm)).3@ is Some) == (
268            perm@ is Some),
269        ensures
270            Self::raw_item_well_formed((pa, level, new_prop, perm)),
271    ;
272
273    /// Splitting a canonical huge-page raw item yields canonical child raw items.
274    proof fn lemma_raw_item_well_formed_split(
275        pa: Paddr,
276        level: PagingLevel,
277        prop: PageProperty,
278        child_pa: Paddr,
279        child_idx: usize,
280        perm: Tracked<Option<Self::Perm>>,
281    )
282        requires
283            valid_frame_paddr(pa),
284            Self::raw_item_well_formed((pa, level, prop, perm)),
285            Self::E::new_page_req(pa, level, prop),
286            level > 1,
287            child_idx < NR_ENTRIES,
288            child_pa == pa + child_idx * page_size::<Self::C>((level - 1) as PagingLevel),
289        ensures
290            Self::raw_item_well_formed((child_pa, (level - 1) as PagingLevel, prop, perm)),
291            Self::E::new_page_req(child_pa, (level - 1) as PagingLevel, prop),
292    ;
293
294    /// Huge mappings are untracked. Both current configurations encode
295    /// tracked mappings only at the base-page level.
296    proof fn lemma_huge_raw_item_untracked(
297        pa: Paddr,
298        level: PagingLevel,
299        prop: PageProperty,
300        perm: Tracked<Option<Self::Perm>>,
301    )
302        requires
303            Self::raw_item_well_formed((pa, level, prop, perm)),
304            level > 1,
305        ensures
306            perm@ is None,
307    ;
308
309    /// The item produced by [`PageTableConfig::item_from_raw`] is well-formed.
310    proof fn lemma_item_from_raw_well_formed(
311        pa: Paddr,
312        level: PagingLevel,
313        prop: PageProperty,
314        perm: Tracked<Option<Self::Perm>>,
315    )
316        requires
317            valid_frame_paddr(pa),
318            Self::raw_item_well_formed((pa, level, prop, perm)),
319        ensures
320            Self::item_well_formed(Self::item_from_raw(pa, level, prop, perm)),
321    ;
322
323    /// Re-encoding a canonical raw item preserves the complete raw representation.
324    proof fn lemma_item_into_raw_roundtrip(
325        pa: Paddr,
326        level: PagingLevel,
327        prop: PageProperty,
328        perm: Tracked<Option<Self::Perm>>,
329    )
330        requires
331            valid_frame_paddr(pa),
332            Self::raw_item_well_formed((pa, level, prop, perm)),
333        ensures
334            Self::item_into_raw(Self::item_from_raw(pa, level, prop, perm)) == (
335                pa,
336                level,
337                prop,
338                perm,
339            ),
340    ;
341
342    /// Decoding the raw representation produced from a well-formed item restores that item.
343    proof fn lemma_item_from_raw_roundtrip(
344        item: Self::Item,
345        pa: Paddr,
346        level: PagingLevel,
347        prop: PageProperty,
348        perm: Tracked<Option<Self::Perm>>,
349    )
350        requires
351            valid_frame_paddr(pa),
352            Self::item_well_formed(item),
353            Self::item_into_raw(item) == (pa, level, prop, perm),
354        ensures
355            Self::item_from_raw(pa, level, prop, perm) == item,
356    ;
357
358    /// Proves that `clone_ensures` for `Self::Item` implies concrete per-field
359    /// properties on `MetaRegionOwners`.
360    proof fn lemma_clone_ensures_concrete(
361        item: Self::Item,
362        pa: Paddr,
363        old_regions: MetaRegionOwners,
364        new_regions: MetaRegionOwners,
365        res: Self::Item,
366    )
367        requires
368            item.clone_ensures(old_regions, new_regions, res),
369            Self::item_into_raw(item).0 == pa,
370            new_regions.inv(),
371            new_regions.slots =~= old_regions.slots,
372            new_regions.slot_owners.dom() =~= old_regions.slot_owners.dom(),
373        ensures
374            Self::item_into_raw(res).0 == Self::item_into_raw(item).0,
375            Self::item_into_raw(res).1 == Self::item_into_raw(item).1,
376            Self::item_into_raw(res).2 == Self::item_into_raw(item).2,
377            (Self::item_into_raw(res).3@ is Some) == (Self::item_into_raw(item).3@ is Some),
378            Self::item_into_raw(item).3@ is Some ==> {
379                old_regions.inc_frame_reference_region_spec(pa, new_regions)
380            },
381            Self::item_into_raw(item).3@ is None ==> new_regions == old_regions,
382    ;
383
384    proof fn lemma_clone_requires_concrete(
385        item: Self::Item,
386        pa: Paddr,
387        level: PagingLevel,
388        prop: PageProperty,
389        regions: MetaRegionOwners,
390    )
391        requires
392            regions.inv(),
393            Self::item_from_raw(pa, level, prop, Self::item_into_raw(item).3) == item,
394            Self::raw_item_well_formed((pa, level, prop, Self::item_into_raw(item).3)),
395            Self::perm_well_formed_with_region(pa, Self::item_into_raw(item).3, regions),
396            valid_frame_paddr(pa),
397            regions.contains(frame_to_index(pa)),
398            Self::item_into_raw(item).3@ is Some ==> {
399                &&& 0 < regions.slot_owner(pa).ref_count()
400                &&& regions.slot_owner(pa).ref_count() != REF_COUNT_UNUSED
401                &&& allowed_to_panic_if(regions.slot_owner(pa).ref_count() >= REF_COUNT_MAX)
402            },
403        ensures
404            item.clone_requires(regions),
405    ;
406
407    /// The requirements of the page table configuration constants so that the memory management system can work correctly.
408    ///
409    /// NOTE: The postcondition is designed to be minimal, to actually be used in proofs, call `lemma_page_table_config_constant_properties`
410    /// instead to get all the properties that are derived from the requirements.
411    proof fn lemma_page_table_config_constant_requirements()
412        ensures
413            core::mem::size_of::<Self::E>() == Self::C::PTE_SIZE,
414            Self::TOP_LEVEL_INDEX_RANGE.start < Self::TOP_LEVEL_INDEX_RANGE.end
415                <= nr_subpage_per_huge::<Self::C>(),
416    ;
417
418    // The derived properties of the page table config constants.
419    ///
420    /// NOTE: Implementations of `PageTableConfig` do not need to implement this lemma, the proof is automatically inherited from the default implementation.
421    proof fn lemma_page_table_config_constant_properties()
422        ensures
423    // Derived properties.
424
425            Self::TOP_LEVEL_INDEX_RANGE.end <= pow2(top_level_index_width_spec::<Self::C>() as nat),
426            Self::TOP_LEVEL_INDEX_RANGE.end * pow2(
427                pte_index_bit_offset_spec::<Self::C>(Self::C::NR_LEVELS) as nat,
428            ) <= usize::MAX,
429            // Copied from the postcondition of `lemma_page_table_config_constant_requirements`
430            // so that we only need to call this lemma in proofs.
431            core::mem::size_of::<Self::E>() == Self::C::PTE_SIZE,
432            Self::TOP_LEVEL_INDEX_RANGE.start < Self::TOP_LEVEL_INDEX_RANGE.end
433                <= nr_subpage_per_huge::<Self::C>(),
434    {
435        use vstd::arithmetic::mul::{
436            lemma_mul_inequality,
437            lemma_mul_inequality_converse,
438            lemma_mul_is_commutative,
439        };
440
441        Self::C::lemma_paging_consts_properties();
442        Self::lemma_page_table_config_constant_requirements();
443        let level = Self::C::NR_LEVELS;
444        let offset = pte_index_bit_offset_spec::<Self::C>(level);
445        let coverage = nr_page_table_coverage_bits_spec::<Self::C>();
446        let width = Self::C::ADDRESS_WIDTH;
447        lemma_page_size_is_pow2_pte_index_bit_offset::<Self::C>(level);
448        lemma_page_size_is_pow2_pte_index_bit_offset::<Self::C>((level + 1) as PagingLevel);
449        lemma_page_size_next::<Self::C>(level);
450        if coverage < width {
451            lemma_pow2_strictly_increases(coverage as nat, width as nat);
452        }
453        lemma_pow2_strictly_increases(width as nat, usize::BITS as nat);
454        lemma_pow2_adds(top_level_index_width_spec::<Self::C>() as nat, offset as nat);
455        let size = page_size::<Self::C>(level) as int;
456        let fanout = nr_subpage_per_huge::<Self::C>() as int;
457        let end = Self::TOP_LEVEL_INDEX_RANGE.end as int;
458        lemma_mul_is_commutative(size, fanout);
459        lemma_mul_inequality(end, fanout, size);
460        lemma_mul_inequality_converse(
461            end,
462            pow2(top_level_index_width_spec::<Self::C>() as nat) as int,
463            size,
464        );
465        lemma2_to64();
466    }
467}
468
469// Implement it so that we can comfortably use low level functions
470// like `page_size::<C>` without typing `C::C` everywhere.
471impl<C: PageTableConfig> PagingConstsTrait for C {
472    // Work around verus! dropping `open` on trait associated constants.
473    #[verus::internal(open)]
474    const BASE_PAGE_SIZE: usize = C::C::BASE_PAGE_SIZE;
475
476    #[verus::internal(open)]
477    const NR_LEVELS: PagingLevel = C::C::NR_LEVELS;
478
479    #[verus::internal(open)]
480    const HIGHEST_TRANSLATION_LEVEL: PagingLevel = C::C::HIGHEST_TRANSLATION_LEVEL;
481
482    #[verus::internal(open)]
483    const PTE_SIZE: usize = C::C::PTE_SIZE;
484
485    #[verus::internal(open)]
486    const ADDRESS_WIDTH: usize = C::C::ADDRESS_WIDTH;
487
488    #[verus::internal(open)]
489    const VA_SIGN_EXT: bool = C::C::VA_SIGN_EXT;
490
491    proof fn lemma_paging_consts_requirements() {
492        C::C::lemma_paging_consts_requirements();
493    }
494}
495
496/// Splits the address range into largest page table items.
497///
498/// Each of the returned items is a tuple of the physical address and the
499/// paging level. It is helpful when you want to map a physical address range
500/// into the provided virtual address.
501///
502/// For example, on x86-64, `C: PageTableConfig` may specify level 1 page as
503/// 4KiB, level 2 page as 2MiB, and level 3 page as 1GiB. Suppose that the
504/// supplied physical address range is from `0x3fdff000` to `0x80002000`,
505/// and the virtual address is also `0x3fdff000`, the following 5 items will
506/// be returned:
507///
508/// ```text
509/// 0x3fdff000                                                 0x80002000
510/// start                                                             end
511///   |----|----------------|--------------------------------|----|----|
512///    4KiB      2MiB                       1GiB              4KiB 4KiB
513/// ```
514///
515/// # Panics
516///
517/// Panics if:
518///  - any of `va`, `pa`, or `len` is not aligned to the base page size;
519///  - the range `va..(va + len)` is not valid for the page table.
520#[verifier::external_body]
521pub fn largest_pages<C: PageTableConfig>(
522    mut va: Vaddr,
523    mut pa: Paddr,
524    mut len: usize,
525) -> impl Iterator<Item = (Paddr, PagingLevel)> {
526    assert_eq!(va % C::BASE_PAGE_SIZE, 0);
527    assert_eq!(pa % C::BASE_PAGE_SIZE, 0);
528    assert_eq!(len % C::BASE_PAGE_SIZE, 0);
529    assert!(is_valid_range::<C>(&(va..(va + len))));
530
531    core::iter::from_fn(
532        move ||
533            {
534                if len == 0 {
535                    return None;
536                }
537                let mut level = C::HIGHEST_TRANSLATION_LEVEL;
538                while page_size::<C>(level) > len || va % page_size::<C>(level) != 0 || pa
539                    % page_size::<C>(level) != 0 {
540                    level -= 1;
541                }
542
543                let item_start = pa;
544                va += page_size::<C>(level);
545                pa += page_size::<C>(level);
546                len -= page_size::<C>(level);
547
548                Some((item_start, level))
549            },
550    )
551}
552
553/// Gets the top-level index width, in bits, for the page table.
554const fn top_level_index_width<C: PageTableConfig>() -> (ret: usize)
555    returns
556        top_level_index_width_spec::<C>(),
557{
558    proof {
559        C::lemma_paging_consts_properties();
560        C::lemma_page_table_config_constant_properties();
561    }
562
563    C::ADDRESS_WIDTH - pte_index_bit_offset::<C>(C::NR_LEVELS)
564}
565
566const fn pt_va_range_start<C: PageTableConfig>() -> (ret: Vaddr)
567    ensures
568        ret == page_table_managed_start_spec::<C>() - page_table_coverage_start_spec::<C>(),
569{
570    proof {
571        C::lemma_paging_consts_properties();
572        lemma_page_table_managed_bounds::<C>();
573        lemma_page_size_is_pow2_pte_index_bit_offset::<C>(C::NR_LEVELS);
574        let ghost idx_start = C::TOP_LEVEL_INDEX_RANGE.start;
575        let ghost offset = pte_index_bit_offset_spec::<C>(C::NR_LEVELS);
576        crate::specs::mm::page_table::vaddr_range_proofs::lemma_pt_va_range_start_shift_facts::<C>(
577            idx_start,
578            offset,
579        );
580        vstd::bits::lemma_usize_shl_is_mul(idx_start, offset);
581    }
582
583    C::TOP_LEVEL_INDEX_RANGE.start << pte_index_bit_offset::<C>(C::NR_LEVELS)
584}
585
586/// Inclusive positional end before sign extension, obtained from the managed end
587/// by removing the configured upper-address contribution and subtracting one.
588const fn pt_va_range_end<C: PageTableConfig>() -> (ret: Vaddr)
589    ensures
590        ret == page_table_managed_end_spec::<C>() - page_table_coverage_start_spec::<C>() - 1,
591{
592    let idx_end = C::TOP_LEVEL_INDEX_RANGE.end;
593    proof {
594        C::lemma_paging_consts_properties();
595    }
596    let offset = pte_index_bit_offset::<C>(C::NR_LEVELS);
597
598    proof {
599        crate::specs::mm::page_table::vaddr_range_proofs::lemma_pt_va_range_end_shift_facts::<C>(
600            idx_end,
601            offset,
602        );
603        lemma_page_size_is_pow2_pte_index_bit_offset::<C>(C::NR_LEVELS);
604        vstd::layout::unsigned_int_max_values();
605        vstd::bits::lemma_usize_shl_is_mul(idx_end, offset);
606    }
607
608    let shifted = idx_end << offset;
609    let ret = shifted.wrapping_sub(1);
610
611    ret
612}
613
614const fn sign_bit_of_va<C: PageTableConfig>(va: Vaddr) -> (ret: bool)
615    ensures
616        ret == ((va as int / pow2((C::ADDRESS_WIDTH - 1) as nat) as int) % 2 == 1),
617{
618    proof {
619        C::lemma_paging_consts_properties();
620        C::lemma_page_table_config_constant_properties();
621        vstd::bits::lemma_usize_shr_is_div(va, (C::ADDRESS_WIDTH - 1) as usize);
622        vstd::bits::lemma_usize_low_bits_mask_is_mod(va >> (C::ADDRESS_WIDTH - 1), 1);
623        vstd::bits::lemma_low_bits_mask_values();
624        vstd::arithmetic::power2::lemma2_to64();
625    }
626    (va >> (C::ADDRESS_WIDTH - 1)) & 1 != 0
627}
628
629/// Apply the sign-extension OR to a positional value.
630///
631/// For any value `va` in `[0, 2^ADDRESS_WIDTH)`, the OR with
632/// `!0 ^ ((1 << ADDRESS_WIDTH) - 1)` is equivalent to adding
633/// the derived upper-address contribution, because the mask's bits and `va`'s bits are
634/// disjoint.
635const fn apply_sign_ext<C: PageTableConfig>(va: Vaddr) -> (ret: Vaddr)
636    requires
637        va < pow2(C::ADDRESS_WIDTH as nat),
638        C::ADDRESS_WIDTH < usize::BITS,
639        page_table_coverage_start_spec::<C>() == 0x1_0000_0000_0000_0000int - pow2(
640            C::ADDRESS_WIDTH as nat,
641        ),
642    ensures
643        ret == va + page_table_coverage_start_spec::<C>(),
644{
645    let address_width = C::ADDRESS_WIDTH;
646    let low_bit = 1usize << address_width;
647    proof {
648        vstd::layout::unsigned_int_max_values();
649        vstd::bits::lemma_usize_pow2_no_overflow(address_width as nat);
650        vstd::bits::lemma_usize_shl_is_mul(1usize, address_width);
651    }
652    let low_mask = low_bit - 1;
653    let sign_ext_mask = !0 ^ low_mask;
654    let ret = va | sign_ext_mask;
655    proof {
656        assert(!0usize == 0xffff_ffff_ffff_ffffusize) by (compute_only);
657        assert(sign_ext_mask == usize::MAX - low_mask) by (bit_vector)
658            requires
659                sign_ext_mask == (!0usize ^ low_mask),
660                !0usize == 0xffff_ffff_ffff_ffffusize,
661                usize::MAX == 0xffff_ffff_ffff_ffffusize,
662        ;
663        assert(pow2(64) == 0x1_0000_0000_0000_0000nat) by {
664            vstd::arithmetic::power2::lemma2_to64();
665        };
666        assert(sign_ext_mask == 0x1_0000_0000_0000_0000int - pow2(address_width as nat));
667        assert(sign_ext_mask == page_table_coverage_start_spec::<C>());
668
669        assert((va & sign_ext_mask) == 0usize) by (bit_vector)
670            requires
671                address_width < usize::BITS,
672                low_bit == 1usize << address_width,
673                low_mask == low_bit - 1,
674                sign_ext_mask == !0usize ^ low_mask,
675                va < low_bit,
676        ;
677        assert(ret == va + sign_ext_mask) by (bit_vector)
678            requires
679                ret == va | sign_ext_mask,
680                (va & sign_ext_mask) == 0usize,
681        ;
682    }
683    ret
684}
685
686/// Gets the managed virtual addresses range for the page table.
687///
688/// Returns a [`RangeInclusive`] because the end address, when the range
689/// reaches the top of the 64-bit address space (e.g. the canonical
690/// high-half kernel range ending at `usize::MAX`), would overflow the
691/// exclusive end of a [`Range<Vaddr>`].
692#[verusfmt::skip]
693const fn vaddr_range<C: PageTableConfig>() -> (ret: RangeInclusive<Vaddr>)
694    ensures
695        ret@ == vaddr_range_spec::<C>(),
696{
697    let mut start = pt_va_range_start::<C>();
698    let mut end = pt_va_range_end::<C>();
699
700    proof {
701        reveal(leading_bits_spec);
702        C::lemma_paging_consts_properties();
703        C::lemma_page_table_config_constant_properties();
704        lemma_leading_bits_properties::<C>();
705        if leading_bits_spec::<C>() == 0 {
706            assert(page_table_coverage_start_spec::<C>() == 0) by (nonlinear_arith)
707                requires
708                    leading_bits_spec::<C>() == 0,
709                    page_table_coverage_start_spec::<C>() == leading_bits_spec::<C>() * pow2(
710                        nr_page_table_coverage_bits_spec::<C>() as nat,
711                    ),
712            ;
713        }
714        lemma_page_table_managed_bounds::<C>();
715        lemma_page_size_is_pow2_pte_index_bit_offset::<C>(C::NR_LEVELS);
716        lemma2_to64();
717        crate::specs::mm::page_table::vaddr_range_proofs::lemma_idx_times_pow2_bound::<C>(
718            start,
719            end,
720        );
721    }
722
723    if C::VA_SIGN_EXT && sign_bit_of_va::<C>(pt_va_range_start::<C>()) {
724        start = apply_sign_ext::<C>(start);
725        end = apply_sign_ext::<C>(end);
726    }
727    proof {
728        reveal(leading_bits_spec);
729        assert(start == vaddr_range_spec::<C>().start);
730        assert(end == vaddr_range_spec::<C>().end);
731    }
732    start..=end
733}
734
735/// Checks if the given range is covered by the valid range of the page table.
736const fn is_valid_range<C: PageTableConfig>(r: &Range<Vaddr>) -> bool
737    returns
738        is_valid_range_spec::<C>(*r),
739{
740    proof {
741        lemma_page_table_managed_bounds::<C>();
742    }
743    let va_range = vaddr_range::<C>();
744    r.start < r.end && (*va_range.start() <= r.start && r.end - 1 <= *va_range.end())
745}
746
747// Here are some const values that are determined by the paging constants.
748/// The number of virtual address bits used to index a PTE in a page.
749const fn nr_pte_index_bits<C: PagingConstsTrait>() -> usize
750    returns
751        nr_pte_index_bits_spec::<C>(),
752{
753    proof {
754        C::lemma_paging_consts_properties();
755    }
756    nr_subpage_per_huge::<C>().ilog2() as usize
757}
758
759/// The index of a VA's PTE in a page table node at the given level.
760const fn pte_index<C: PagingConstsTrait>(va: Vaddr, level: PagingLevel) -> (res: usize)
761    requires
762        1 <= level <= C::NR_LEVELS,
763    returns
764        pte_index_spec::<C>(va, level),
765{
766    proof {
767        C::lemma_paging_consts_properties();
768    }
769    (va >> pte_index_bit_offset::<C>(level)) & (nr_subpage_per_huge::<C>() - 1)
770}
771
772/// The bit offset of the entry offset part in a virtual address.
773///
774/// This function returns the bit offset of the least significant bit. Take
775/// x86-64 as an example, the `pte_index_bit_offset(2)` should return 21, which
776/// is 12 (the 4KiB in-page offset) plus 9 (index width in the level-1 table).
777const fn pte_index_bit_offset<C: PagingConstsTrait>(level: PagingLevel) -> usize
778    requires
779        1 <= level <= C::NR_LEVELS,
780    ensures
781        pte_index_bit_offset_spec::<C>(level) < usize::BITS,
782    returns
783        pte_index_bit_offset_spec::<C>(level),
784{
785    proof {
786        C::lemma_paging_consts_properties();
787        assert(C::BASE_PAGE_SIZE.ilog2() + nr_pte_index_bits_spec::<C>() * (level - 1)
788            < usize::BITS) by (nonlinear_arith)
789            requires
790                level <= C::NR_LEVELS,
791                C::BASE_PAGE_SIZE.ilog2() + nr_pte_index_bits_spec::<C>() * C::NR_LEVELS
792                    <= C::ADDRESS_WIDTH,
793                C::ADDRESS_WIDTH < usize::BITS,
794        ;
795    }
796    C::BASE_PAGE_SIZE.ilog2() as usize + nr_pte_index_bits::<C>() * (level as usize - 1)
797}
798
799/// A handle to a page table.
800/// A page table can track the lifetime of the mapped physical pages.
801pub struct PageTable<C: PageTableConfig> {
802    pub root: PageTableNode<C>,
803}
804
805/*
806impl PageTable<UserPtConfig> {
807    pub fn activate(&self) {
808        // SAFETY: The user mode page table is safe to activate since the kernel
809        // mappings are shared.
810        unsafe {
811            self.root.activate();
812        }
813    }
814}*/
815
816impl PageTable<KernelPtConfig> {
817    /// Create a new kernel page table.
818    #[verifier::external_body]
819    pub(crate) fn new_kernel_page_table() -> Self {
820        unimplemented!()/*        let kpt = Self::empty();
821
822        // Make shared the page tables mapped by the root table in the kernel space.
823        {
824        let preempt_guard = disable_preempt();
825        let mut root_node = kpt.root.borrow().lock(&preempt_guard);
826
827        for i in KernelPtConfig::TOP_LEVEL_INDEX_RANGE {
828            let mut root_entry = root_node.entry(i);
829            let _ = root_entry.alloc_if_none(&preempt_guard).unwrap();
830            }
831        }
832
833        kpt*/
834
835    }
836
837    /// Panic condition for [`Self::create_user_page_table`]:
838    /// Some kernel root entry at index `i` in `TOP_LEVEL_INDEX_RANGE` is
839    /// not a page table node (i.e., is absent or maps a huge frame).
840    pub open spec fn create_user_pt_panic_condition(root_owner: NodeOwner<KernelPtConfig>) -> bool {
841        exists|i: usize|
842            #![trigger root_owner.children_perm.value()[i as int]]
843            KernelPtConfig::TOP_LEVEL_INDEX_RANGE.start <= i
844                < KernelPtConfig::TOP_LEVEL_INDEX_RANGE.end && {
845                let pte = root_owner.children_perm.value()[i as int];
846                ||| !pte.is_present()
847                ||| pte.is_last(root_owner.level())
848            }
849    }
850
851    /// Create a new user page table.
852    ///
853    /// This should be the only way to create the user page table, that is to
854    /// duplicate the kernel page table with all the kernel mappings shared.
855    #[verus_spec(r =>
856        with Tracked(kernel_owner): Tracked<&PageTableOwner<KernelPtConfig>>,
857            Tracked(regions): Tracked<&mut MetaRegionOwners>,
858            Tracked(guards): Tracked<&mut Guards>,
859        requires
860            kernel_owner.inv(),
861            old(regions).inv(),
862            kernel_owner.0.value().is_node(),
863            !Self::create_user_pt_panic_condition(kernel_owner.0.value().node()),
864            self.root.slot_vaddr() == kernel_owner.0.value().node().slot_vaddr(),
865            self.relates_owner(*kernel_owner, *old(regions)),
866            kernel_owner.0.value().metaregion_sound(*old(regions)),
867            kernel_owner.metaregion_sound(*old(regions)),
868            // The kernel root is not currently locked.
869            old(guards).unlocked(kernel_owner.0.value().node().slot_vaddr()),
870        ensures
871            final(regions).inv(),
872    )]
873    pub(in crate::mm) fn create_user_page_table(&'static self) -> PageTable<UserPtConfig> {
874        proof_decl! {
875            let tracked mut new_pt_owner: Option<PageTableOwner<UserPtConfig>> = None;
876        }
877        let ghost regions_before_alloc = *regions;
878        let new_pt: PageTable<UserPtConfig> = (
879        #[verus_spec(with Tracked(&mut new_pt_owner), Tracked(regions), Tracked(guards))]
880        PageTable::empty_with_owner());
881        let new_root = new_pt.root;
882        let preempt_guard = disable_preempt();
883        // Capture new_idx as a ghost BEFORE the tracked_take below empties new_pt_owner.
884        let ghost new_idx_g: int = frame_to_index(
885            new_pt_owner@.unwrap().0.value().meta_slot_paddr().unwrap(),
886        );
887        proof {
888            let kern_idx = frame_to_index(kernel_owner.0.value().meta_slot_paddr().unwrap());
889            let new_idx = new_idx_g;
890            EntryOwner::<KernelPtConfig>::lemma_active_entry_not_in_free_pool(
891                kernel_owner.0.value(),
892                regions_before_alloc,
893                new_idx,
894            );
895        }
896
897        proof_decl! {
898            let tracked root_owner: &NodeOwner<KernelPtConfig>
899                = kernel_owner.0.tracked_borrow_value().tracked_borrow_node();
900            let tracked mut new_pt_owner_val: PageTableOwner<UserPtConfig>
901                = new_pt_owner.tracked_take();
902            let tracked mut new_node_owner: NodeOwner<UserPtConfig> = {
903                let tracked new_pt_value = new_pt_owner_val.0.tracked_borrow_mut_value();
904                new_pt_value.tracked_take_node()
905            };
906            let tracked mut entry_owner: &EntryOwner<KernelPtConfig>;
907        }
908
909        // Discharge borrow/lock preconditions for the kernel root from
910        // kernel_owner.inv() + metaregion_sound + guards unlocked.
911        proof {
912            assert(kernel_owner.0.value().is_node());
913            assert(kernel_owner.0.value().metaregion_sound(*regions));
914        }
915        let mut root_node = {
916            let root_ref = self.root.borrow();
917            #[verus_spec(with Tracked(guards), Tracked(regions.tracked_borrow_slot_owner(root_ref.start_paddr_spec()).metadata_perm.tracked_borrow()))]
918            root_ref.lock(&preempt_guard)
919        };
920        let mut new_node: PageTableGuard<'_, UserPtConfig> = {
921            let new_ref = new_root.borrow();
922            #[verus_spec(with Tracked(guards), Tracked(regions.tracked_borrow_slot_owner(new_ref.start_paddr_spec()).metadata_perm.tracked_borrow()))]
923            new_ref.lock(&preempt_guard)
924        };
925        for i in KernelPtConfig::TOP_LEVEL_INDEX_RANGE
926            invariant
927                kernel_owner.inv(),
928                kernel_owner.0.value().is_node(),
929                regions.inv(),
930                !Self::create_user_pt_panic_condition(kernel_owner.0.value().node()),
931                // Lock postcondition for the kernel root.
932                *root_owner == kernel_owner.0.value().node(),
933                root_owner.relate_guard(root_node),
934                // Tree-wide soundness of the kernel page table.
935                kernel_owner.metaregion_sound(*regions),
936                // The new node owner's invariants and guard relation.
937                new_node_owner.inv(),
938                new_node_owner.relate_guard(new_node),
939                regions.contains(new_node_owner.slot_index),
940        {
941            proof {
942                let kern_node = kernel_owner.0.value().node();
943                assert forall|j: usize|
944                    #![trigger kern_node.children_perm.value()[j as int]]
945                    KernelPtConfig::TOP_LEVEL_INDEX_RANGE.start <= j
946                        < KernelPtConfig::TOP_LEVEL_INDEX_RANGE.end implies {
947                    let pte = kern_node.children_perm.value()[j as int];
948                    pte.is_present() && !pte.is_last(kern_node.level())
949                } by {
950                    let pte = kern_node.children_perm.value()[j as int];
951                    if !pte.is_present() || pte.is_last(kern_node.level()) {
952                        assert(Self::create_user_pt_panic_condition(kern_node));
953                    }
954                }
955
956                lemma_vaddr_range_spec_kernel();
957                kernel_owner.pt_inv_unroll(i as int);
958                let tracked child_subtree: &OwnerSubtree<KernelPtConfig> =
959                    kernel_owner.0.tracked_borrow_child(i as int);
960                entry_owner = child_subtree.tracked_borrow_value();
961                let kern_node = kernel_owner.0.value().node();
962                assert(entry_owner.match_pte(
963                    kern_node.children_perm.value()[i as int],
964                    entry_owner.parent_level,
965                ));
966                assert(entry_owner.parent_level == kern_node.level());
967                assert(child_subtree.inv());
968                assert(entry_owner.inv());
969                assert(root_owner.relate_guard(root_node));
970
971                kernel_owner.0.lemma_subtree_satisfies_unroll_once(
972                    kernel_owner.0.value().path,
973                    PageTableOwner::<KernelPtConfig>::metaregion_sound_pred(*regions),
974                    i as int,
975                );
976                assert(child_subtree.subtree_satisfies(
977                    kernel_owner.0.value().path.push_tail(i as int),
978                    PageTableOwner::<KernelPtConfig>::metaregion_sound_pred(*regions),
979                ));
980                assert(entry_owner.metaregion_sound(*regions));
981            }
982
983            #[verus_spec(with Tracked(root_owner), Tracked(entry_owner), Tracked(&*regions))]
984            let root_entry = root_node.entry(i);
985            let ghost pre_to_ref_regions: MetaRegionOwners = *regions;
986            #[verus_spec(with Tracked(entry_owner), Tracked(regions.tracked_borrow_slot_owner(root_entry.node.inner.start_paddr_spec()).metadata_perm.tracked_borrow()), Tracked(&*regions))]
987            let child = root_entry.to_ref();
988
989            proof {
990                let kern_node = kernel_owner.0.value().node();
991                let pte = kern_node.children_perm.value()[i as int];
992
993                assert(pte.is_present() && !pte.is_last(kern_node.level())) by {
994                    if !pte.is_present() || pte.is_last(kern_node.level()) {
995                        assert(KernelPtConfig::TOP_LEVEL_INDEX_RANGE.start <= i
996                            < KernelPtConfig::TOP_LEVEL_INDEX_RANGE.end);
997                        assert(exists|j: usize|
998                            KernelPtConfig::TOP_LEVEL_INDEX_RANGE.start <= j
999                                < KernelPtConfig::TOP_LEVEL_INDEX_RANGE.end && {
1000                                let p = #[trigger] kern_node.children_perm.value()[j as int];
1001                                ||| !p.is_present()
1002                                ||| p.is_last(kern_node.level())
1003                            });
1004                        assert(Self::create_user_pt_panic_condition(kern_node));
1005                    }
1006                }
1007                kernel_owner.lemma_metaregion_sound_preserved_slot_owners_eq(
1008                    pre_to_ref_regions,
1009                    *regions,
1010                );
1011            }
1012            let ChildRef::PageTable(pt) = child else {
1013                panic!("The kernel page table doesn't contain shared nodes");
1014            };
1015
1016            let pt_addr = pt.start_paddr();
1017            let pte = PageTableEntry::new_pt(pt_addr);
1018
1019            proof {
1020                assert(regions.contains(new_node_owner.slot_index));
1021            }
1022            unsafe {
1023                #[verus_spec(with Tracked(&mut new_node_owner), Tracked(&*regions))]
1024                new_node.write_pte(i, pte)
1025            };
1026        }
1027
1028        PageTable::<UserPtConfig> { root: new_root }
1029    }/*
1030    /// Protect the given virtual address range in the kernel page table.
1031    ///
1032    /// This method flushes the TLB entries when doing protection.
1033    ///
1034    /// # Safety
1035    ///
1036    /// The caller must ensure that the protection operation does not affect
1037    /// the memory safety of the kernel.
1038    pub unsafe fn protect_flush_tlb(
1039        &self,
1040        vaddr: &Range<Vaddr>,
1041        mut op: impl FnMut(&mut PageProperty),
1042    ) -> Result<(), PageTableError> {
1043        let preempt_guard = disable_preempt();
1044        let mut cursor = CursorMut::new(self, &preempt_guard, vaddr)?;
1045        // SAFETY: The safety is upheld by the caller.
1046        while let Some(range) =
1047            unsafe { cursor.protect_next(vaddr.end - cursor.virt_addr(), &mut op) }
1048        {
1049            crate::arch::mm::tlb_flush_addr(range.start);
1050        }
1051        Ok(())
1052    }*/
1053
1054}
1055
1056#[verus_verify]
1057impl<C: PageTableConfig> PageTable<C> {
1058    /// Relates this executable page-table handle to its tracked ownership tree.
1059    pub open spec fn relates_owner(
1060        &self,
1061        owner: PageTableOwner<C>,
1062        regions: MetaRegionOwners,
1063    ) -> bool {
1064        &&& owner.inv()
1065        &&& self.root.slot_vaddr() == owner.0.value().node().slot_vaddr()
1066        &&& self.root.inv()
1067        &&& owner.0.value().node().matches_permission(self.root.frac_metadata_perm())
1068        &&& owner.0.value().node_permission is None
1069        &&& self.root.tracked_slot_perm@ == regions.slots[owner.0.value().node().slot_index]
1070        &&& owner.0.value().node().level() == C::NR_LEVELS
1071        &&& owner.0.value().path == vstd_extra::ghost_tree::TreePath::<NR_ENTRIES>::new(
1072            Seq::empty(),
1073        )
1074        &&& owner.metaregion_sound(regions)
1075    }
1076
1077    /// Create a new empty page table.
1078    ///
1079    /// Useful for the IOMMU page tables only.
1080    #[verifier::external_body]
1081    pub fn empty() -> Self {
1082        unimplemented!()
1083    }
1084
1085    /// Create a new empty page table together with its tracked ownership.
1086    #[verifier::external_body]
1087    #[verus_spec(r =>
1088        with Tracked(owner): Tracked<&mut Option<PageTableOwner<C>>>,
1089            Tracked(regions): Tracked<&mut MetaRegionOwners>,
1090            Tracked(guards): Tracked<&mut Guards>,
1091        requires
1092            old(regions).inv(),
1093        ensures
1094            final(owner)@ is Some,
1095            final(owner)@->0.inv(),
1096            (final(owner)@->0).0.value().is_node(),
1097            r.root.slot_vaddr() == (final(owner)@->0).0.value().node().slot_vaddr(),
1098            (final(owner)@->0).0.value().metaregion_sound(*final(regions)),
1099            r.relates_owner(final(owner)@->0, *final(regions)),
1100            final(regions).inv(),
1101            final(guards).unlocked((final(owner)@->0).0.value().node().slot_vaddr()),
1102            // Allocating a fresh node does not change the lock set, so any node
1103            // that was (un)locked before remains so.
1104            final(guards).guards == old(guards).guards,
1105            old(regions).contains(
1106                frame_to_index(
1107                    (final(owner)@->0).0.value().meta_slot_paddr()->0)),
1108            final(regions).contains(
1109                frame_to_index(
1110                    (final(owner)@->0).0.value().meta_slot_paddr()->0)),
1111            MetaSlot::claim_unused_slot_region_spec(
1112                (final(owner)@->0).0.value().meta_slot_paddr()->0,
1113                false, *old(regions), *final(regions)),
1114            // Allocation preserves the soundness of the kernel page-table tree:
1115            // a fresh allocation cannot collide with any active node or frame entry
1116            // (the allocator returns a slot that wasn't in use).
1117            forall |kt: PageTableOwner<KernelPtConfig>|
1118                #![trigger kt.metaregion_sound(*final(regions))]
1119                kt.inv() && kt.metaregion_sound(*old(regions))
1120                ==> kt.metaregion_sound(*final(regions)),
1121            forall |kt: PageTableOwner<KernelPtConfig>|
1122                #![trigger kt.metaregion_sound(*old(regions))]
1123                kt.inv() && kt.metaregion_sound(*old(regions)) ==>
1124                kt.0.subtree_satisfies(
1125                    kt.0.value().path,
1126                    |e: EntryOwner<KernelPtConfig>,
1127                     p: vstd_extra::ghost_tree::TreePath<NR_ENTRIES>|
1128                        e.is_node() || (e.is_frame() && e.frame_is_tracked()) ==>
1129                            frame_to_index(e.meta_slot_paddr()->0) !=
1130                            frame_to_index((final(owner)@->0).0.value().meta_slot_paddr()->0),
1131                ),
1132    )]
1133    pub fn empty_with_owner<'rcu>() -> Self {
1134        unimplemented!()
1135    }
1136
1137    #[verifier::external_body]
1138    pub(in crate::mm) unsafe fn first_activate_unchecked(&self) {
1139        unimplemented!()
1140        // SAFETY: The safety is upheld by the caller.
1141        //        unsafe { self.root.first_activate() };
1142
1143    }
1144
1145    pub uninterp spec fn root_paddr_spec(&self) -> Paddr;
1146
1147    /// The physical address of the root page table.
1148    ///
1149    /// Obtaining the physical address of the root page table is safe, however, using it or
1150    /// providing it to the hardware will be unsafe since the page table node may be dropped,
1151    /// resulting in UAF.
1152    #[verifier::external_body]
1153    #[verifier::when_used_as_spec(root_paddr_spec)]
1154    pub fn root_paddr(&self) -> (r: Paddr)
1155        returns
1156            self.root_paddr_spec(),
1157    {
1158        unimplemented!()
1159        //        self.root.start_paddr()
1160
1161    }
1162
1163    /// Query about the mapping of a single byte at the given virtual address.
1164    ///
1165    /// Note that this function may fail reflect an accurate result if there are
1166    /// cursors concurrently accessing the same virtual address range, just like what
1167    /// happens for the hardware MMU walk.
1168    #[cfg(ktest)]
1169    pub fn page_walk(&self, vaddr: Vaddr) -> Option<(Paddr, PageProperty)> {
1170        // SAFETY: The root node is a valid page table node so the address is valid.
1171        unsafe { page_walk::<C>(self.root_paddr(), vaddr) }
1172    }
1173
1174    /// Create a new cursor exclusively accessing the virtual address range for mapping.
1175    ///
1176    /// If another cursor is already accessing the range, the new cursor may wait until the
1177    /// previous cursor is dropped.
1178    #[verus_spec(r =>
1179        with Tracked(owner): Tracked<PageTableOwner<C>>,
1180            Ghost(root_guard): Ghost<PageTableGuard<'rcu, C>>,
1181            Tracked(regions): Tracked<&mut MetaRegionOwners>,
1182            Tracked(guards): Tracked<&mut Guards>
1183        requires
1184            self.relates_owner(owner, *old(regions)),
1185            Cursor::<C>::cursor_new_input_valid(*va)
1186                ==> Cursor::<C>::cursor_new_success_conditions(*va),
1187            owner.0.value().node().relate_guard(root_guard),
1188            va.end > 0,
1189        ensures
1190            final(regions).slots == old(regions).slots,
1191            forall|idx: int| #![trigger final(regions).slot_owners[idx]]
1192                old(regions).contains(idx) && old(regions).ref_count(idx) != REF_COUNT_UNUSED ==>
1193                    final(regions).slot_owners[idx] == old(regions).slot_owners[idx],
1194            Cursor::<C>::cursor_new_success_conditions(*va) ==> {
1195                &&& r is Ok
1196                &&& r.unwrap().0.0.invariants(*r.unwrap().1, *final(regions), *final(guards))
1197                &&& r.unwrap().1.in_barrier_va()
1198                &&& r.unwrap().0.0.level == r.unwrap().0.0.guard_level
1199                &&& r.unwrap().0.0.va < r.unwrap().0.0.barrier_va.end
1200                &&& r.unwrap().0.0.va == va.start
1201                &&& r.unwrap().0.0.barrier_va == *va
1202            },
1203            !Cursor::<C>::cursor_new_success_conditions(*va) ==> r is Err,
1204            forall |item: C::Item| #![trigger CursorMut::<'rcu, C>::item_not_mapped(item, *old(regions))]
1205                CursorMut::<'rcu, C>::item_not_mapped(item, *old(regions)) ==>
1206                CursorMut::<'rcu, C>::item_not_mapped(item, *final(regions)),
1207            // CursorMut::new inherits Cursor::new's weakened preservation:
1208            // PT-node allocations come from UNUSED slots, so any slot that
1209            // was already in use keeps its paths_in_pt.
1210            forall |idx: int| #![trigger final(regions).slot_owners[idx].paths_in_pt]
1211                old(regions).contains(idx) && old(regions).ref_count(idx)
1212                    != REF_COUNT_UNUSED
1213                ==> final(regions).slot_owners[idx].paths_in_pt
1214                        == old(regions).slot_owners[idx].paths_in_pt,
1215            forall|idx: int| #![trigger final(regions).slot_owners[idx]]
1216                old(regions).contains(idx)
1217                && old(regions).ref_count(idx)
1218                    != REF_COUNT_UNUSED
1219                ==> final(regions).ref_count(idx)
1220                        == old(regions).ref_count(idx)
1221                    && final(regions).slot_owners[idx].usage
1222                        == old(regions).slot_owners[idx].usage,
1223    )]
1224    pub fn cursor_mut<'rcu, G: AsAtomicModeGuard>(
1225        &'rcu self,
1226        guard: &'rcu G,
1227        va: &Range<Vaddr>,
1228    ) -> Result<(CursorMut<'rcu, C>, Tracked<CursorOwner<'rcu, C>>), PageTableError> {
1229        #[verus_spec(with Tracked(owner), Ghost(root_guard), Tracked(regions), Tracked(guards))]
1230        CursorMut::new(self, guard.as_atomic_mode_guard(), va)
1231    }
1232
1233    /// Create a new cursor exclusively accessing the virtual address range for querying.
1234    ///
1235    /// If another cursor is already accessing the range, the new cursor may wait until the
1236    /// previous cursor is dropped. The modification to the mapping by the cursor may also
1237    /// block or be overridden by the mapping of another cursor.
1238    #[verus_spec(r =>
1239        with Tracked(owner): Tracked<PageTableOwner<C>>,
1240            Ghost(root_guard): Ghost<PageTableGuard<'rcu, C>>,
1241            Tracked(regions): Tracked<&mut MetaRegionOwners>,
1242            Tracked(guards): Tracked<&mut Guards>
1243        requires
1244            self.relates_owner(owner, *old(regions)),
1245            Cursor::<C>::cursor_new_input_valid(*va)
1246                ==> Cursor::<C>::cursor_new_success_conditions(*va),
1247            owner.0.value().node().relate_guard(root_guard),
1248            va.end > 0,
1249        ensures
1250            final(regions).slots == old(regions).slots,
1251            forall|idx: int| #![trigger final(regions).slot_owners[idx]]
1252                old(regions).contains(idx) && old(regions).ref_count(idx) != REF_COUNT_UNUSED ==>
1253                    final(regions).slot_owners[idx] == old(regions).slot_owners[idx],
1254            Cursor::<C>::cursor_new_success_conditions(*va) ==> {
1255                &&& r is Ok
1256                &&& r.unwrap().0.invariants(*r.unwrap().1, *final(regions), *final(guards))
1257                &&& r.unwrap().1.in_barrier_va()
1258                &&& r.unwrap().0.level == r.unwrap().0.guard_level
1259                &&& r.unwrap().0.va < r.unwrap().0.barrier_va.end
1260                &&& r.unwrap().0.va == va.start
1261                &&& r.unwrap().0.barrier_va == *va
1262                &&& r.unwrap().1@.as_page_table_owner() == owner
1263                &&& r.unwrap().1@.continuations[C::NR_LEVELS - 1].path() == owner.0.value().path
1264            },
1265            !Cursor::<C>::cursor_new_success_conditions(*va) ==> r is Err,
1266            forall|idx: int| #![trigger final(regions).slot_owners[idx].paths_in_pt]
1267                old(regions).contains(idx) && old(regions).ref_count(idx)
1268                    != REF_COUNT_UNUSED
1269                ==> final(regions).slot_owners[idx].paths_in_pt
1270                        == old(regions).slot_owners[idx].paths_in_pt,
1271            // Non-saturation preservation.
1272            (forall |i: int| #![trigger old(regions).slot_owners[i]]
1273                old(regions).contains(i)
1274                && old(regions).ref_count(i)
1275                    != REF_COUNT_UNUSED
1276                ==> old(regions).ref_count(i) + 1
1277                    < REF_COUNT_MAX)
1278            ==>
1279            (forall |i: int| #![trigger final(regions).slot_owners[i]]
1280                final(regions).contains(i)
1281                && final(regions).ref_count(i)
1282                    != REF_COUNT_UNUSED
1283                ==> final(regions).ref_count(i) + 1
1284                    < REF_COUNT_MAX),
1285            forall|idx: int| #![trigger final(regions).slot_owners[idx].ref_count()]
1286                final(regions).ref_count(idx)
1287                    >= REF_COUNT_MAX
1288                ==> old(regions).ref_count(idx)
1289                        == final(regions).ref_count(idx),
1290            forall|idx: int| #![trigger old(regions).slot_owners[idx].ref_count()]
1291                old(regions).ref_count(idx)
1292                    >= REF_COUNT_MAX
1293                ==> final(regions).ref_count(idx)
1294                        == old(regions).ref_count(idx),
1295    )]
1296    pub fn cursor<'rcu, G: AsAtomicModeGuard>(
1297        &'rcu self,
1298        guard: &'rcu G,
1299        va: &Range<Vaddr>,
1300    ) -> Result<(Cursor<'rcu, C>, Tracked<CursorOwner<'rcu, C>>), PageTableError> {
1301        proof {
1302            C::lemma_paging_consts_properties();
1303            C::lemma_page_table_config_constant_properties();
1304        }
1305        #[verus_spec(with Tracked(owner), Ghost(root_guard), Tracked(regions), Tracked(guards))]
1306        Cursor::new(self, guard.as_atomic_mode_guard(), va)
1307    }/*
1308    /// Create a new reference to the same page table.
1309    /// The caller must ensure that the kernel page table is not copied.
1310    /// This is only useful for IOMMU page tables. Think twice before using it in other cases.
1311    pub unsafe fn shallow_copy(&self) -> Self {
1312        PageTable {
1313            root: self.root.clone(),
1314        }
1315    }
1316    */
1317
1318}
1319
1320/// A software emulation of the MMU address translation process.
1321///
1322/// This method returns the physical address of the given virtual address and
1323/// the page property if a valid mapping exists for the given virtual address.
1324///
1325/// # Safety
1326///
1327/// The caller must ensure that the `root_paddr` is a pointer to a valid root
1328/// page table node.
1329///
1330/// # Notes on the page table use-after-free problem
1331///
1332/// Neither the hardware MMU nor the software page walk method acquires the page
1333/// table locks while reading. They can enter a to-be-recycled page table node
1334/// and read the page table entries after the node is recycled and reused.
1335///
1336/// For the hardware MMU page walk, we mitigate this problem by dropping the page
1337/// table nodes only after the TLBs have been flushed on all the CPUs that
1338/// activate the page table.
1339///
1340/// For the software page walk, we only need to disable preemption at the beginning
1341/// since the page table nodes won't be recycled in the RCU critical section.
1342#[cfg(ktest)]
1343pub(super) unsafe fn page_walk<C: PageTableConfig>(root_paddr: Paddr, vaddr: Vaddr) -> Option<
1344    (Paddr, PageProperty),
1345> {
1346    use super::paddr_to_vaddr;
1347
1348    let _rcu_guard = disable_preempt();
1349
1350    let mut pt_addr = paddr_to_vaddr(root_paddr);
1351    #[verusfmt::skip]
1352    for cur_level in (1..= C::NR_LEVELS).rev() {
1353        let offset = pte_index::<C>(vaddr, cur_level);
1354        // SAFETY:
1355        //  - The page table node is alive because (1) the root node is alive and
1356        //    (2) all child nodes cannot be recycled because we're in the RCU critical section.
1357        //  - The index is inside the bound, so the page table entry is valid.
1358        //  - All page table entries are aligned and accessed with atomic operations only.
1359        let cur_pte = unsafe { load_pte((pt_addr as *mut C::E).add(offset), Ordering::Acquire) };
1360
1361        if !cur_pte.is_present() {
1362            return None;
1363        }
1364        if cur_pte.is_last(cur_level) {
1365            debug_assert!(cur_level <= C::HIGHEST_TRANSLATION_LEVEL);
1366            return Some(
1367                (cur_pte.paddr() + (vaddr & (page_size::<C>(cur_level) - 1)), cur_pte.prop()),
1368            );
1369        }
1370        pt_addr = paddr_to_vaddr(cur_pte.paddr());
1371    }
1372
1373    unreachable!("All present PTEs at the level 1 must be last-level PTEs");
1374}
1375
1376/// A trait that abstracts architecture-specific page table entries (PTEs).
1377///
1378/// Note that a default PTE should be a PTE that points to nothing.
1379pub trait PageTableEntryTrait:
1380    Clone + Copy + Debug + Default + Sized + Pod + PodOnce + Send + Sync + 'static {
1381    spec fn new_absent_spec() -> Self;
1382
1383    /// Create a set of new invalid page table flags that indicates an absent page.
1384    ///
1385    /// Note that currently the implementation requires an all zero PTE to be an absent PTE.
1386    #[verifier(when_used_as_spec(new_absent_spec))]
1387    fn new_absent() -> (res: Self)
1388        ensures
1389            valid_frame_paddr(res.paddr()),
1390            !res.is_present(),
1391        returns
1392            Self::new_absent(),
1393    ;
1394
1395    spec fn is_present_spec(&self) -> bool;
1396
1397    /// Returns if the PTE points to something.
1398    ///
1399    /// For PTEs created by [`Self::new_absent`], this method should return
1400    /// false. For PTEs created by [`Self::new_page`] or [`Self::new_pt`]
1401    /// and modified with [`Self::set_prop`], this method should return true.
1402    #[verifier::when_used_as_spec(is_present_spec)]
1403    fn is_present(&self) -> bool
1404        returns
1405            self.is_present_spec(),
1406    ;
1407
1408    spec fn new_page_spec(paddr: Paddr, level: PagingLevel, prop: PageProperty) -> Self;
1409
1410    /// The preconditions for creating a new page-mapping PTE.
1411    spec fn new_page_req(paddr: Paddr, level: PagingLevel, prop: PageProperty) -> bool;
1412
1413    /// Creates a new PTE that maps to a page.
1414    #[verifier::when_used_as_spec(new_page_spec)]
1415    fn new_page(paddr: Paddr, level: PagingLevel, prop: PageProperty) -> (res: Self)
1416        requires
1417            paddr < MAX_PADDR,
1418            Self::new_page_req(paddr, level, prop),
1419        ensures
1420            res.paddr() == paddr & !((PAGE_SIZE - 1) as usize),
1421            paddr % PAGE_SIZE == 0 ==> res.paddr() == paddr,
1422            valid_frame_paddr(res.paddr()),
1423            res.is_present(),
1424            res.is_last(level),
1425            res.prop() == prop,
1426        returns
1427            Self::new_page(paddr, level, prop),
1428    ;
1429
1430    spec fn new_pt_spec(paddr: Paddr) -> Self;
1431
1432    /// Create a new PTE that map to a child page table.
1433    #[verifier::when_used_as_spec(new_pt_spec)]
1434    fn new_pt(paddr: Paddr) -> (res: Self)
1435        requires
1436            paddr < MAX_PADDR,
1437        ensures
1438            res.paddr() == paddr & !((PAGE_SIZE - 1) as usize),
1439            paddr % PAGE_SIZE == 0 ==> res.paddr() == paddr,
1440            valid_frame_paddr(res.paddr()),
1441            res.is_present(),
1442            forall|level: PagingLevel| level > 1 ==> !res.is_last(level),
1443        returns
1444            Self::new_pt(paddr),
1445    ;
1446
1447    /// Returns the physical address from the PTE.
1448    ///
1449    /// The physical address recorded in the PTE is either:
1450    /// - the physical address of the next-level page table, or
1451    /// - the physical address of the page that the PTE maps to.
1452    spec fn paddr_spec(&self) -> Paddr;
1453
1454    #[verifier::when_used_as_spec(paddr_spec)]
1455    fn paddr(&self) -> (res: Paddr)
1456        ensures
1457            res % PAGE_SIZE == 0,
1458        returns
1459            self.paddr(),
1460    ;
1461
1462    spec fn prop_spec(&self) -> PageProperty;
1463
1464    #[verifier::when_used_as_spec(prop_spec)]
1465    fn prop(&self) -> PageProperty
1466        returns
1467            self.prop(),
1468    ;
1469
1470    /// The preconditions for setting the page property of a PTE.
1471    spec fn set_prop_req(self, prop: PageProperty) -> bool;
1472
1473    fn set_prop(&mut self, prop: PageProperty)
1474        requires
1475            old(self).set_prop_req(prop),
1476        ensures
1477            !old(self).is_present() ==> *old(self) == *final(self),
1478            old(self).is_present() ==> {
1479                &&& final(self).prop() == prop
1480                &&& final(self).paddr() == old(self).paddr()
1481                &&& final(self).is_present()
1482                &&& forall|level: PagingLevel|
1483                    #![trigger old(self).is_last(level)]
1484                    old(self).is_last(level) ==> final(self).is_last(level)
1485            },
1486    ;
1487
1488    spec fn is_last_spec(&self, level: PagingLevel) -> bool;
1489
1490    /// Returns if the PTE maps a page rather than a child page table.
1491    ///
1492    /// The method needs to know the level of the page table where the PTE resides,
1493    /// since architectures like x86-64 have a huge bit only in intermediate levels.
1494    #[verifier::when_used_as_spec(is_last_spec)]
1495    fn is_last(&self, level: PagingLevel) -> bool
1496        returns
1497            self.is_last_spec(level),
1498    ;
1499
1500    spec fn as_usize_spec(self) -> usize;
1501
1502    /// Converts the PTE into a raw `usize` value.
1503    #[verifier::external_body]
1504    #[verifier::when_used_as_spec(as_usize_spec)]
1505    fn as_usize(self) -> usize
1506        returns
1507            self.as_usize(),
1508    {
1509        unimplemented!()
1510        // const { assert!(size_of::<Self>() == size_of::<usize>()) };
1511        // SAFETY: `Self` is `Pod` and has the same memory representation as `usize`.
1512        // unsafe { transmute_unchecked(self) }
1513
1514    }
1515
1516    /// Converts the raw `usize` value into a PTE.
1517    #[verifier::external_body]
1518    fn from_usize(pte_raw: usize) -> Self {
1519        unimplemented!()
1520        // const { assert!(size_of::<Self>() == size_of::<usize>()) };
1521        // SAFETY: `Self` is `Pod` and has the same memory representation as `usize`.
1522        // unsafe { transmute_unchecked(pte_raw) }
1523
1524    }
1525
1526    /// Absent (zero) PTE has well-formed paddr for match_pte.
1527    proof fn lemma_page_table_entry_properties()
1528        ensures
1529            core::mem::size_of::<Self>() == core::mem::size_of::<usize>(),
1530            core::mem::size_of::<Self>() % core::mem::align_of::<Self>() == 0,
1531            core::mem::align_of::<Self>() > 0,
1532            valid_frame_paddr(Self::new_absent().paddr()),
1533            !Self::new_absent().is_present(),
1534            forall|level: PagingLevel|
1535                #![trigger Self::new_absent().is_last(level)]
1536                1 < level ==> !Self::new_absent().is_last(level),
1537            forall|paddr: Paddr, level: PagingLevel, prop: PageProperty|
1538                #![trigger Self::new_page(paddr, level, prop)]
1539                Self::new_page_req(paddr, level, prop) && (prop.cache is Writeback
1540                    || prop.cache is Writethrough || prop.cache is Uncacheable) ==> {
1541                    &&& Self::new_page(paddr, level, prop).is_present()
1542                    &&& (paddr < MAX_PADDR ==> Self::new_page(paddr, level, prop).paddr() == paddr
1543                        & !((PAGE_SIZE - 1) as usize))
1544                    &&& (paddr < MAX_PADDR && paddr % PAGE_SIZE == 0 ==> Self::new_page(
1545                        paddr,
1546                        level,
1547                        prop,
1548                    ).paddr() == paddr)
1549                    &&& Self::new_page(paddr, level, prop).prop() == prop
1550                    &&& Self::new_page(paddr, level, prop).is_last(level)
1551                },
1552            forall|paddr: Paddr|
1553                #![trigger Self::new_pt(paddr)]
1554                {
1555                    &&& Self::new_pt(paddr).is_present()
1556                    &&& (paddr < MAX_PADDR ==> Self::new_pt(paddr).paddr() == paddr & !((PAGE_SIZE
1557                        - 1) as usize))
1558                    &&& (paddr < MAX_PADDR && paddr % PAGE_SIZE == 0 ==> Self::new_pt(paddr).paddr()
1559                        == paddr)
1560                    &&& forall|level: PagingLevel| level > 1 ==> !Self::new_pt(paddr).is_last(level)
1561                },
1562    ;
1563
1564    proof fn lemma_paddr_is_page_aligned(self)
1565        ensures
1566            self.paddr() % PAGE_SIZE == 0,
1567    ;
1568}
1569
1570/// Loads a page table entry with an atomic instruction.
1571///
1572/// # Verification Design
1573/// ## Preconditions
1574/// - The pointer must be a valid pointer to the array that represents the page table node.
1575/// - The array must be initialized at the target index.
1576/// ## Postconditions
1577/// - The value is loaded from the array at the given index.
1578/// ## Safety
1579/// - We require the caller to provide a permission token to ensure that this function is only called on a valid array
1580/// and the pointer is in bounds.
1581/// - Like an `AtomicUsize::load` in normal Rust, this function assumes that the value being loaded is an integer
1582/// (and therefore can be safely cloned). We model the PTE as an abstract type, but in all actual implementations it is an
1583/// integer. Importantly, it does not include any data that is unsafe to duplicate.
1584#[verifier::external_body]
1585#[verus_spec(
1586    with Tracked(perm): Tracked<&vstd_extra::array_ptr::PointsTo<E, NR_ENTRIES>>
1587    requires
1588        perm.is_init(ptr.index as int),
1589        perm.addr() == ptr.addr(),
1590        0 <= ptr.index < NR_ENTRIES,
1591    returns
1592        perm.value()[ptr.index as int],
1593)]
1594pub unsafe fn load_pte<E: PageTableEntryTrait>(
1595    ptr: vstd_extra::array_ptr::ArrayPtr<E, NR_ENTRIES>,
1596    ordering: Ordering,
1597) -> (pte: E) {
1598    unimplemented!()
1599}
1600
1601/// Stores a page table entry with an atomic instruction.
1602///
1603/// # Verification Design
1604/// We axiomatize this function as a store operation in the array that represents the page table node.
1605/// ## Preconditions
1606/// - The pointer must be a valid pointer to the array that represents the page table node.
1607/// - The array must be initialized so that the verifier knows that it remains initialized after the store.
1608/// ## Postconditions
1609/// - The new value is stored in the array at the given index.
1610/// ## Safety
1611/// - We require the caller to provide a permission token to ensure that this function is only called on a valid array
1612/// and the pointer is in bounds.
1613#[verifier::external_body]
1614#[verus_spec(
1615    with Tracked(perm): Tracked<&mut vstd_extra::array_ptr::PointsTo<E, NR_ENTRIES>>
1616    requires
1617        old(perm).addr() == ptr.addr(),
1618        0 <= ptr.index < NR_ENTRIES,
1619        old(perm).is_init_all(),
1620    ensures
1621        final(perm).wf(),
1622        final(perm).value()[ptr.index as int] == new_val,
1623        final(perm).value() == old(perm).value().update(ptr.index as int, new_val),
1624        final(perm).addr() == old(perm).addr(),
1625        final(perm).is_init_all(),
1626)]
1627pub unsafe fn store_pte<E: PageTableEntryTrait>(
1628    ptr: vstd_extra::array_ptr::ArrayPtr<E, NR_ENTRIES>,
1629    new_val: E,
1630    ordering: Ordering,
1631);
1632
1633} // verus!