Skip to main content

ostd/mm/frame/
unique.rs

1// SPDX-License-Identifier: MPL-2.0
2//! The unique frame pointer that is not shared with others.
3use vstd::{prelude::*, simple_pptr::PPtr};
4use vstd_extra::{
5    auxiliary::OptionExtraFns,
6    cast_ptr::*,
7    ownership::*,
8    raw_ptr::{ExposedPointsTo, ptr_from_addr, ptr_ref},
9};
10
11use crate::specs::{
12    arch::*,
13    mm::frame::{mapping::*, meta_owners::*, meta_region_owners::MetaRegionOwners, unique::*},
14};
15
16use super::{
17    Frame,
18    meta::{
19        AnyFrameMeta, GetFrameError, META_SLOT_SIZE, MetaSlot, REF_COUNT_UNIQUE, REF_COUNT_UNUSED,
20        mapping::{frame_to_meta, meta_to_frame},
21    },
22};
23use crate::mm::{Paddr, PagingConsts, PagingLevel};
24use core::{marker::PhantomData, mem::ManuallyDrop, sync::atomic::Ordering};
25
26verus! {
27
28pub struct UniqueFrame<M: AnyFrameMeta + ?Sized + Repr<MetaSlotStorage> + OwnerOf> {
29    pub ptr: *const MetaSlot,
30    pub _marker: PhantomData<M>,
31    /// The permission to access the `MetaSlot` fields.
32    #[cfg(verus_keep_ghost_body)]
33    pub tracked_slot_perm: Tracked<&'static ExposedPointsTo<MetaSlot>>,
34    /// The complete permission for the currently installed metadata.
35    #[cfg(verus_keep_ghost_body)]
36    pub tracked_metadata_perm: Tracked<Option<MetadataPerm>>,
37}
38
39#[verifier::external]
40unsafe impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf + Send> Send for UniqueFrame<M> {
41
42}
43
44#[verifier::external]
45unsafe impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf + Sync> Sync for UniqueFrame<M> {
46
47}
48
49/*
50impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf + ?Sized> core::fmt::Debug for UniqueFrame<
51    M,
52> {
53    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
54        write!(f, "UniqueFrame({:#x})", self.start_paddr())
55    }
56}
57*/
58
59#[verus_verify]
60impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf> UniqueFrame<M> {
61    /// Gets a [`UniqueFrame`] with a specific usage from a raw, unused page.
62    ///
63    /// The caller should provide the initial metadata of the page.
64    /// # Verified Properties
65    /// ## Preconditions
66    /// The page must be unused and the metadata region must be well-formed.
67    /// ## Postconditions
68    /// If the page is valid, the function returns a unique frame.
69    /// ## Safety
70    /// If `paddr` is misaligned or out of bounds, the function will return an error. If it returns a frame,
71    /// it also returns an owner for that frame, indicating that the caller now has exclusive ownership of it.
72    /// See [Safe Encapsulation] for more details.
73    #[verus_spec(res =>
74        with
75            Tracked(regions): Tracked<&mut MetaRegionOwners>,
76            Tracked(meta_own_in): Tracked<M::Owner>,
77                -> owner: Tracked<Option<UniqueFrameOwner<M>>>,
78        requires
79            old(regions).contains(frame_to_index(paddr)),
80            old(regions).slot_owner(paddr).usage is Unused,
81            old(regions).inv(),
82            <M as OwnerOf>::wf(metadata, meta_own_in),
83        ensures
84            res matches Ok(res) ==> {
85                &&& owner@ is Some
86                &&& res.wf(owner@->0)
87                &&& res.wf_with_region(owner@->0, *final(regions))
88                &&& owner@->0.meta_own == meta_own_in
89                &&& res.meta_value(owner@->0) == metadata
90                &&& res.inv()
91                &&& res.start_paddr_spec() == paddr
92            },
93            res is Err ==> {
94                &&& owner@ is None
95                &&& *final(regions) == *old(regions)
96            },
97            final(regions).inv(),
98    )]
99    pub fn from_unused(paddr: Paddr, metadata: M) -> Result<Self, GetFrameError> {
100        #[verus_spec(with
101            Tracked(regions) => Tracked(permissions)
102        )]
103        let from_unused = MetaSlot::get_from_unused(paddr, metadata, true);
104
105        if let Err(err) = from_unused {
106            proof_with!(|= Tracked(None));
107            Err(err)
108        } else {
109            proof_decl! {
110                let tracked metadata_perms = permissions.tracked_unwrap().tracked_take_right();
111                let tracked slot_perm = regions.tracked_borrow_slot(paddr);
112                let tracked owner = UniqueFrameOwner::<M> {
113                    meta_own: meta_own_in,
114                    slot_index: frame_to_index(paddr),
115                };
116            }
117
118            let ptr = from_unused.unwrap();
119
120            proof_with!(|= Tracked(Some(owner)));
121            Ok(
122                Self {
123                    ptr,
124                    _marker: PhantomData,
125                    #[cfg(verus_keep_ghost_body)]
126                    tracked_slot_perm: Tracked(slot_perm),
127                    #[cfg(verus_keep_ghost_body)]
128                    tracked_metadata_perm: Tracked(Some(metadata_perms)),
129                },
130            )
131        }
132    }
133
134    // FIXME: This seems to be unsound and has to be corrected until we have better modeling of trait object.
135    pub open spec fn transmute_spec<M1: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf>(
136        self,
137        transmuted: UniqueFrame<M1>,
138    ) -> bool {
139        &&& transmuted.slot_vaddr() == self.slot_vaddr()
140        &&& transmuted.tracked_slot_perm@ == self.tracked_slot_perm@
141        &&& transmuted.tracked_metadata_perm@ == self.tracked_metadata_perm@
142    }
143
144    #[verifier::external_body]
145    #[verus_spec(res =>
146        ensures
147            Self::transmute_spec(self, res),
148    )]
149    pub fn transmute<M1: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf>(self) -> UniqueFrame<M1> {
150        unimplemented!()
151    }
152
153    /// Repurposes the frame with a new metadata.
154    /// # Verified Properties
155    /// ## Preconditions
156    /// - The caller must provide a valid owner for the frame, and the metadata region invariants must hold.
157    /// - The meta slot's reference count must be `REF_COUNT_UNIQUE`.
158    /// ## Postconditions
159    /// The function returns a new owner for the frame with the new metadata,
160    /// and the metadata region invariants are preserved.
161    /// ## Safety
162    /// The existence of a valid owner guarantees that the memory is initialized with metadata of type `M`,
163    /// and represents that the caller has exclusive ownership of the frame.
164    #[verus_spec(res =>
165        with
166            Tracked(owner): Tracked<UniqueFrameOwner<M>>,
167            Tracked(regions): Tracked<&mut MetaRegionOwners>,
168            Tracked(meta_own_in): Tracked<M1::Owner>,
169                -> new_owner: Tracked<UniqueFrameOwner<M1>>,
170        requires
171            self.wf_with_region(owner, *old(regions)),
172            old(regions).slot_owners[self.index()].in_list_perm.value() == 0,
173            old(regions).inv(),
174            self.inv(),
175            owner.inv(),
176            <M1 as OwnerOf>::wf(metadata, meta_own_in),
177        ensures
178            res.wf(new_owner@),
179            res.wf_with_region(new_owner@, *final(regions)),
180            new_owner@.meta_own == meta_own_in,
181            res.meta_value(new_owner@) == metadata,
182            final(regions).inv(),
183    )]
184    pub fn repurpose<M1: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf>(
185        mut self,
186        metadata: M1,
187    ) -> UniqueFrame<M1> {
188        proof_decl! {
189            broadcast use group_page_meta;
190            let ghost idx = self.index();
191            let tracked slot_own = regions.slot_owners.tracked_borrow_mut(idx);
192            let tracked metadata_perm = self.tracked_metadata_perm.tracked_take();
193        }
194
195        // SAFETY: We are the sole owner and the metadata is initialized.
196        unsafe {
197            #[verus_spec(with
198                Tracked(&slot_own.ref_count_perm),
199                Tracked(&slot_own.in_list_perm),
200                Tracked(&mut metadata_perm)
201            )]
202            self.slot().drop_meta_in_place()
203        };
204
205        unsafe {
206            #[verus_spec(with
207                Tracked(&mut metadata_perm),
208            )]
209            self.slot().write_meta(metadata)
210        };
211
212        proof {
213            slot_own.usage = metadata_perm.usage();
214        }
215        proof_decl! {
216            let tracked new_owner = UniqueFrameOwner::<M1> {
217                meta_own: meta_own_in,
218                slot_index: meta_to_index(self.slot_vaddr()),
219            };
220        }
221
222        #[cfg(verus_keep_ghost_body)]
223        {
224            self.tracked_metadata_perm = Tracked(Some(metadata_perm));
225        }
226
227        // SAFETY: The metadata is initialized with type `M1`.
228        proof_with!(|= Tracked(new_owner));
229        self.transmute()
230    }
231
232    /// Gets the metadata of this page.
233    /// # Verified Properties
234    /// ## Preconditions
235    /// The caller must provide a valid owner for the frame.
236    /// ## Postconditions
237    /// The function returns the metadata of the frame.
238    /// ## Safety
239    /// The existence of a valid owner guarantees that the memory is initialized with metadata of type `M`,
240    /// and represents that the caller has exclusive ownership of the frame.
241    #[verus_spec(l =>
242        with
243            Tracked(owner): Tracked<&'a UniqueFrameOwner<M>>,
244        requires
245            owner.inv(),
246            self.inv(),
247            self.wf(*owner),
248            self.meta_wf(*owner),
249        ensures
250            self.meta_value(*owner) == l,
251    )]
252    pub fn meta<'a>(&'a self) -> &'a M {
253        // SAFETY: The type is tracked by the type system.
254        // unsafe { &*self.slot().as_meta_ptr::<M>() }
255        let tracked points_to = *self.tracked_slot_perm.borrow();
256        let tracked metadata_perms = self.tracked_metadata_perm.borrow().tracked_borrow();
257        borrow_meta(
258            ReprPtr::<MetaSlotStorage, M>::from_pptr(PPtr::from_addr(self.ptr.addr())),
259            Tracked(points_to),
260            Tracked(metadata_perms),
261        )
262    }
263
264    /// Gets the mutable metadata of this page.
265    /// Verified Properties
266    /// ## Preconditions
267    /// The caller must provide a valid owner for the frame.
268    /// ## Postconditions
269    /// The function returns the mutable metadata of the frame.
270    /// ## Safety
271    /// The existence of a valid owner guarantees that the memory is initialized with metadata of type `M`,
272    /// and represents that the caller has exclusive ownership of the frame. (See [Safe Encapsulation])
273    #[verus_spec(res =>
274        with
275            Tracked(owner): Tracked<&'a mut UniqueFrameOwner<M>>,
276        requires
277            old(self).inv(),
278            old(self).wf(*owner),
279            old(self).meta_wf(*owner),
280            owner.inv(),
281        ensures
282            *res == old(self).meta_value(*old(owner)),
283            *final(res) == final(self).meta_value(*final(owner)),
284            final(self).inv(),
285            final(self).ptr == old(self).ptr,
286            final(self).tracked_slot_perm@ == old(self).tracked_slot_perm@,
287            final(owner).meta_own == old(owner).meta_own,
288            final(owner).slot_index == old(owner).slot_index,
289            final(owner).inv(),
290            final(self).meta_wf(*final(owner)),
291            (*final(self)).wf(*final(owner)),
292    )]
293    pub fn meta_mut<'a>(&'a mut self) -> &'a mut M {
294        let tracked points_to = *self.tracked_slot_perm.borrow();
295        let tracked metadata_perms = self.tracked_metadata_perm.borrow_mut().tracked_borrow_mut();
296        borrow_meta_mut(
297            ReprPtr::<MetaSlotStorage, M>::from_pptr(PPtr::from_addr(self.ptr.addr())),
298            Tracked(points_to),
299            Tracked(metadata_perms),
300        )
301    }
302}
303
304impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf + ?Sized> UniqueFrame<M> {
305    /// Gets the size of this page in bytes.
306    pub const fn size(&self) -> usize
307        returns
308            PAGE_SIZE,
309    {
310        PAGE_SIZE
311    }
312
313    /// Gets the paging level of this page.
314    ///
315    /// This is the level of the page table entry that maps the frame,
316    /// which determines the size of the frame.
317    ///
318    /// Currently, the level is always 1, which means the frame is a regular
319    /// page frame.
320    pub const fn level(&self) -> PagingLevel
321        returns
322            1u8,
323    {
324        1
325    }
326}
327
328#[verus_verify]
329impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf + ?Sized> UniqueFrame<M> {
330    /// Gets the physical address of the start of the frame.
331    #[verus_spec(
332        requires
333            self.ptr_inv(),
334        returns
335            meta_to_frame(self.slot_vaddr()),
336    )]
337    pub fn start_paddr(&self) -> Paddr {
338        let slot = self.slot();
339
340        #[verus_spec(with self.tracked_slot_perm)]
341        slot.frame_paddr()
342    }
343
344    /*    /// Gets the dynamically-typed metadata of this frame.
345    ///
346    /// If the type is known at compile time, use [`Frame::meta`] instead.
347
348    #[verifier::external_body]
349    pub fn dyn_meta(&self) -> &M {
350        // SAFETY: The metadata is initialized and valid.
351        unsafe { &*self.slot().dyn_meta_ptr::<M>() }
352    }
353
354    /// Gets the dynamically-typed metadata of this frame.
355    ///
356    /// If the type is known at compile time, use [`Frame::meta`] instead.
357
358    #[verifier::external_body]
359    pub fn dyn_meta_mut(&mut self) -> &mut FrameMeta {
360        // SAFETY: The metadata is initialized and valid. We have the exclusive
361        // access to the frame.
362        unsafe { &mut *self.slot().dyn_meta_ptr() }
363    }*/
364    /// Resets the frame to unused without up-calling the allocator.
365    ///
366    /// This is solely useful for the allocator implementation/testing and
367    /// is highly experimental. Usage of this function is discouraged.
368    ///
369    /// Usage of this function other than the allocator would actually leak
370    /// the frame since the allocator would not be aware of the frame.
371    //
372    // FIXME: We may have a better `Segment` and `UniqueSegment` design to
373    // allow the allocator hold the ownership of all the frames in a chunk
374    // instead of the head. Then this weird public API can be `#[cfg(ktest)]`.
375    #[verus_spec(
376        with
377            Tracked(owner): Tracked<UniqueFrameOwner<M>>,
378            Tracked(regions): Tracked<&mut MetaRegionOwners>,
379        requires
380            self.inv(),
381            owner.inv(),
382            regions.inv(),
383            self.wf_with_region(owner, *old(regions)),
384            old(regions).slot_owners[owner.slot_index].in_list_perm.value() == 0,
385        ensures
386            final(regions).inv(),
387    )]
388    pub fn reset_as_unused(mut self) {
389        let mut this = self;
390
391        proof_decl! {
392            let tracked mut owner = owner;
393            let tracked slot_own = regions.tracked_borrow_mut_slot_owner(self.start_paddr_spec());
394            let tracked metadata_perms = this.tracked_metadata_perm.tracked_take();
395            slot_own.metadata_perm.put_resource(metadata_perms);
396        }
397
398        this.slot().ref_count.store(Tracked(&mut slot_own.ref_count_perm), 0);
399
400        // SAFETY: We are the sole owner and the reference count is 0.
401        // The slot is initialized.
402        unsafe {
403            #[verus_spec(with Tracked(slot_own))]
404            this.slot().drop_last_in_place()
405        };
406    }
407
408    /// Converts this frame into a raw physical address.
409    #[verus_spec(r =>
410        with
411            -> metadata_perms: Tracked<MetadataPerm>,
412        requires
413            self.inv(),
414        ensures
415            metadata_perms@ == self.metadata_perm(),
416            r == meta_to_frame(self.slot_vaddr()),
417    )]
418    pub(crate) fn into_raw(mut self) -> Paddr {
419        let tracked metadata_perms = self.tracked_metadata_perm.tracked_take();
420        let this = ManuallyDrop::new(self);
421
422        proof_with!(|= Tracked(metadata_perms));
423        this.start_paddr()
424    }
425
426    /// Restores a raw physical address back into a unique frame.
427    ///
428    /// # Safety
429    ///
430    /// The caller must ensure that the physical address is valid and points to
431    /// a forgotten frame that was previously casted by [`Self::into_raw`].
432    #[verus_spec(res =>
433        with
434            Tracked(slot_perm): Tracked<&'static ExposedPointsTo<MetaSlot>>,
435            Tracked(meta_own): Tracked<M::Owner>,
436            Tracked(metadata_perm): Tracked<MetadataPerm>,
437            ->
438                owner: Tracked<UniqueFrameOwner<M>>,
439        requires
440            valid_frame_paddr(paddr),
441            slot_perm.addr() == frame_to_meta(paddr),
442            slot_perm.is_init(),
443            MetaSlot::perms_related(*slot_perm, metadata_perm)
444        ensures
445            res.inv(),
446            res.start_paddr_spec() == paddr,
447            res.tracked_slot_perm@ == slot_perm,
448            res.wf(owner@),
449            owner@.meta_own == meta_own,
450            res.tracked_metadata_perm@ == Some(metadata_perm),
451            owner@.slot_index == frame_to_index(paddr),
452    )]
453    pub(crate) unsafe fn from_raw(paddr: Paddr) -> Self {
454        let vaddr = frame_to_meta(paddr);
455        // Origin Rust: let ptr = vaddr as *const MetaSlot;
456        let ptr = ptr_from_addr(vaddr, Tracked(slot_perm));
457
458        let tracked owner = UniqueFrameOwner { meta_own, slot_index: frame_to_index(paddr) };
459        proof_with!{ |= Tracked(owner)}
460        Self {
461            ptr,
462            _marker: PhantomData,
463            #[cfg(verus_keep_ghost_body)]
464            tracked_slot_perm: Tracked(slot_perm),
465            #[cfg(verus_keep_ghost_body)]
466            tracked_metadata_perm: Tracked(Some(metadata_perm)),
467        }
468    }
469
470    #[verus_spec(
471        requires
472            self.ptr_inv(),
473        returns
474            self.tracked_slot_perm@.value(),
475    )]
476    pub fn slot<'a>(&self) -> &'a MetaSlot {
477        // SAFETY: `ptr` points to a valid `MetaSlot` that will never be
478        // mutably borrowed, so taking an immutable reference to it is safe.
479        let tracked slot_perm = *self.tracked_slot_perm;
480        // Origin Rust: unsafe { &*self.ptr }
481        ptr_ref(self.ptr, Tracked(slot_perm))
482    }
483}
484
485/*
486impl<M: AnyFrameMeta + ?Sized> Drop for UniqueFrame<M> {
487    fn drop(&mut self) {
488        self.slot().ref_count.store(0, Ordering::Relaxed);
489        // SAFETY: We are the sole owner and the reference count is 0.
490        // The slot is initialized.
491        unsafe { self.slot().drop_last_in_place() };
492
493        super::allocator::get_global_frame_allocator().dealloc(self.start_paddr(), PAGE_SIZE);
494    }
495} */
496
497impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf + ?Sized> UniqueFrame<M> {
498    #[verus_spec(
499        with
500            Tracked(owner): Tracked<UniqueFrameOwner<M>>,
501            Tracked(regions): Tracked<&mut MetaRegionOwners>,
502        requires
503            old(self).inv(),
504            owner.inv(),
505            regions.inv(),
506            old(self).wf_with_region(owner, *old(regions)),
507            old(regions).slot_owners[owner.slot_index].in_list_perm.value() == 0,
508        ensures
509            final(regions).inv(),
510            final(regions).slots == old(regions).slots,
511            forall|i: int| #![trigger final(regions).slot_owners[i]]
512                i != owner.slot_index ==> final(regions).slot_owners[i]
513                    == old(regions).slot_owners[i],
514    )]
515    pub(crate) fn drop(&mut self) {
516        let tracked mut owner = owner;
517        let tracked slot_own = regions.tracked_borrow_mut_slot_owner(self.start_paddr_spec());
518        let tracked metadata_perms = self.tracked_metadata_perm.tracked_take();
519        proof {
520            slot_own.metadata_perm.put_resource(metadata_perms);
521        }
522        // SAFETY: We are the sole owner and the reference count is 0.
523        // The slot is initialized.
524        self.slot().ref_count.store(Tracked(&mut slot_own.ref_count_perm), 0);
525
526        unsafe {
527            #[verus_spec(with Tracked(slot_own))]
528            self.slot().drop_last_in_place()
529        };
530
531        // super::allocator::get_global_frame_allocator().dealloc(self.start_paddr(), PAGE_SIZE);
532    }
533}
534
535#[verus_verify]
536impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf> Frame<M> {
537    #[verus_spec(res =>
538        with
539            Tracked(owner): Tracked<UniqueFrameOwner<M>>,
540            Tracked(regions): Tracked<&mut MetaRegionOwners>,
541        requires
542            unique.inv(),
543            owner.inv(),
544            old(regions).inv(),
545            unique.wf_with_region(owner, *old(regions)),
546            old(regions).slot_owners[owner.slot_index].in_list_perm.value() == 0,
547        ensures
548            res.inv(),
549            final(regions).inv(),
550            res.wf_with_region(*final(regions)),
551            final(regions).slots == old(regions).slots,
552            final(regions).slot_owners.dom() == old(regions).slot_owners.dom(),
553    )]
554    pub fn from_unique(unique: UniqueFrame<M>) -> Self {
555        let tracked mut owner = owner;
556        let ptr = unique.ptr;
557        let ghost idx = meta_to_index(unique.slot_vaddr());
558        proof {
559            broadcast use group_page_meta;
560
561            regions.lemma_contains_valid_frame_paddr(meta_to_frame(unique.slot_vaddr()));
562        }
563        let tracked slot_own = regions.slot_owners.tracked_borrow_mut(idx);
564        let slot = unique.slot();
565        let tracked metadata_perms = unique.tracked_metadata_perm.get().tracked_unwrap();
566        proof {
567            slot_own.metadata_perm.put_resource(metadata_perms);
568        }
569        let tracked frame_permission = slot_own.metadata_perm.split_one();
570        let tracked mut inner_perms = &mut slot_own;
571
572        slot.ref_count.store(Tracked(&mut inner_perms.ref_count_perm), 1);
573
574        let res = Frame {
575            ptr,
576            _marker: PhantomData,
577            #[cfg(verus_keep_ghost_body)]
578            tracked_slot_perm: unique.tracked_slot_perm,
579            #[cfg(verus_keep_ghost_body)]
580            tracked_metadata_perm: Tracked(Some(frame_permission)),
581        };
582        res
583    }
584}
585
586#[verus_verify]
587impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf> UniqueFrame<M> {
588    /// Tries to convert a shared frame into a unique one by CAS'ing ref_count
589    /// from 1 to `REF_COUNT_UNIQUE`. Inherent sibling of
590    /// `TryFrom<Frame<M>> for UniqueFrame<M>`.
591    #[verus_spec(res =>
592        with
593            Tracked(regions): Tracked<&mut MetaRegionOwners>,
594        requires
595            frame.inv(),
596            old(regions).inv(),
597            frame.wf_with_region(*old(regions)),
598        ensures
599            final(regions).slots == old(regions).slots,
600            final(regions).slot_owners.dom() == old(regions).slot_owners.dom(),
601    )]
602    pub fn try_from_shared(mut frame: Frame<M>) -> Result<Self, Frame<M>> {
603        let ghost idx = meta_to_index(frame.slot_vaddr());
604        proof {
605            broadcast use group_page_meta;
606
607            regions.lemma_contains_valid_frame_paddr(frame.start_paddr_spec());
608        }
609        let tracked mut slot_own = regions.slot_owners.tracked_borrow_mut(idx);
610        let tracked inner_perms = &mut slot_own;
611        let res = frame.slot().ref_count.compare_exchange(
612            Tracked(&mut inner_perms.ref_count_perm),
613            1,
614            REF_COUNT_UNIQUE,
615        );
616
617        match res {
618            Ok(_) => {
619                let tracked frame_permission = frame.tracked_metadata_perm.tracked_take();
620                proof {
621                    slot_own.metadata_perm.combine(frame_permission);
622                }
623                let tracked metadata_perms = slot_own.metadata_perm.take_resource();
624                Ok(
625                    UniqueFrame {
626                        ptr: frame.ptr,
627                        _marker: PhantomData,
628                        #[cfg(verus_keep_ghost_body)]
629                        tracked_slot_perm: frame.tracked_slot_perm,
630                        #[cfg(verus_keep_ghost_body)]
631                        tracked_metadata_perm: Tracked(Some(metadata_perms)),
632                    },
633                )
634            },
635            Err(_) => Err(frame),
636        }
637    }
638}
639
640impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf> From<UniqueFrame<M>> for Frame<M> {
641    #[verifier::external_body]
642    fn from(unique: UniqueFrame<M>) -> Self {
643        Frame::from_unique(unique)
644    }
645}
646
647impl<M: AnyFrameMeta + Repr<MetaSlotStorage> + OwnerOf> TryFrom<Frame<M>> for UniqueFrame<M> {
648    type Error = Frame<M>;
649
650    /// Tries to get a unique frame from a shared frame.
651    ///
652    /// If the reference count is not 1, the frame is returned back.
653    #[verifier::external_body]
654    fn try_from(frame: Frame<M>) -> Result<Self, Self::Error> {
655        UniqueFrame::try_from_shared(frame)
656    }
657}
658
659} // verus!