ostd/specs/mm/frame/segment.rs
1// SPDX-License-Identifier: MPL-2.0
2//! Spec/proof companion for [`crate::mm::frame::segment`].
3use core::ops::Range;
4
5use vstd::prelude::*;
6
7use vstd_extra::{drop_tracking::*, ownership::*};
8
9use crate::specs::{
10 arch::PAGE_SIZE,
11 mm::{
12 frame::{
13 mapping::{frame_to_index, index_to_meta},
14 meta_region_owners::MetaRegionOwners,
15 },
16 virt_mem::MemView,
17 },
18};
19
20use crate::mm::{
21 Paddr, Vaddr,
22 frame::{AnyFrameMeta, Segment},
23 paddr_to_vaddr,
24};
25
26verus! {
27
28impl<M: AnyFrameMeta + ?Sized> TrackDrop for Segment<M> {
29 /// The tracked state for `ManuallyDrop` purposes is the global
30 /// [`MetaRegionOwners`]. The real per-segment obligation is represented
31 /// by one entry per frame in `MetaRegionOwners::frame_obligations`, not
32 /// by this `TrackDrop` impl. That keeps
33 /// `ManuallyDrop::new(self)` callable in places like
34 /// `Segment::split` / `Segment::into_raw` where the segment is
35 /// "temporarily forgotten" without an actual ledger event.
36 type State = MetaRegionOwners;
37
38 /// Real segment-range key. The token produced by `constructor_spec`
39 /// carries `self.range` as identity. The mint here does NOT insert
40 /// into `obligations` — the real per-segment entry is added by
41 /// [`Segment::from_unused`] and removed by [`Segment::drop`] directly.
42 /// Carrying `Range<Paddr>` on the token still strengthens the
43 /// discipline: a token forged for one segment can't masquerade as
44 /// belonging to another (the `consume_requires`/`drop_requires`
45 /// checks would refuse the mismatched key).
46 type Obligation = DropObligation<Range<Paddr>>;
47
48 open spec fn tracked_redeem_requires(self, s: Self::State) -> bool {
49 true
50 }
51
52 open spec fn tracked_redeem_ensures(
53 self,
54 s0: Self::State,
55 s1: Self::State,
56 obl: Self::Obligation,
57 ) -> bool {
58 &&& s0 =~= s1
59 &&& obl.value() == self.range
60 }
61
62 proof fn tracked_redeem(self, tracked s: &mut Self::State) -> (tracked obl: Self::Obligation) {
63 DropObligation::tracked_mint(self.range)
64 }
65
66 open spec fn drop_requires(self, s: Self::State, obl: Self::Obligation) -> bool {
67 &&& s.inv()
68 &&& obl.value() == self.range
69 }
70
71 open spec fn drop_ensures(
72 self,
73 s0: Self::State,
74 s1: Self::State,
75 obl: Self::Obligation,
76 ) -> bool {
77 true
78 }
79}
80
81/// Number of frames in a page-aligned physical range.
82#[verifier::inline]
83pub open spec fn seg_nframes(range: Range<Paddr>) -> int {
84 (range.end - range.start) / PAGE_SIZE as int
85}
86
87impl<M: AnyFrameMeta + ?Sized> Segment<M> {
88 /// The cross-object relation between a [`Segment`] and the global
89 /// [`MetaRegionOwners`].
90 ///
91 /// For every frame `i` in the segment, this asserts:
92 /// - the slot owner and canonical slot permission are present in `regions`,
93 /// - the slot's `slot_vaddr` is consistent with its index,
94 /// - the slot has a live, non-`UNUSED` reference count,
95 /// - the slot has a pending `frame_obligations` entry for this segment,
96 /// - the slot is a data-frame slot with no page-table paths,
97 /// - distinct frames in the segment map to distinct slot indices.
98 pub open spec fn relate_regions(&self, regions: MetaRegionOwners) -> bool {
99 &&& forall|i: int|
100 #![trigger frame_to_index((self.range.start + i * PAGE_SIZE) as usize)]
101 0 <= i < seg_nframes(self.range) ==> {
102 let idx = frame_to_index((self.range.start + i * PAGE_SIZE) as usize);
103 // Per-frame linear-drop: the segment holds one (forgotten)
104 // reference per frame, recorded as a `frame_obligations` count.
105 &&& regions.frame_obligations.count(idx) >= 1
106 &&& regions.contains(idx)
107 &&& regions.slot_owners[idx].slot_vaddr == index_to_meta(idx)
108 &&& 0 < regions.slot_owners[idx].ref_count()
109 <= crate::mm::frame::meta::REF_COUNT_MAX
110 &&& regions.slot_owners[idx].paths_in_pt.is_empty()
111 &&& regions.slot_owners[idx].usage is Frame
112 }
113 &&& forall|i: int, j: int|
114 #![trigger frame_to_index((self.range.start + i * PAGE_SIZE) as usize),
115 frame_to_index((self.range.start + j * PAGE_SIZE) as usize)]
116 0 <= i < j < seg_nframes(self.range) ==> frame_to_index(
117 (self.range.start + i * PAGE_SIZE) as usize,
118 ) != frame_to_index((self.range.start + j * PAGE_SIZE) as usize)
119 }
120
121 /// Manually instantiates the [`relate_regions`] forall at a specific index.
122 /// Use this to extract per-frame facts without fighting trigger inference.
123 pub proof fn relate_regions_at(&self, regions: MetaRegionOwners, i: int)
124 requires
125 self.relate_regions(regions),
126 0 <= i < seg_nframes(self.range),
127 ensures
128 ({
129 let idx = frame_to_index((self.range.start + i * PAGE_SIZE) as usize);
130 &&& regions.frame_obligations.count(idx) >= 1
131 &&& regions.contains(
132 idx,
133 )
134 // Borrow-protocol transition: `raw_count` is dormant.
135 &&& regions.slot_owners[idx].slot_vaddr == index_to_meta(idx)
136 &&& regions.slot_owners[idx].ref_count() > 0
137 &&& regions.slot_owners[idx].ref_count() <= crate::mm::frame::meta::REF_COUNT_MAX
138 &&& regions.slot_owners[idx].paths_in_pt.is_empty()
139 &&& regions.slot_owners[idx].usage is Frame
140 }),
141 {
142 // Trigger the forall at index `i`.
143 let _ = frame_to_index((self.range.start + i * PAGE_SIZE) as usize);
144 }
145
146 /// Manually instantiates the [`relate_regions`] distinctness forall at a
147 /// specific index pair: distinct in-range frames map to distinct slot
148 /// indices. Reusable lever for `from_unused`/`split`/`slice` proofs.
149 pub proof fn relate_regions_distinct(&self, regions: MetaRegionOwners, i: int, j: int)
150 requires
151 self.relate_regions(regions),
152 0 <= i < j < seg_nframes(self.range),
153 ensures
154 frame_to_index((self.range.start + i * PAGE_SIZE) as usize) != frame_to_index(
155 (self.range.start + j * PAGE_SIZE) as usize,
156 ),
157 {
158 // Trigger the distinctness forall at `(i, j)`.
159 let _ = frame_to_index((self.range.start + i * PAGE_SIZE) as usize);
160 let _ = frame_to_index((self.range.start + j * PAGE_SIZE) as usize);
161 }
162
163 /// The bundled invariant for [`Segment`] operations that thread the global
164 /// `regions`: the segment's own invariant, the region invariant, and the
165 /// cross-object relation tying this segment's range to `regions`.
166 ///
167 /// Mirrors the `invariants` bundles used throughout the page-table / cursor
168 /// code — it collapses the clauses repeated across `split`, `slice`,
169 /// `into_raw`, `next`, and `drop` into one predicate.
170 pub open spec fn invariants(&self, regions: MetaRegionOwners) -> bool {
171 &&& self.inv()
172 &&& regions.inv()
173 &&& self.relate_regions(regions)
174 }
175
176 /// Whether a [`MemView`] covers the segment through the kernel direct mapping.
177 ///
178 /// This predicate only describes the virtual-to-physical relation and the
179 /// presence of initialized backing frame contents.
180 pub open spec fn kernel_mem_view_covers(&self, view: &MemView) -> bool {
181 &&& self.inv()
182 &&& view.mappings_are_disjoint()
183 &&& forall|vaddr: Vaddr|
184 #![trigger view.addr_transl(vaddr)]
185 paddr_to_vaddr(self.start_paddr()) <= vaddr < paddr_to_vaddr(self.start_paddr())
186 + self.end_paddr() - self.start_paddr() ==> {
187 &&& view.addr_transl(vaddr) is Some
188 &&& view.memory.contains_key((view.addr_transl(vaddr)->0).0)
189 &&& view.memory[(view.addr_transl(vaddr)->0).0].inv()
190 &&& view.memory[(view.addr_transl(vaddr)->0).0].contents[(view.addr_transl(
191 vaddr,
192 )->0).1 as int] is Init
193 }
194 &&& forall|paddr: Paddr|
195 #![trigger paddr_to_vaddr(paddr)]
196 self.start_paddr() <= paddr < self.end_paddr() ==> {
197 let vaddr = paddr_to_vaddr(paddr);
198 &&& view.addr_transl(vaddr) is Some
199 &&& (view.addr_transl(vaddr)->0).0 <= paddr
200 &&& paddr < (view.addr_transl(vaddr)->0).0 + view.memory[(view.addr_transl(
201 vaddr,
202 )->0).0].size@
203 &&& (view.addr_transl(vaddr)->0).1 == paddr - (view.addr_transl(vaddr)->0).0
204 &&& view.memory.contains_key((view.addr_transl(vaddr)->0).0)
205 &&& view.memory[(view.addr_transl(vaddr)->0).0].inv()
206 &&& view.memory[(view.addr_transl(vaddr)->0).0].contents[(view.addr_transl(
207 vaddr,
208 )->0).1 as int] is Init
209 }
210 }
211}
212
213/// Helper spec: the slot index of the j-th frame in a segment whose physical
214/// range starts at `range_start`. Unlike a let-bound ghost closure (which Verus
215/// treats opaquely under SMT), a `spec fn` is auto-unfolded so equalities
216/// between `frame_idx_at(...)` and `frame_to_index(...)` are derivable.
217#[verifier::inline]
218pub open spec fn frame_idx_at(range_start: usize, j: int) -> int {
219 frame_to_index((range_start + j * PAGE_SIZE) as usize)
220}
221
222/// The exact `frame_obligations` effect of recording one forgotten reference
223/// per frame for the first `n` frames of a segment starting at `range_start`:
224///
225/// - every segment frame's count grows by at least one (its recorded
226/// reference), and
227/// - the *frame condition*: every slot that is NOT a segment frame is left
228/// untouched.
229///
230/// The frame condition is the load-bearing part — it pins the *support* of the
231/// change to the segment's slots, so a caller's ledger accounting telescopes
232/// (it can conclude this only touched the segment's slots). Shared by
233/// [`tracked_mint_seg_obligations`] (which establishes it) and
234/// [`Segment::from_unused`] (which advertises it).
235pub open spec fn seg_obligations_minted(
236 pre: MetaRegionOwners,
237 post: MetaRegionOwners,
238 range_start: usize,
239 n: int,
240) -> bool {
241 // Each segment frame gains at least one entry.
242 &&& forall|i: int|
243 #![trigger frame_to_index((range_start + i * PAGE_SIZE) as usize)]
244 0 <= i < n ==> post.frame_obligations.count(
245 frame_to_index((range_start + i * PAGE_SIZE) as usize),
246 ) >= pre.frame_obligations.count(frame_to_index((range_start + i * PAGE_SIZE) as usize))
247 + 1
248 // Frame condition: every slot that is NOT a segment frame is untouched.
249 &&& forall|jdx: int|
250 #![trigger post.frame_obligations.count(jdx)]
251 (forall|i: int|
252 #![trigger frame_to_index((range_start + i * PAGE_SIZE) as usize)]
253 0 <= i < n ==> jdx != frame_to_index((range_start + i * PAGE_SIZE) as usize))
254 ==> post.frame_obligations.count(jdx) == pre.frame_obligations.count(jdx)
255}
256
257/// Mints one per-frame `frame_obligations` entry for each of the first `n`
258/// frames of a segment starting at `range_start`. Used by
259/// [`Segment::from_unused`] to record the segment's forgotten per-frame
260/// references *after* the construction loop (which is net-zero on the ledger:
261/// each frame's `Frame::from_unused` mint is cancelled by its `ManuallyDrop`).
262///
263/// Per-frame obligations replace the old single range-keyed `obligations`
264/// ledger entry. Because `frame_obligations` is a multiset and minting only
265/// ever increases counts, no distinctness hypothesis on the frame indices is
266/// needed.
267///
268/// EXACT accounting (Tier A): the ensures pin the *support* of the change —
269/// every segment frame's count grows by at least one, and every *other* slot
270/// is untouched. This frame condition is what lets a caller's accounting
271/// telescope (it can conclude this call touched only the segment's slots).
272/// Each mint targets a segment index, so a non-segment slot is simply never a
273/// mint target — hence the frame condition needs no injectivity argument.
274pub proof fn tracked_mint_seg_obligations(
275 tracked regions: &mut MetaRegionOwners,
276 range_start: usize,
277 n: int,
278)
279 requires
280 0 <= n,
281 old(regions).inv(),
282 ensures
283 final(regions).inv(),
284 final(regions).slots == old(regions).slots,
285 final(regions).slot_owners == old(regions).slot_owners,
286 // Counts only grow.
287 forall|idx: int|
288 #![trigger final(regions).frame_obligations.count(idx)]
289 final(regions).frame_obligations.count(idx) >= old(regions).frame_obligations.count(
290 idx,
291 ),
292 // The exact per-frame mint effect (segment frames +≥1, all else fixed).
293 seg_obligations_minted(*old(regions), *final(regions), range_start, n),
294 decreases n,
295{
296 let ghost g0 = *regions;
297 if n > 0 {
298 tracked_mint_seg_obligations(regions, range_start, n - 1);
299 let ghost gmid = *regions;
300 let idx = frame_to_index((range_start + (n - 1) * PAGE_SIZE) as usize);
301 let tracked _ = regions.tracked_mint_frame_obligation(idx);
302 // `regions.frame_obligations == gmid.frame_obligations.insert(idx)`,
303 // and the recursion already proved the strengthened ensures for the
304 // first `n-1` frames against `g0`. Bridge each ensures to `n`.
305 // Frame condition: a non-segment slot is untouched by the recursion
306 // (it omits the slot from `[0, n-1)`) and is not the mint target.
307 assert forall|jdx: int|
308 #![trigger regions.frame_obligations.count(jdx)]
309 (forall|i: int|
310 #![trigger frame_to_index((range_start + i * PAGE_SIZE) as usize)]
311 0 <= i < n ==> jdx != frame_to_index(
312 (range_start + i * PAGE_SIZE) as usize,
313 )) implies regions.frame_obligations.count(jdx) == g0.frame_obligations.count(
314 jdx,
315 ) by {};
316 // Each segment frame gained at least one entry.
317 assert forall|i: int|
318 #![trigger frame_to_index((range_start + i * PAGE_SIZE) as usize)]
319 0 <= i < n implies regions.frame_obligations.count(
320 frame_to_index((range_start + i * PAGE_SIZE) as usize),
321 ) >= g0.frame_obligations.count(frame_to_index((range_start + i * PAGE_SIZE) as usize))
322 + 1 by {
323 // i < n-1: recursion gives `gmid.count(idx_i) >= g0.count(idx_i)+1`;
324 // the mint only grows counts. i == n-1: `gmid.count(idx) >= g0.count(idx)`
325 // (monotone), and the mint adds exactly one at `idx`.
326 };
327 }
328}
329
330/// Redeems the per-frame `frame_obligations` entry for each of the first `n`
331/// frames of a segment starting at `range_start` — the inverse of
332/// [`tracked_mint_seg_obligations`]. Used by [`Segment::drop`] to drain the
333/// segment's retained per-frame references *before* the per-frame teardown
334/// loop, so that loop sees `count == 0` (as it did before the migration) and
335/// its `from_raw`(+1)/`frame.drop`(-1) pair nets to zero unchanged.
336///
337/// Unlike minting, redeeming requires the frame indices be *distinct*
338/// (redeeming one frame must not drop another's count below 1) and each count
339/// be `>= 1` up front — both supplied by [`Segment::relate_regions`].
340/// Leaves `slots`, `slot_owners`, and the (vestigial) range `obligations`
341/// ledger untouched.
342pub proof fn tracked_redeem_seg_obligations(
343 tracked regions: &mut MetaRegionOwners,
344 range_start: usize,
345 n: int,
346)
347 requires
348 0 <= n,
349 old(regions).inv(),
350 forall|i: int|
351 #![trigger frame_to_index((range_start + i * PAGE_SIZE) as usize)]
352 0 <= i < n ==> old(regions).frame_obligations.count(
353 frame_to_index((range_start + i * PAGE_SIZE) as usize),
354 ) >= 1,
355 forall|i: int, j: int|
356 #![trigger frame_to_index((range_start + i * PAGE_SIZE) as usize),
357 frame_to_index((range_start + j * PAGE_SIZE) as usize)]
358 0 <= i < j < n ==> frame_to_index((range_start + i * PAGE_SIZE) as usize)
359 != frame_to_index((range_start + j * PAGE_SIZE) as usize),
360 ensures
361 final(regions).inv(),
362 final(regions).slots == old(regions).slots,
363 final(regions).slot_owners == old(regions).slot_owners,
364 decreases n,
365{
366 if n > 0 {
367 let idx = frame_to_index((range_start + (n - 1) * PAGE_SIZE) as usize);
368 let tracked tok = DropObligation::tracked_mint(idx);
369 regions.tracked_redeem_frame_obligation(tok);
370 // Redeeming `idx` (the n-1'th frame) left every earlier frame's count
371 // untouched, since the indices are distinct — so the `>= 1` hypothesis
372 // still holds for `[0, n-1)` and the recursive call's precondition is met.
373 assert forall|i: int|
374 #![trigger frame_to_index((range_start + i * PAGE_SIZE) as usize)]
375 0 <= i < n - 1 implies regions.frame_obligations.count(
376 frame_to_index((range_start + i * PAGE_SIZE) as usize),
377 ) >= 1 by {};
378 tracked_redeem_seg_obligations(regions, range_start, n - 1);
379 }
380}
381
382} // verus!