Skip to main content

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

1use vstd::prelude::*;
2
3use vstd::set_lib::*;
4
5use vstd_extra::ownership::*;
6use vstd_extra::prelude::TreePath;
7
8use crate::mm::page_prop::PageProperty;
9use crate::mm::page_table::*;
10use crate::mm::{Paddr, PagingConstsTrait, PagingLevel, Vaddr};
11use crate::specs::arch::mm::{NR_ENTRIES, NR_LEVELS, PAGE_SIZE};
12use crate::specs::arch::paging_consts::PagingConsts;
13use crate::specs::mm::page_table::cursor::owners::*;
14use crate::specs::mm::page_table::*;
15use vstd_extra::arithmetic::*;
16
17use core::ops::Range;
18
19verus! {
20
21impl<C: PageTableConfig> PageTableOwner<C> {
22    pub uninterp spec fn new_cursor_owner_spec<'rcu>(self) -> (Self, CursorOwner<'rcu, C>);
23}
24
25/// A `CursorView` is not aware that the underlying structure of the page table is a tree.
26/// It treats the page table as an array of mappings of various sizes, and the cursor itself as the
27/// current virtual address, moving from low to high addresses. These functions specify its behavior
28/// and provide a simple interface for reasoning about its behavior.
29impl<C: PageTableConfig> CursorView<C> {
30
31    pub open spec fn item_into_mapping(va: Vaddr, item: C::Item) -> Mapping {
32        let (paddr, level, prop) = C::item_into_raw_spec(item);
33        let size = page_size(level);
34        Mapping {
35            va_range: va as int..va as int + size as int,
36            pa_range: paddr..(paddr + size) as Paddr,
37            page_size: size,
38            property: prop,
39        }
40    }
41
42    /// This function checks if the current virtual address is mapped. It does not correspond
43    /// to a cursor method itself, but defines what it means for an entry to present:
44    /// there is a mapping whose virtual address range contains the current virtual address.
45    pub open spec fn present(self) -> bool {
46        self.mappings.filter(|m: Mapping| m.va_range.start <= self.cur_va < m.va_range.end).len() > 0
47    }
48
49    pub open spec fn query_mapping(self) -> Mapping
50        recommends
51            self.present(),
52    {
53        self.mappings.filter(|m: Mapping| m.va_range.start <= self.cur_va < m.va_range.end).choose()
54    }
55
56    pub open spec fn query(self, paddr: Paddr, size: usize, prop: PageProperty) -> bool {
57        let m = self.query_mapping();
58        m.pa_range.start == paddr && m.page_size == size && m.property == prop
59    }
60
61    pub open spec fn query_range(self) -> Range<int> {
62        self.query_mapping().va_range
63    }
64
65    /// The VA range of the current slot when mapping a page of the given size.
66    /// Works for both present and absent mappings: when present, equals query_range() for
67    /// a mapping of that size; when absent, returns the aligned range that would be mapped.
68    pub open spec fn cur_slot_range(self, size: usize) -> Range<int> {
69        let start = nat_align_down(self.cur_va as nat, size as nat) as int;
70        start..start + size as int
71    }
72
73    /// This predicate specifies the behavior of the `query` method. It states that the current item
74    /// in the page table matches the given item, mapped at the resulting virtual address range.
75    pub open spec fn query_item_spec(self, item: C::Item) -> Option<Range<Vaddr>>
76        recommends
77            self.present(),
78    {
79        let (paddr, level, prop) = C::item_into_raw_spec(item);
80        let size = page_size(level);
81        if self.query(paddr, size, prop) {
82            let r = self.query_range();
83            Some(r.start as Vaddr..r.end as Vaddr)
84        } else {
85            None
86        }
87    }
88
89    /// The specification for the internal function, `find_next_impl`. It finds the next mapped virtual address
90    /// that is at most `len` bytes away from the current virtual address. TODO: add the specifications for
91    /// `find_unmap_subtree` and `split_huge`, which are used by other functions that call this one.
92    /// This returns a mapping rather than the address because that is useful when it's called as a subroutine.
93    pub open spec fn find_next_impl_spec(self, len: usize, find_unmap_subtree: bool, split_huge: bool) -> (Self, Option<Mapping>) {
94        let mappings_in_range = self.mappings.filter(|m: Mapping| self.cur_va as int <= m.va_range.start < self.cur_va as int + len as int);
95
96        if mappings_in_range.len() > 0 {
97            let mapping = mappings_in_range.find_unique_minimal(|m: Mapping, n: Mapping| m.va_range.start < n.va_range.start);
98            let view = CursorView {
99                cur_va: mapping.va_range.end as Vaddr,
100                ..self
101            };
102            (view, Some(mapping))
103        } else {
104            let view = CursorView {
105                cur_va: (self.cur_va + len) as Vaddr,
106                ..self
107            };
108            (view, None)
109        }
110    }
111
112    /// Actual specification for `find_next`. The cursor finds the next mapped virtual address
113    /// that is at most `len` bytes away from the current virtual address, returns it, and then
114    /// moves the cursor forward to the next end of its range.
115    pub open spec fn find_next_spec(self, len: usize) -> (Self, Option<Vaddr>) {
116        let (cursor, mapping) = self.find_next_impl_spec(len, false, false);
117        if mapping is Some {
118            (cursor, Some(mapping.unwrap().va_range.start as Vaddr))
119        } else {
120            (cursor, None)
121        }
122    }
123
124    /// Jump just sets the current virtual address to the given address.
125    pub open spec fn jump_spec(self, va: usize) -> Self {
126        CursorView {
127            cur_va: va as Vaddr,
128            ..self
129        }
130    }
131
132    pub open spec fn align_up_spec(self, size: usize) -> Vaddr {
133        nat_align_up(self.cur_va as nat, size as nat) as Vaddr
134    }
135
136    pub open spec fn split_index(m: Mapping, new_size: usize, n: usize) -> Mapping {
137        Mapping {
138            va_range: m.va_range.start + n as int * new_size as int
139                ..m.va_range.start + (n + 1) as int * new_size as int,
140            pa_range: (m.pa_range.start + n * new_size) as usize..(m.pa_range.start + (n + 1) * new_size) as usize,
141            page_size: new_size,
142            property: m.property,
143        }
144    }
145
146    pub open spec fn split_if_mapped_huge_spec(self, new_size: usize) -> Self {
147        let m = self.query_mapping();
148        let size = m.page_size;
149        let new_mappings = Set::<int>::new(|n:int| 0 <= n < size / new_size).map(|n:int| Self::split_index(m, new_size, n as usize));
150        CursorView {
151            cur_va: self.cur_va,
152            mappings: self.mappings - set![m] + new_mappings,
153            ..self
154        }
155    }
156
157    pub open spec fn split_while_huge(self, size: usize) -> Self
158        decreases self.query_mapping().page_size when self.inv()
159    {
160        if self.present() {
161            let m = self.query_mapping();
162            if m.page_size > size {
163                let new_size = m.page_size / NR_ENTRIES;
164                let new_self = self.split_if_mapped_huge_spec(new_size);
165                proof {
166                    let f = self.mappings.filter(|m2: Mapping| m2.va_range.start <= self.cur_va < m2.va_range.end);
167                    vstd::set::axiom_set_intersect_finite::<Mapping>(
168                        self.mappings, Set::new(|m2: Mapping| m2.va_range.start <= self.cur_va < m2.va_range.end));
169                    vstd::set::axiom_set_choose_len(f);
170                    assert(self.mappings.contains(m));
171                    assert(m.inv());
172                    assert(NR_ENTRIES == 512);
173                    assert(m.page_size % (m.page_size / 512usize) == 0) by {
174                        if m.page_size == 4096 { assert(4096usize % (4096usize / 512usize) == 0); }
175                        else if m.page_size == 2097152 { assert(2097152usize % (2097152usize / 512usize) == 0); }
176                        else { assert(1073741824usize % (1073741824usize / 512usize) == 0); }
177                    };
178                    Self::split_if_mapped_huge_spec_preserves_present(self, new_size);
179                    Self::split_if_mapped_huge_spec_decreases_page_size(self, new_size);
180                }
181                new_self.split_while_huge(size)
182            } else {
183                self
184            }
185        } else {
186            self
187        }
188    }
189
190    pub open spec fn remove_subtree(self, size: usize) -> Set<Mapping> {
191        let start = nat_align_down(self.cur_va as nat, size as nat) as Vaddr;
192        let subtree = self.mappings.filter(|m: Mapping|
193            start <= m.va_range.start < start + size);
194        self.mappings - subtree
195    }
196
197    /// Inserts a mapping into the cursor. If there were previously mappings there,
198    /// they are removed. Note that multiple mappings might be removed if they overlap with
199    /// a new large mapping.
200    pub open spec fn map_spec(self, paddr: Paddr, size: usize, prop: PageProperty) -> Self {
201        let new = Mapping {
202            va_range: self.cur_slot_range(size),
203            pa_range: paddr..(paddr + size) as usize,
204            page_size: size,
205            property: prop,
206        };
207        let split_self = self.split_while_huge(size);
208        CursorView {
209            cur_va: split_self.align_up_spec(size),
210            mappings: split_self.remove_subtree(size) + set![new],
211            ..split_self
212        }
213    }
214
215    pub open spec fn map_simple(self, paddr: Paddr, size: usize, prop: PageProperty) -> Self {
216        let new = Mapping {
217            va_range: self.cur_slot_range(size),
218            pa_range: paddr..(paddr + size) as usize,
219            page_size: size,
220            property: prop,
221        };
222        CursorView {
223            cur_va: self.cur_va,
224            mappings: self.mappings + set![new],
225            ..self
226        }
227    }
228
229    /// Unmaps a range of virtual addresses from the current address up to `len` bytes.
230    /// It returns the number of mappings that were removed.
231    ///
232    /// Because the implementation may split huge pages that straddle the range
233    /// boundaries, the spec first applies `split_while_huge` at both `cur_va`
234    /// and `cur_va + len` to obtain a "base" set of mappings where all boundary
235    /// entries are at the finest granularity.  Mappings whose `va_range.start`
236    /// falls in `[cur_va, cur_va + len)` are then removed from this base.
237    pub open spec fn unmap_spec(self, len: usize, new_view: Self, num_unmapped: usize) -> bool {
238        let start = self.cur_va;
239        let end = (self.cur_va + len) as Vaddr;
240        // Cursor advanced past the range.
241        &&& new_view.cur_va >= end
242        // Mappings fully outside [start, end) are preserved.
243        // (A mapping that straddles a boundary may be split, but its sub-mappings
244        // outside the range are present — see refinement clause.)
245        &&& forall |m: Mapping| #[trigger] self.mappings.contains(m)
246            && (m.va_range.end <= start || m.va_range.start >= end)
247            ==> new_view.mappings.contains(m)
248        // No mapping in the new view starts inside [start, end), UNLESS it is
249        // a sub-mapping of an old entry that straddled the start boundary.
250        // (When a huge page straddles `start`, splitting it produces sub-mappings
251        // whose `start` may fall inside [start, end) but before the cursor.)
252        &&& forall |m: Mapping| new_view.mappings.contains(m)
253            && start <= m.va_range.start < end
254            ==> exists |parent: Mapping| #[trigger] self.mappings.contains(parent)
255                && parent.va_range.start < start
256                && parent.va_range.start <= m.va_range.start
257                && m.va_range.end <= parent.va_range.end
258                && m.pa_range.start == (parent.pa_range.start + (m.va_range.start - parent.va_range.start)) as Paddr
259                && m.property == parent.property
260        // New mappings are either from the old view or are sub-mappings of
261        // old entries that straddled a boundary (refinement).
262        &&& forall |m: Mapping| #[trigger] new_view.mappings.contains(m)
263            ==> self.mappings.contains(m)
264            || exists |parent: Mapping| #[trigger] self.mappings.contains(parent)
265                && parent.va_range.start <= m.va_range.start
266                && m.va_range.end <= parent.va_range.end
267                && m.pa_range.start == (parent.pa_range.start + (m.va_range.start - parent.va_range.start)) as Paddr
268                && m.property == parent.property
269    }
270
271    /// Models `protect_next`: find the next mapping in range, split it to
272    /// `target_page_size` if it is a huge page, then update its property via `op`.
273    ///
274    /// `target_page_size` corresponds to the cursor level after `find_next_impl`
275    /// with `split_huge = true` — this is determined by the page table structure
276    /// and cannot be derived from the abstract view alone.
277    pub open spec fn protect_spec(self, len: usize, op: spec_fn(PageProperty) -> PageProperty, target_page_size: usize) -> (Self, Option<Range<Vaddr>>) {
278        let (find_cursor, next) = self.find_next_impl_spec(len, false, true);
279        if next is Some {
280            let found = next.unwrap();
281            // Position cursor at the found mapping and split to target size
282            let at_found = CursorView {
283                cur_va: found.va_range.start as Vaddr,
284                ..self
285            };
286            let split_view = at_found.split_while_huge(target_page_size);
287            // The mapping at cur_va in the split view is the one to protect
288            let split_mapping = split_view.query_mapping();
289            let new_mapping = Mapping {
290                property: op(split_mapping.property),
291                ..split_mapping
292            };
293            let new_cursor = CursorView {
294                cur_va: split_mapping.va_range.end as Vaddr,
295                mappings: split_view.mappings - set![split_mapping] + set![new_mapping],
296                ..self
297            };
298            (new_cursor, Some(split_mapping.va_range.start as Vaddr..split_mapping.va_range.end as Vaddr))
299        } else {
300            (find_cursor, None)
301        }
302    }
303}
304
305} // verus!