ostd/mm/frame/mod.rs
1// SPDX-License-Identifier: MPL-2.0
2//! Frame (physical memory page) management.
3//!
4//! A frame is an aligned, contiguous range of bytes in physical memory. The
5//! sizes of base frames and huge frames (that are mapped as "huge pages") are
6//! architecture-dependent. A frame can be mapped to virtual address spaces
7//! using the page table.
8//!
9//! Frames can be accessed through frame handles, namely, [`Frame`]. A frame
10//! handle is a reference-counted pointer to a frame. When all handles to a
11//! frame are dropped, the frame is released and can be reused. Contiguous
12//! frames are managed with [`Segment`].
13//!
14//! There are various kinds of frames. The top-level grouping of frame kinds
15//! are "typed" frames and "untyped" frames. Typed frames host Rust objects
16//! that must follow the visibility, lifetime and borrow rules of Rust, thus
17//! not being able to be directly manipulated. Untyped frames are raw memory
18//! that can be manipulated directly. So only untyped frames can be
19//! - safely shared to external entities such as device drivers or user-space
20//! applications.
21//! - or directly manipulated with readers and writers that neglect Rust's
22//! "alias XOR mutability" rule.
23//!
24//! The kind of a frame is determined by the type of its metadata. Untyped
25//! frames have its metadata type that implements the [`AnyUFrameMeta`]
26//! trait, while typed frames don't.
27//!
28//! Frames can have dedicated metadata, which is implemented in the [`meta`]
29//! module. The reference count and usage of a frame are stored in the metadata
30//! as well, leaving the handle only a pointer to the metadata slot. Users
31//! can create custom metadata types by implementing the [`AnyFrameMeta`] trait.
32use vstd::{
33 assert_maps_equal, assert_sets_equal, atomic::PermissionU64, map::assert_maps_equal_internal,
34 prelude::*, simple_pptr::PPtr, std_specs::cmp::PartialEqSpecImpl,
35};
36use vstd_extra::{
37 cast_ptr::*,
38 ownership::*,
39 panic::allowed_to_panic_if,
40 raw_ptr::{ExposedPointsTo, ptr_from_addr, ptr_ref},
41};
42
43pub mod allocator;
44pub mod linked_list;
45pub mod meta;
46pub mod segment;
47pub mod unique;
48pub mod untyped;
49
50mod frame_ref;
51pub use frame_ref::FrameRef;
52
53#[cfg(ktest)]
54mod test;
55
56use crate::specs::{
57 arch::*,
58 mm::frame::{frame_specs::*, mapping::*, meta_owners::*, meta_region_owners::MetaRegionOwners},
59};
60
61use crate::mm::{
62 MAX_PADDR,
63 frame::meta::{
64 META_SLOT_SIZE, REF_COUNT_MAX, REF_COUNT_UNIQUE,
65 mapping::{frame_to_meta, meta_to_frame},
66 },
67 kspace::{FRAME_METADATA_RANGE, LINEAR_MAPPING_BASE_VADDR, VMALLOC_BASE_VADDR},
68 page_table::{PageTableConfig, PageTablePageMeta, RCClone},
69};
70
71use core::{
72 marker::PhantomData,
73 mem::ManuallyDrop,
74 sync::atomic::{AtomicUsize, Ordering},
75};
76
77//pub use allocator::GlobalFrameAllocator;
78use meta::{AnyFrameMeta, GetFrameError, MetaSlot, REF_COUNT_UNUSED, mapping};
79pub use segment::Segment;
80use untyped::{AnyUFrameMeta, UFrame};
81
82use super::{PAGE_SIZE, PagingLevel};
83use crate::mm::{Paddr, PagingConsts, Vaddr};
84
85verus! {
86
87/*
88static MAX_PADDR: AtomicUsize = AtomicUsize::new(0);
89*/
90/// Returns the maximum physical address that is tracked by frame metadata.
91#[verifier::external_body]
92pub(in crate::mm) fn max_paddr() -> Paddr
93 returns
94 MAX_PADDR,
95{
96 // let max_paddr = MAX_PADDR.load(Ordering::Relaxed) as Paddr;
97 // debug_assert_ne!(max_paddr, 0);
98 // max_paddr
99 unimplemented!()
100}
101
102#[verifier::external_body]
103fn acquire_fence() {
104 core::sync::atomic::fence(Ordering::Acquire);
105}
106
107/// A smart pointer to a frame.
108///
109/// A frame is a contiguous range of bytes in physical memory. The [`Frame`]
110/// type is a smart pointer to a frame that is reference-counted.
111///
112/// Frames are associated with metadata. The type of the metadata `M` is
113/// determines the kind of the frame. If `M` implements [`AnyUFrameMeta`], the
114/// frame is a untyped frame. Otherwise, it is a typed frame.
115// #[repr(transparent)]
116pub struct Frame<M: ?Sized> {
117 pub ptr: *const MetaSlot,
118 pub _marker: PhantomData<M>,
119 /// The permission to access the `MetaSlot` fields.
120 #[cfg(verus_keep_ghost_body)]
121 pub tracked_slot_perm: Tracked<&'static ExposedPointsTo<MetaSlot>>,
122 /// One fractional permission for the currently installed metadata.
123 #[cfg(verus_keep_ghost_body)]
124 pub tracked_metadata_perm: Tracked<Option<FracMetadataPerm>>,
125}
126
127#[verifier::external]
128unsafe impl<M: AnyFrameMeta + ?Sized> Send for Frame<M> {
129
130}
131
132#[verifier::external]
133unsafe impl<M: AnyFrameMeta + ?Sized> Sync for Frame<M> {
134
135}
136
137/*
138impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + ?Sized> core::fmt::Debug for Frame<M> {
139 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
140 write!(f, "Frame({:#x})", self.start_paddr())
141 }
142}
143*/
144
145verus!{
146
147impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + ?Sized> PartialEqSpecImpl for Frame<M>{
148 open spec fn obeys_eq_spec() -> bool { true }
149
150 open spec fn eq_spec(&self, other: &Self) -> bool {
151 self.start_paddr_spec() == other.start_paddr_spec()
152 }
153}
154
155}
156
157#[verus_verify]
158impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + ?Sized> PartialEq for Frame<M> {
159 fn eq(&self, other: &Self) -> bool {
160 proof!{
161 //FIXME: Add `ptr_inv` as type invariant when we fix visibility.
162 assume(self.ptr_inv());
163 assume(other.ptr_inv());
164 }
165 self.start_paddr() == other.start_paddr()
166 }
167}
168
169#[verus_verify]
170impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + ?Sized> Eq for Frame<M> {
171
172}
173
174#[verus_verify]
175impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf> Frame<M> {
176 /// Gets a [`Frame`] with a specific usage from a raw, unused page.
177 ///
178 /// The caller should provide the initial metadata of the page.
179 ///
180 /// If the provided frame is not truly unused at the moment, it will return
181 /// an error. If wanting to acquire a frame that is already in use, use
182 /// [`Frame::from_in_use`] instead.
183 /// # Verified Properties
184 /// ## Preconditions
185 /// - **Safety Invariant**: Metaslot region invariants must hold.
186 /// ## Postconditions
187 /// - **Safety Invariant**: Metaslot region invariants hold after the call.
188 /// - **Correctness**: If successful, the function returns a pointer to the metadata slot and a permission to the slot.
189 /// - **Correctness**: If successful, the slot is initialized with the given metadata.
190 /// - **Correctness**: If `paddr` does not have a corresponding metadata slot, the function returns an error.
191 /// - **Drop Bookkeeping**: If successful, the function returns a live frame, which is tracked correctly as needing to be dropped.
192 /// ## Safety
193 /// - This function returns an error if `paddr` does not correspond to a valid slot or the slot is in use.
194 #[verus_spec(r =>
195 with
196 Tracked(regions): Tracked<&mut MetaRegionOwners>,
197 requires
198 old(regions).inv(),
199 ensures
200 final(regions).inv(),
201 r matches Ok(res) ==> {
202 &&& MetaSlot::get_from_unused_region_spec(
203 paddr, false, res.metadata_perm().usage(),
204 *old(regions), *final(regions))
205 &&& typed_meta_wf::<M>(res.slot_perm(), res.metadata_perm())
206 &&& M::from_repr_spec(res.metadata_perm().storage_perm.value()) == metadata
207 &&& res.inv()
208 &&& res.start_paddr_spec() == paddr
209 &&& res.wf_with_region(*final(regions))
210 },
211 r is Err ==> *final(regions) == *old(regions)
212 )]
213 pub fn from_unused(paddr: Paddr, metadata: M) -> Result<Self, GetFrameError> {
214 #[verus_spec(with
215 Tracked(regions) => Tracked(permissions)
216 )]
217 let from_unused = MetaSlot::get_from_unused(paddr, metadata, false);
218 if let Err(err) = from_unused {
219 Err(err)
220 } else {
221 proof_decl! {
222 lemma_paddr_to_meta_biinjective(paddr);
223 lemma_frame_to_meta_soundness(paddr);
224 let tracked slot_perm = regions.tracked_borrow_slot(paddr);
225 let ghost idx = frame_to_index(paddr);
226 assert(regions.slot_owners.contains_key(idx));
227 let tracked metadata_perm = permissions.tracked_unwrap().tracked_take_left();
228 }
229 let ptr = from_unused.unwrap();
230 Ok(
231 Self {
232 ptr,
233 _marker: PhantomData,
234 #[cfg(verus_keep_ghost_body)]
235 tracked_slot_perm: Tracked(slot_perm),
236 #[cfg(verus_keep_ghost_body)]
237 tracked_metadata_perm: Tracked(Some(metadata_perm)),
238 },
239 )
240 }
241 }
242
243 /// Gets the metadata of this page.
244 /// # Verified Properties
245 /// ## Preconditions
246 /// - The caller must have a valid permission for the frame.
247 /// ## Postconditions
248 /// - The function returns the borrowed metadata of the frame.
249 /// ## Safety
250 /// - By requiring the caller to provide a typed permission, we ensure that the metadata is of type `M`.
251 /// While a non-verified caller cannot be trusted to obey this interface, all functions that return a `Frame<M>` also
252 /// return an appropriate permission.
253 #[verus_spec(ret =>
254 with
255 Tracked(metadata_perm): Tracked<Option<&'a MetadataPerm>>,
256 requires
257 {
258 self.inv() && metadata_perm is None
259 && typed_meta_wf::<M>(self.slot_perm(), self.metadata_perm()) ||
260 metadata_perm is Some
261 && self.external_meta_wf(*metadata_perm->0)
262 },
263 ensures
264 {
265 let metadata_perm = if metadata_perm is Some {*metadata_perm -> 0} else
266 { self.metadata_perm() };
267 ret == typed_meta_value::<M>(metadata_perm)
268 },
269 )]
270 pub fn meta<'a>(&'a self) -> &'a M {
271 // SAFETY: The type is tracked by the typed storage permission.
272 // unsafe { &*self.slot().as_meta_ptr::<M>() }
273 proof_decl! {
274 let tracked slot_perm = self.tracked_slot_perm.borrow();
275 let tracked metadata_perm = if metadata_perm is Some {
276 metadata_perm.tracked_borrow()
277 } else {
278 self.tracked_metadata_perm.tracked_borrow().tracked_borrow()
279 };
280 }
281 borrow_meta(
282 ReprPtr::<MetaSlotStorage, M>::from_pptr(PPtr::from_addr(self.ptr.addr())),
283 Tracked(slot_perm),
284 Tracked(metadata_perm),
285 )
286 }
287}
288
289#[verus_verify]
290impl<M: AnyFrameMeta + Repr<MetaSlotStorage>> Frame<M> {
291 /// Gets a dynamically typed [`Frame`] from a raw, in-use page.
292 ///
293 /// If the provided frame is not in use at the moment, it will return an error.
294 ///
295 /// The returned frame will have an extra reference count to the frame.
296 ///
297 /// # Verified Properties
298 /// ## Preconditions
299 /// - **Safety Invariant**: Metaslot region invariants must hold.
300 /// - *Termination*: The function may panic if `paddr` is a valid slot and its reference count is saturated.
301 /// ## Postconditions
302 /// - **Safety Invariant**: Metaslot region invariants hold after the call.
303 /// - **Correctness**: If successful, the function returns the frame at `paddr`.
304 /// - **Correctness**: If successful, the frame has an extra reference count.
305 /// - **Correctness**: If `paddr` does not have a valid metadata slot, the function returns an error.
306 /// - **Safety**: Frames other than the one at `paddr` are not affected by the call.
307 /// ## Safety
308 /// - If `paddr` is a valid frame address, it is safe to take a reference to the frame.
309 /// - If `paddr` is not a valid frame address, the function will return an error.
310 #[verus_spec(res =>
311 with Tracked(regions) : Tracked<&mut MetaRegionOwners>,
312 requires
313 old(regions).inv(),
314 allowed_to_panic_if(valid_frame_paddr(paddr) && old(regions).ref_count(frame_to_index(paddr)) >= REF_COUNT_MAX),
315 ensures
316 final(regions).inv(),
317 res matches Ok(res) ==> {
318 &&& old(regions).inc_frame_reference_region_spec(paddr, *final(regions))
319 &&& res.inv()
320 &&& res.start_paddr_spec() == paddr
321 &&& res.wf_with_region(*final(regions))
322 },
323 res is Err ==> *old(regions) == *final(regions),
324 )]
325 #[verifier::spinoff_prover]
326 pub fn from_in_use(paddr: Paddr) -> Result<Self, GetFrameError> {
327 proof_decl!{
328 let tracked frame_permission: Option<FracMetadataPerm>;
329 }
330 let res = #[verus_spec(with Tracked(regions) => Tracked(frame_permission))]
331 MetaSlot::get_from_in_use(paddr);
332 match res {
333 Ok(ptr) => {
334 proof {
335 regions.lemma_contains_valid_frame_paddr(paddr);
336 }
337 let tracked slot_perm = regions.tracked_borrow_slot(paddr);
338 Ok(
339 Self {
340 ptr,
341 _marker: PhantomData,
342 #[cfg(verus_keep_ghost_body)]
343 tracked_slot_perm: Tracked(slot_perm),
344 #[cfg(verus_keep_ghost_body)]
345 tracked_metadata_perm: Tracked(frame_permission),
346 },
347 )
348 },
349 Err(e) => Err(e),
350 }
351 }
352}
353
354#[verus_verify]
355impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + ?Sized> Frame<M> {
356 /// Gets the physical address of the start of the frame.
357 /// # Verified Properties
358 /// ## Preconditions
359 /// - **Bookkeeping**: takes the permission for the frame's metadata slot.
360 /// ## Postconditions
361 /// - **Correctness**: returns the physical address of the frame.
362 /// ## Safety
363 /// The caller cannot obtain a frame that doesn't have a valid permission,
364 /// and this function does not mutate any state, so it is always sound to call.
365 #[verus_spec(
366 requires
367 self.ptr_inv(),
368 returns
369 self.start_paddr_spec(),
370 )]
371 pub fn start_paddr(&self) -> Paddr {
372 let slot = self.slot();
373
374 #[verus_spec(with self.tracked_slot_perm)]
375 slot.frame_paddr()
376 }
377
378 /// Gets the map level of this page.
379 ///
380 /// This is the level of the page table entry that maps the frame,
381 /// which determines the size of the frame.
382 ///
383 /// Currently, the level is always 1, which means the frame is a regular
384 /// page frame.
385 pub const fn map_level(&self) -> PagingLevel
386 returns
387 1u8,
388 {
389 1
390 }
391
392 /// Gets the size of this page in bytes.
393 pub const fn size(&self) -> usize
394 returns
395 PAGE_SIZE,
396 {
397 PAGE_SIZE
398 }
399
400 /* /// Gets the dynamically-typed metadata of this frame.
401 ///
402 /// If the type is known at compile time, use [`Frame::meta`] instead.
403 pub fn dyn_meta(&self) -> FrameMeta {
404 // SAFETY: The metadata is initialized and valid.
405 unsafe { &*self.slot().dyn_meta_ptr() }
406 }*/
407 /// Gets the reference count of the frame.
408 ///
409 /// It returns the number of all references to the frame, including all the
410 /// existing frame handles ([`Frame`], [`Frame<dyn AnyFrameMeta>`]), and all
411 /// the mappings in the page table that points to the frame.
412 ///
413 /// ## Safety
414 ///
415 /// The function is safe to call, but using it requires extra care. The
416 /// reference count can be changed by other threads at any time including
417 /// potentially between calling this method and acting on the result.
418 ///
419 /// # Verified Properties
420 /// ## Preconditions
421 /// - **Safety Invariant**: Metaslot region invariants must hold.
422 /// - **Bookkeeping**: The caller must have a valid and well-typed permission for the frame.
423 /// ## Postconditions
424 /// - **Correctness**: The function returns the reference count of the frame.
425 #[verus_spec(
426 with
427 Tracked(slot_own): Tracked<&MetaSlotOwner>,
428 requires
429 self.ptr_inv(),
430 self.tracked_slot_perm@.value().wf(*slot_own),
431 returns
432 slot_own.ref_count(),
433 )]
434 pub fn reference_count(&self) -> u64 {
435 let refcnt = self.slot().ref_count.load(Tracked(&slot_own.ref_count_perm));
436 refcnt
437 }
438
439 /// Borrows a reference from the given frame.
440 /// # Verified Properties
441 /// ## Preconditions
442 /// - **Safety Invariant**: Metaslot region invariants must hold.
443 /// ## Postconditions
444 /// - **Safety Invariant**: Metaslot region invariants hold after the call.
445 /// - **Correctness**: The function returns a reference to the frame.
446 /// - **Correctness**: The system context is unchanged.
447 #[verus_spec(res =>
448 requires
449 self.inv(),
450 ensures
451 res.slot_vaddr() == self.slot_vaddr(),
452 res.inv(),
453 res.frac_metadata_perm() == self.frac_metadata_perm(),
454 MetaSlot::perms_related(res@.slot_perm(), self.metadata_perm()),
455 )]
456 pub fn borrow<'a>(&'a self) -> FrameRef<'a, M> {
457 let tracked slot_perm = *self.tracked_slot_perm.borrow();
458 let tracked metadata_perm = self.tracked_metadata_perm.borrow().tracked_borrow();
459 // SAFETY: Both the lifetime and the type matches `self`.
460 unsafe {
461 #[verus_spec(with Tracked(slot_perm), Tracked(Some(metadata_perm)))]
462 FrameRef::borrow_paddr(self.start_paddr())
463 }
464 }
465
466 /// Forgets the handle to the frame.
467 ///
468 /// This will result in the frame being leaked without calling the custom dropper.
469 ///
470 /// A physical address to the frame is returned in case the frame needs to be
471 /// restored using [`Frame::from_raw`] later. This is useful when some architectural
472 /// data structures need to hold the frame handle such as the page table.
473 ///
474 /// # Verified Properties
475 /// ## Preconditions
476 /// - **Safety**: The frame's invariant must be satisfied.
477 /// ## Postconditions
478 /// - **Correctness**: The function returns the physical address of the frame.
479 /// ## Safety
480 /// - We require the slot to be in use to ensure that a fresh frame handle will not be created until the raw frame is restored.
481 /// - The owner's raw count is incremented so that we can enforce the safety requirement on `Frame::from_raw`.
482 #[verus_spec(r =>
483 with
484 -> raw_permission: Tracked<FrameRawPerms>,
485 requires
486 self.inv(),
487 ensures
488 r == self.start_paddr_spec(),
489 raw_permission@.inv(),
490 )]
491 pub(in crate::mm) fn into_raw(mut self) -> Paddr {
492 broadcast use group_page_meta;
493
494 proof_decl!{
495 let tracked perm = FrameRawPerms {
496 slot_perm: &*self.tracked_slot_perm,
497 metadata_perm: self.tracked_metadata_perm.tracked_take(),
498 };
499 }
500
501 let this = ManuallyDrop::new(self);
502 proof_with!(|= Tracked(perm));
503 this.start_paddr()
504 }
505}
506
507#[verus_verify]
508impl<M: ?Sized> Frame<M> {
509 /// Gets the metadata slot of the frame.
510 ///
511 /// # Verified Properties
512 /// ## Preconditions
513 /// - **Safety**: The caller must have a valid permission for the frame.
514 /// ## Postconditions
515 /// - **Correctness**: The function returns a reference to the metadata slot of the frame.
516 /// ## Safety
517 /// - There is no way to mutably borrow the metadata slot, so taking an immutable reference is safe.
518 /// (The fields of the slot can be mutably borrowed, but not the slot itself.)
519 #[verus_spec(
520 requires
521 self.ptr_inv(),
522 returns
523 self.tracked_slot_perm@.value(),
524 )]
525 pub fn slot<'a>(&'a self) -> &'a MetaSlot {
526 // SAFETY: `ptr` points to a valid `MetaSlot` that will never be
527 // mutably borrowed, so taking an immutable reference to it is safe.
528 proof_decl! {
529 let tracked slot_perm = *self.tracked_slot_perm;
530 }
531 // Origin Rust: unsafe { &*self.ptr }
532 ptr_ref(self.ptr, Tracked(slot_perm))
533 }
534}
535
536#[verus_verify]
537impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + ?Sized> Frame<M> {
538 /// Restores a forgotten [`Frame`] from a physical address.
539 ///
540 /// # Safety
541 ///
542 /// The caller should only restore a `Frame` that was previously forgotten using
543 /// [`Frame::into_raw`].
544 ///
545 /// And the restoring operation should only be done once for a forgotten
546 /// [`Frame`]. Otherwise double-free will happen.
547 ///
548 /// Also, the caller ensures that the usage of the frame is correct. There's
549 /// no checking of the usage in this function.
550 #[verus_spec(r =>
551 with
552 Tracked(perm): Tracked<FrameRawPerms>,
553 requires
554 valid_frame_paddr(paddr),
555 perm.slot_vaddr() == frame_to_meta(paddr),
556 perm.inv(),
557 ensures
558 r.tracked_slot_perm@ == perm.slot_perm,
559 r.tracked_metadata_perm@ == Some(perm.metadata_perm),
560 r.start_paddr_spec() == paddr,
561 r.inv(),
562 )]
563 pub(in crate::mm) unsafe fn from_raw(paddr: Paddr) -> Self
564 no_unwind
565 {
566 // debug_assert!(paddr < max_paddr());
567 let vaddr = frame_to_meta(paddr);
568 /* vstd requires the exposed provenance witness retained by the slot permission.
569 * Origin Rust: let ptr = vaddr as *const MetaSlot;
570 */
571 let ptr = ptr_from_addr(vaddr, Tracked(perm.slot_perm));
572
573 proof_with!{ tracked_slot_perm: Tracked(perm.slot_perm), tracked_metadata_perm: Tracked(Some(perm.metadata_perm)) }
574 Self { ptr, _marker: PhantomData }
575 }
576}
577
578#[verus_verify]
579impl<M: AnyFrameMeta + Repr<MetaSlotStorage>> RCClone for Frame<M> {
580 open spec fn clone_requires(self, regions: MetaRegionOwners) -> bool {
581 let paddr = self.start_paddr_spec();
582 let ref_count = regions.slot_owner(paddr).ref_count();
583 &&& self.inv()
584 &&& regions.inv()
585 &&& self.wf_with_region(regions)
586 &&& ref_count > 0
587 &&& ref_count != REF_COUNT_UNUSED
588 &&& allowed_to_panic_if(ref_count >= REF_COUNT_MAX)
589 }
590
591 open spec fn clone_ensures(
592 self,
593 pre: MetaRegionOwners,
594 post: MetaRegionOwners,
595 res: Self,
596 ) -> bool {
597 let idx = self.index();
598 &&& pre.inc_frame_reference_region_spec(self.start_paddr_spec(), post)
599 &&& post.inv()
600 &&& res.tracked_metadata_perm@ is Some
601 &&& res.frac_metadata_perm().frac() == 1
602 &&& res.frac_metadata_perm().id() == post.slot_owners[idx].metadata_perm.id()
603 &&& res.tracked_slot_perm@ == post.slots[idx]
604 &&& res.ptr == self.ptr
605 }
606
607 fn clone(&self, Tracked(regions): Tracked<&mut MetaRegionOwners>) -> Self {
608 proof_decl! {
609 regions.lemma_contains_valid_frame_paddr(self.start_paddr_spec());
610 let ghost paddr = self.start_paddr_spec();
611 let tracked slot_perm = regions.tracked_borrow_slot(paddr);
612 let tracked slot_own = regions.tracked_borrow_mut_slot_owner(paddr);
613 }
614
615 // SAFETY: We have already held a reference to the frame.
616 unsafe {
617 #[verus_spec(with Tracked(&mut slot_own.ref_count_perm))]
618 self.slot().inc_ref_count();
619 }
620
621 proof_decl!{
622 let tracked metadata_perm = slot_own.metadata_perm.split_one();
623 };
624
625 Self {
626 ptr: self.ptr,
627 _marker: PhantomData,
628 #[cfg(verus_keep_ghost_body)]
629 tracked_slot_perm: Tracked(slot_perm),
630 #[cfg(verus_keep_ghost_body)]
631 tracked_metadata_perm: Tracked(Some(metadata_perm)),
632 }
633 }
634}
635
636/*
637impl<M: AnyFrameMeta + ?Sized> Drop for Frame<M> {
638 fn drop(&mut self) {
639 let last_ref_cnt = self.slot().ref_count.fetch_sub(1, Ordering::Release);
640 debug_assert!(last_ref_cnt != 0 && last_ref_cnt != REF_COUNT_UNUSED);
641
642 if last_ref_cnt == 1 {
643 // A fence is needed here with the same reasons stated in the implementation of
644 // `Arc::drop`: <https://doc.rust-lang.org/std/sync/struct.Arc.html#method.drop>.
645 core::sync::atomic::fence(Ordering::Acquire);
646
647 // SAFETY: this is the last reference and is about to be dropped.
648 unsafe { self.slot().drop_last_in_place() };
649
650 allocator::get_global_frame_allocator().dealloc(self.start_paddr(), PAGE_SIZE);
651 }
652 }
653}*/
654
655impl<M: ?Sized> Frame<M> {
656 pub fn drop(mut self, Tracked(regions): Tracked<&mut MetaRegionOwners>)
657 requires
658 self.inv(),
659 old(regions).inv(),
660 self.wf_with_region(*old(regions)),
661 old(regions).slot_owners[self.index()].ref_count() == 1 ==> old(
662 regions,
663 ).slot_owners[self.index()].paths_in_pt.is_empty(),
664 ensures
665 final(regions).inv(),
666 ({
667 let paddr = self.start_paddr_spec();
668 let old_owner = old(regions).slot_owner(paddr);
669 let new_owner = final(regions).slot_owner(paddr);
670 &&& *final(regions) =~= old(regions).insert_slot_owner(paddr, new_owner)
671 &&& new_owner.slot_vaddr == old_owner.slot_vaddr
672 &&& new_owner.usage == old_owner.usage
673 &&& new_owner.paths_in_pt == old_owner.paths_in_pt
674 &&& new_owner.metadata_perm.id() == old_owner.metadata_perm.id()
675 &&& old_owner.ref_count() == 1 ==> new_owner.ref_count() == REF_COUNT_UNUSED
676 &&& old_owner.ref_count() > 1 ==> new_owner.ref_count() == (old_owner.ref_count()
677 - 1) as u64
678 }),
679 {
680 proof_decl!{
681 let ghost idx = self.index();
682 let tracked slot_own = regions.tracked_borrow_mut_slot_owner(self.start_paddr_spec());
683 let tracked frame_permission = self.tracked_metadata_perm.tracked_take();
684 slot_own.metadata_perm.combine(frame_permission);
685 }
686
687 let last_ref_cnt = self.slot().ref_count.fetch_sub(
688 Tracked(&mut slot_own.ref_count_perm),
689 1,
690 );
691
692 if last_ref_cnt == 1 {
693 // A fence is needed here with the same reasons stated in the implementation of
694 // `Arc::drop`: <https://doc.rust-lang.org/std/sync/struct.Arc.html#method.drop>.
695 acquire_fence();
696 // SAFETY: this is the last reference and is about to be dropped.
697 unsafe {
698 #[verus_spec(with Tracked(slot_own))]
699 self.slot().drop_last_in_place()
700 };
701
702 // TODO: return page to allocator
703 // allocator::get_global_frame_allocator().dealloc(paddr, PAGE_SIZE);
704 }
705 proof {
706 assert_maps_equal!(
707 regions.slot_owners,
708 old(regions).slot_owners.insert(idx, regions.slot_owners[idx]),
709 i => {
710 if i != idx {
711 assert(regions.slot_owners[i] == old(regions).slot_owners[i]);
712 }
713 }
714 );
715 }
716 }
717}
718
719/*
720
721impl<M: AnyFrameMeta> TryFrom<Frame<dyn AnyFrameMeta>> for Frame<M> {
722 type Error = Frame<dyn AnyFrameMeta>;
723
724 /// Tries converting a [`Frame<dyn AnyFrameMeta>`] into the statically-typed [`Frame`].
725 ///
726 /// If the usage of the frame is not the same as the expected usage, it will
727 /// return the dynamic frame itself as is.
728 fn try_from(dyn_frame: Frame<dyn AnyFrameMeta>) -> Result<Self, Self::Error> {
729 if (dyn_frame.dyn_meta() as &dyn core::any::Any).is::<M>() {
730 // SAFETY: The metadata is coerceable and the struct is transmutable.
731 Ok(unsafe { core::mem::transmute::<Frame<dyn AnyFrameMeta>, Frame<M>>(dyn_frame) })
732 } else {
733 Err(dyn_frame)
734 }
735 }
736}*/
737
738/*impl<M: AnyFrameMeta> From<UFrame> for Frame<M> {
739 fn from(frame: UFrame) -> Self {
740 // SAFETY: The metadata is coerceable and the struct is transmutable.
741 unsafe { core::mem::transmute(frame) }
742 }
743}*/
744
745/*impl TryFrom<Frame<FrameMeta>> for UFrame {
746 type Error = Frame<FrameMeta>;
747}*/
748
749#[verifier::external]
750impl<M: AnyUFrameMeta> From<Frame<M>> for UFrame {
751 fn from(frame: Frame<M>) -> Self {
752 // SAFETY: The metadata is coerceable and the struct is transmutable.
753 unsafe { core::mem::transmute(frame) }
754 }
755}
756
757/*
758impl From<UFrame> for Frame<dyn AnyFrameMeta> {
759 fn from(frame: UFrame) -> Self {
760 // SAFETY: The metadata is coerceable and the struct is transmutable.
761 unsafe { core::mem::transmute(frame) }
762 }
763}
764
765impl TryFrom<Frame<dyn AnyFrameMeta>> for UFrame {
766 type Error = Frame<dyn AnyFrameMeta>;
767
768 /// Tries converting a [`Frame<dyn AnyFrameMeta>`] into [`UFrame`].
769 ///
770 /// If the usage of the frame is not the same as the expected usage, it will
771 /// return the dynamic frame itself as is.
772 fn try_from(dyn_frame: Frame<dyn AnyFrameMeta>) -> Result<Self, Self::Error> {
773 if dyn_frame.dyn_meta().is_untyped() {
774 // SAFETY: The metadata is coerceable and the struct is transmutable.
775 Ok(unsafe { core::mem::transmute::<Frame<dyn AnyFrameMeta>, UFrame>(dyn_frame) })
776 } else {
777 Err(dyn_frame)
778 }
779 }
780}*/
781
782/// Increases the reference count of the frame by one.
783///
784/// # Safety
785///
786/// The caller should ensure the following conditions:
787/// 1. The physical address must represent a valid frame;
788/// 2. The caller must have already held a reference to the frame.
789///
790/// # Verified Properties
791/// ## Preconditions
792/// - **Safety Invariant**: Metaslot region invariants must hold.
793/// - **Safety**: The physical address must represent a valid frame.
794/// ## Postconditions
795/// - **Safety Invariant**: Metaslot region invariants hold after the call.
796/// - **Correctness**: The reference count of the frame is increased by one.
797/// - **Safety**: Frames other than this one are not affected by the call.
798#[verus_spec(permission =>
799 with
800 Tracked(regions): Tracked<&mut MetaRegionOwners>,
801 requires
802 old(regions).inv(),
803 old(regions).contains(frame_to_index(paddr)),
804 valid_frame_paddr(paddr),
805 old(regions).slot_owner(paddr).ref_count() > 0,
806 old(regions).slot_owner(paddr).ref_count()
807 != REF_COUNT_UNUSED,
808 allowed_to_panic_if(old(regions).slot_owner(paddr).ref_count() >= REF_COUNT_MAX),
809 ensures
810 final(regions).inv(),
811 permission@.frac() == 1,
812 permission@.id() == final(regions).slot_owner(paddr).metadata_perm.id(),
813 permission@.resource() == old(regions).slot_owner(paddr).metadata_perm@,
814 old(regions).inc_frame_reference_region_spec(paddr, *final(regions)),
815)]
816pub(in crate::mm) unsafe fn inc_frame_ref_count(paddr: Paddr) -> (permission: Tracked<
817 FracMetadataPerm,
818>) {
819 let tracked perm = regions.tracked_borrow_slot(paddr);
820 let tracked slot_own = regions.tracked_borrow_mut_slot_owner(paddr);
821
822 let vaddr: Vaddr = frame_to_meta(paddr);
823 // SAFETY: `vaddr` points to a valid `MetaSlot` that will never be mutably borrowed, so taking
824 // an immutable reference to it is always safe.
825 // Origin Rust: let slot = unsafe { &*(vaddr as *const MetaSlot) };
826 let slot = ptr_from_addr::<MetaSlot>(vaddr, Tracked(perm));
827
828 // Origin Rust: unsafe { slot.inc_ref_count() };
829 unsafe {
830 #[verus_spec(with Tracked(&mut slot_own.ref_count_perm))]
831 ptr_ref(slot, Tracked(perm)).inc_ref_count()
832 };
833 let tracked frame_permission = slot_own.metadata_perm.split_one();
834
835 Tracked(frame_permission)
836}
837
838/// A dynamically-typed frame is represented by a frame of the underlying metadata type,
839/// which can be cast from any other type.
840pub type DynFrame = Frame<MetaSlotStorage>;
841
842impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + 'static> Frame<M> {
843 /// Erases the static metadata type, yielding a `Frame<dyn AnyFrameMeta>`.
844 ///
845 /// Inherent method rather than `From`/`Into` to avoid trait-inference
846 /// ambiguity at call sites that previously relied on the blanket
847 /// `From<T> for T` (e.g. `frame.into()` for `Frame<UFrame>`).
848 ///
849 /// Axiomatized (`external_body`) because the body is `transmute`, which
850 /// Verus has no built-in spec for.
851 #[verifier::external_body]
852 pub fn into_dyn(self) -> Frame<dyn AnyFrameMeta> {
853 // SAFETY: Both frame types have the same runtime fields: a `*const MetaSlot`
854 // and a zero-sized, alignment-one `PhantomData`. Their size and alignment
855 // are equal, and the metadata type parameter does not change the pointer.
856 // Tracked permission fields are erased.
857 unsafe { core::mem::transmute(self) }
858 }
859}
860
861} // verus!