Skip to main content

ostd/sync/
mutex.rs

1// SPDX-License-Identifier: MPL-2.0
2use vstd::{
3    atomic_ghost::*,
4    cell::{
5        self,
6        pcell::{self, *},
7    },
8    prelude::*,
9};
10use vstd_extra::{prelude::*, resource::ghost_resource::excl::*};
11
12use super::WaitQueue;
13use alloc::sync::Arc;
14use core::{
15    cell::UnsafeCell,
16    fmt,
17    ops::{Deref, DerefMut},
18    sync::atomic::Ordering,
19};
20
21verus! {
22
23struct_with_invariants! {
24
25/// A mutex with waitqueue.
26pub struct Mutex<T  /* : ?Sized */ > {
27    lock: AtomicBool<_, Option<PointsTo<T>>, _>,
28    queue: WaitQueue,
29    // val: UnsafeCell<T>,
30    val: PCell<T>,
31}
32
33closed spec fn wf(self) -> bool {
34    invariant on lock with (val) is (v: bool, g: Option<PointsTo<T>>) {
35        let active_guard = g is None;
36        &&& v <==> active_guard
37        &&& g is Some ==> g->0.id() == val.id()
38    }
39}
40}
41
42impl<T> Mutex<T> {
43    pub closed spec fn cell_id(self) -> cell::CellId {
44        self.val.id()
45    }
46
47    #[verifier::type_invariant]
48    pub closed spec fn type_inv(self) -> bool {
49        self.wf()
50    }
51
52    /// Creates a new mutex.
53    pub const fn new(val: T) -> Self {
54        let (val, Tracked(perm)) = PCell::new(val);
55        Self {
56            lock: AtomicBool::new(
57                Ghost(val),
58                false,
59                Tracked(Some(perm)),
60            ),
61            queue: WaitQueue::new(),
62            val: val,
63        }
64    }
65}
66
67#[verus_verify]
68impl<T  /* : ?Sized */ > Mutex<T> {
69    /// Acquires the mutex.
70    ///
71    /// This method runs in a block way until the mutex can be acquired.
72    #[track_caller]
73    #[verus_spec(ret => ensures ret.rel_mutex(*self))]
74    pub fn lock(&self) -> MutexGuard<'_, T> {
75        self.queue.wait_until(
76            || -> (ret: Option<MutexGuard<'_, T>>)
77                ensures
78                    ret is Some ==> ret->0.rel_mutex(*self),
79                { self.try_lock() },
80        )
81    }
82
83    /// Tries to acquire the mutex immediately.
84    #[verus_spec(ret =>
85        ensures
86            ret is Some ==> ret->0.rel_mutex(*self),
87    )]
88    pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
89        // Cannot be reduced to `then_some`, or the possible dropping of the temporary
90        // guard will cause an unexpected unlock.
91        // SAFETY: The lock is successfully acquired when creating the guard.
92        proof_decl! {
93            let tracked mut locked_state: Option<PointsTo<T>> = None;
94        }
95        (#[verus_spec(with => Tracked(locked_state))] self.acquire_lock()).then(
96            || -> (ret: MutexGuard<T>)
97                requires
98                    locked_state is Some,
99                    locked_state -> Some_0.id() == self.cell_id(),
100                ensures
101                    ret.rel_mutex(*self),
102                {unsafe { proof_with!{Tracked(locked_state.tracked_unwrap())}; MutexGuard::new(self) }})
103    }
104
105    /* /// Returns a mutable reference to the underlying data.
106    ///
107    /// This method is zero-cost: By holding a mutable reference to the lock, the compiler has
108    /// already statically guaranteed that access to the data is exclusive.
109    #[verifier::external_body]
110    pub fn get_mut(&mut self) -> &mut T {
111        self.val.get_mut()
112    } */
113
114    /// Releases the mutex and wake up one thread which is blocked on this mutex.
115    ///
116    /// # Safety
117    ///
118    /// The caller must ensure that it has acquired the lock.
119    #[verus_spec(
120        with
121            Tracked(perm): Tracked<PointsTo<T>>,
122        requires
123            perm.id() == self.cell_id(),
124    )]
125    unsafe fn unlock(&self)
126    {
127        // SAFETY: The safety is upheld by the caller.
128        unsafe {
129            proof_with!(Tracked(perm));
130            self.release_lock();
131        }
132        self.queue.wake_one();
133    }
134
135    #[verus_spec(ret =>
136        with
137            -> locked_state: Tracked<Option<PointsTo<T>>>,
138        ensures
139            ret ==> locked_state@ is Some && locked_state@->0.id() == self.cell_id(),
140            !ret ==> locked_state@ is None,
141    )]
142    fn acquire_lock(&self) -> bool {
143        proof_decl! {
144            let tracked mut locked_state: Option<PointsTo<T>> = None;
145        }
146        proof! {
147            use_type_invariant(self);
148        }
149        proof_with! { |= Tracked(locked_state) }
150        atomic_with_ghost! {
151            self.lock => compare_exchange(false, true);
152            returning res;
153            ghost perms => {
154                if res is Ok {
155                    let tracked perm = perms.tracked_take();
156                    locked_state = Some(perm);
157                }
158            }
159        }.is_ok()
160    }
161
162    /// # Safety
163    ///
164    /// The caller must ensure that it has acquired the lock.
165    #[verus_spec(
166        with
167            Tracked(perm): Tracked<PointsTo<T>>,
168        requires
169            perm.id() == self.cell_id(),
170    )]
171    unsafe fn release_lock(&self)
172    {
173        proof! {
174            use_type_invariant(self);
175        }
176        atomic_with_ghost! {
177            self.lock => store(false);
178            ghost perms => {
179                perms = Some(perm);
180            }
181        }
182    }
183}
184
185/* impl<T: /* ?Sized +  */fmt::Debug> fmt::Debug for Mutex<T> {
186    #[verifier::external_body]
187    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188        fmt::Debug::fmt(&self.val, f)
189    }
190} */
191#[verifier::external]
192unsafe impl<T: /*?Sized + */Send> Send for Mutex<T> {}
193#[verifier::external]
194unsafe impl<T: /*?Sized + */Send> Sync for Mutex<T> {}
195
196/// A guard that provides exclusive access to the data protected by a [`Mutex`].
197#[verifier::reject_recursive_types(T)]
198#[clippy::has_significant_drop]
199#[must_use]
200#[verus_verify]
201pub struct MutexGuard<'a, T  /* : ?Sized */ > {
202    mutex: &'a Mutex<T>,
203    tracked_perm: Tracked<PointsTo<T>>,
204}
205
206impl<'a, T  /* : ?Sized */ > MutexGuard<'a, T> {
207    #[verifier::type_invariant]
208    closed spec fn type_inv(self) -> bool {
209        self.tracked_perm@.id() == self.mutex.cell_id()
210    }
211
212    /// The value stored in the mutex.
213    pub closed spec fn value(self) -> T {
214        *self.tracked_perm@.value()
215    }
216
217    /// The value stored in the mutex. It is an alias of `Self::value`.
218    pub open spec fn view(self) -> T {
219        self.value()
220    }
221
222    pub closed spec fn rel_mutex(self, mutex: Mutex<T>) -> bool {
223        *self.mutex == mutex
224    }
225}
226
227#[verus_verify]
228impl<'a, T  /* : ?Sized */ > MutexGuard<'a, T> {
229    /// # Safety
230    ///
231    /// The caller must ensure that the given reference of [`Mutex`] lock has been successfully acquired
232    /// in the current context. When the created [`MutexGuard`] is dropped, it will unlock the [`Mutex`].
233    #[verus_spec(ret =>
234        with
235            Tracked(perm): Tracked<PointsTo<T>>,
236        requires
237            perm.id() == mutex.cell_id(),
238        ensures
239            ret.rel_mutex(*mutex),
240    )]
241    unsafe fn new(mutex: &'a Mutex<T>) -> (r: MutexGuard<'a, T>)
242    {
243        MutexGuard { mutex, tracked_perm: Tracked(perm) }
244    }
245}
246
247#[verus_verify]
248impl<T/* : ?Sized */> Deref for MutexGuard<'_, T> {
249    type Target = T;
250
251    #[verus_spec(returns self.view())]
252    fn deref(&self) -> &Self::Target {
253        proof! {
254            use_type_invariant(self);
255        }
256        // unsafe { &*self.mutex.val.get() }
257        self.mutex.val.borrow(Tracked(self.tracked_perm.borrow()))
258    }
259}
260
261#[verus_verify]
262impl<T/* : ?Sized */> DerefMut for MutexGuard<'_, T> {
263    #[verus_spec(ret =>
264        ensures
265            final(self).view() == *final(ret),
266            old(self).view() == *ret,
267    )]
268    fn deref_mut(&mut self) -> &mut Self::Target
269    {
270        proof!{
271            use_type_invariant(&*self);
272        }
273        //unsafe { &mut *self.mutex.val.get() }
274        self.mutex.val.borrow_mut(Tracked(&mut *self.tracked_perm))
275    }
276}
277
278/* impl<T  /* : ?Sized */ > Drop for MutexGuard<'_, T> {
279    fn drop(&mut self)
280    {
281        // SAFETY: The mutex is locked.
282        unsafe { self.mutex.unlock() };
283    }
284} */
285
286impl<T: /* ?Sized*/ > MutexGuard<'_, T> {
287    /// VERUS LIMITATION: We implement `drop` and call it manually because Verus's support for `Drop` is incomplete for now.
288    #[verus_spec]
289    pub fn drop(self) {
290        proof!{use_type_invariant(&self);}
291        // SAFETY: The mutex is locked.
292        unsafe {
293            proof_with!(self.tracked_perm);
294            self.mutex.unlock();
295        }
296    }
297}
298
299impl<T: /*?Sized + */fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
300    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
301        fmt::Debug::fmt(&**self, f)
302    }
303}
304
305impl<T  /* : ?Sized */ > !Send for MutexGuard<'_, T> {}
306
307#[verifier::external]
308unsafe impl<T: /*?Sized +*/ Sync> Sync for MutexGuard<'_, T> {}
309
310#[verus_verify]
311impl<'a, T  /* : ?Sized */ > MutexGuard<'a, T> {
312    /// Returns the [`Mutex`] associated with this guard.
313    #[verus_spec(ret =>
314        ensures
315            guard.rel_mutex(*ret),
316    )]
317    pub fn get_lock(guard: &MutexGuard<'a, T>) -> &'a Mutex<T> {
318        guard.mutex
319    }
320}
321
322} // verus!
323
324/* #[cfg(ktest)] */
325mod test {
326    use vstd::invariant::AtomicInvariant;
327
328    use super::*;
329    use crate::prelude::*;
330
331    // A regression test for a bug fixed in [#1279](https://github.com/asterinas/asterinas/pull/1279).
332    /* #[ktest] */
333    #[verus_spec]
334    fn test_mutex_try_lock_does_not_unlock() {
335        /* Unfold Mutex::new so the initial load can use the atomic permission before
336         * it is hidden in an invariant. vstd's atomic loads are sequentially consistent.
337         * Origin Rust:
338         * let lock = Mutex::new(0);
339         * assert!(!lock.lock.load(Ordering::Relaxed));
340         */
341        let (val, perm) = PCell::new(0);
342        let (patomic, lock_perm) = vstd::atomic::PAtomicBool::new(false);
343        assert!(verus_exec_expr! { !patomic.load(Tracked(lock_perm.borrow())) });
344        let lock = Mutex {
345            lock: AtomicBool {
346                patomic,
347                atomic_inv: verus_exec_expr! {
348                    Tracked(AtomicInvariant::new(
349                        (val, patomic.id()), (lock_perm.get(), Some(perm.get())), 0,
350                    ))
351                },
352            },
353            queue: WaitQueue::new(),
354            val,
355        };
356
357        // A successful lock
358        let guard1 = lock.lock();
359        proof! {
360            use_type_invariant(&lock);
361            use_type_invariant(&guard1);
362        }
363        /* Open the atomic invariant to relate the loaded bit to the live guard's permission.
364         * Origin Rust: assert!(lock.lock.load(Ordering::Relaxed));
365         */
366        assert!(atomic_with_ghost! {
367            lock.lock => load();
368            returning locked;
369            ghost perms => {
370                if let Some(perm) = &mut perms {
371                    perm.is_exclusive(guard1.tracked_perm.borrow());
372                }
373            }
374        });
375
376        // A failed `try_lock` won't drop the lock
377        /* Name the result so its permission can be compared with the live guard's permission.
378         * Origin Rust: assert!(lock.try_lock().is_none());
379         */
380        let mut guard2 = lock.try_lock();
381        proof! {
382            use_type_invariant(&guard1);
383            if let Some(guard2) = &mut guard2 {
384                use_type_invariant(&*guard2);
385                guard2.tracked_perm.borrow_mut().is_exclusive(guard1.tracked_perm.borrow());
386            }
387        }
388        assert!(guard2.is_none());
389        /* Open the atomic invariant to relate the loaded bit to the live guard's permission.
390         * Origin Rust: assert!(lock.lock.load(Ordering::Relaxed));
391         */
392        assert!(atomic_with_ghost! {
393            lock.lock => load();
394            returning locked;
395            ghost perms => {
396                if let Some(perm) = &mut perms {
397                    perm.is_exclusive(guard1.tracked_perm.borrow());
398                }
399            }
400        });
401
402        // Ensure the lock is held until here
403        /* Verus requires the guard's explicit release method because automatic Drop is unsupported.
404         * Origin Rust: drop(guard1);
405         */
406        guard1.drop();
407    }
408}