Skip to main content

vstd/
rwlock.rs

1#![allow(non_snake_case)]
2#![allow(unused_imports)]
3#![allow(non_shorthand_field_patterns)]
4
5use super::atomic_ghost::*;
6use super::cell::CellId;
7use super::cell::pcell_maybe_uninit as un;
8use super::invariant::InvariantPredicate;
9use super::modes::*;
10use super::multiset::*;
11use super::prelude::*;
12use super::set::*;
13use core::marker::PhantomData;
14use verus_state_machines_macros::tokenized_state_machine_vstd;
15
16tokenized_state_machine_vstd!(
17RwLockToks<K, V, Pred: InvariantPredicate<K, V>> {
18    #![verifier::prophetic]
19
20    fields {
21        #[sharding(constant)]
22        pub k: K,
23
24        #[sharding(constant)]
25        pub pred: PhantomData<Pred>,
26
27        #[sharding(variable)]
28        pub flag_exc: bool,
29
30        #[sharding(variable)]
31        pub flag_rc: nat,
32
33        #[sharding(storage_option)]
34        pub storage: Option<V>,
35
36        #[sharding(option)]
37        pub pending_writer: Option<()>,
38
39        #[sharding(option)]
40        pub writer: Option<()>,
41
42        #[sharding(multiset)]
43        pub pending_reader: Multiset<()>,
44
45        #[sharding(multiset)]
46        pub reader: Multiset<V>,
47    }
48
49    init!{
50        initialize_full(k: K, t: V) {
51            require Pred::inv(k, t);
52            init k = k;
53            init pred = PhantomData;
54            init flag_exc = false;
55            init flag_rc = 0;
56            init storage = Option::Some(t);
57            init pending_writer = Option::None;
58            init writer = Option::None;
59            init pending_reader = Multiset::empty();
60            init reader = Multiset::empty();
61        }
62    }
63
64    #[inductive(initialize_full)]
65    fn initialize_full_inductive(post: Self, k: K, t: V) {
66        broadcast use group_multiset_axioms;
67    }
68
69    /// Increment the 'rc' counter, obtain a pending_reader
70    transition!{
71        acquire_read_start() {
72            update flag_rc = pre.flag_rc + 1;
73            add pending_reader += {()};
74        }
75    }
76
77    /// Exchange the pending_reader for a reader by checking
78    /// that the 'exc' bit is 0
79    transition!{
80        acquire_read_end() {
81            require(pre.flag_exc == false);
82
83            remove pending_reader -= {()};
84
85            birds_eye let x: V = pre.storage->0;
86            add reader += {x};
87
88            assert Pred::inv(pre.k, x);
89        }
90    }
91
92    /// Decrement the 'rc' counter, abandon the attempt to gain
93    /// the 'read' lock.
94    transition!{
95        acquire_read_abandon() {
96            remove pending_reader -= {()};
97            assert(pre.flag_rc >= 1);
98            update flag_rc = (pre.flag_rc - 1) as nat;
99        }
100    }
101
102    /// Atomically set 'exc' bit from 'false' to 'true'
103    /// Obtain a pending_writer
104    transition!{
105        acquire_exc_start() {
106            require(pre.flag_exc == false);
107            update flag_exc = true;
108            add pending_writer += Some(());
109        }
110    }
111
112    /// Finish obtaining the write lock by checking that 'rc' is 0.
113    /// Exchange the pending_writer for a writer and withdraw the
114    /// stored object.
115    transition!{
116        acquire_exc_end() {
117            require(pre.flag_rc == 0);
118
119            remove pending_writer -= Some(());
120
121            add writer += Some(());
122
123            birds_eye let x = pre.storage->0;
124            withdraw storage -= Some(x);
125
126            assert Pred::inv(pre.k, x);
127        }
128    }
129
130    /// Release the write-lock. Update the 'exc' bit back to 'false'.
131    /// Return the 'writer' and also deposit an object back into storage.
132    transition!{
133        release_exc(x: V) {
134            require Pred::inv(pre.k, x);
135            remove writer -= Some(());
136
137            update flag_exc = false;
138
139            deposit storage += Some(x);
140        }
141    }
142
143    /// Check that the 'reader' is actually a guard for the given object.
144    property!{
145        read_guard(x: V) {
146            have reader >= {x};
147            guard storage >= Some(x);
148        }
149    }
150
151    property!{
152        read_match(x: V, y: V) {
153            have reader >= {x};
154            have reader >= {y};
155            assert(equal(x, y));
156        }
157    }
158
159    /// Release the reader-lock. Decrement 'rc' and return the 'reader' object.
160    #[transition]
161    transition!{
162        release_shared(x: V) {
163            remove reader -= {x};
164
165            assert(pre.flag_rc >= 1) by {
166                //assert(pre.reader.count(x) >= 1);
167                assert(equal(pre.storage, Option::Some(x)));
168                //assert(equal(x, pre.storage->0));
169            };
170            update flag_rc = (pre.flag_rc - 1) as nat;
171        }
172    }
173
174    #[invariant]
175    pub fn exc_bit_matches(&self) -> bool {
176        (if self.flag_exc { 1 } else { 0 as int }) ==
177            (if self.pending_writer is Some { 1 } else { 0 as int }) as int
178            + (if self.writer is Some { 1 } else { 0 as int }) as int
179    }
180
181    #[invariant]
182    pub fn count_matches(&self) -> bool {
183        self.flag_rc == self.pending_reader.count(())
184            + self.reader.count(self.storage->0)
185    }
186
187    #[invariant]
188    pub fn reader_agrees_storage(&self) -> bool {
189        forall |t: V| imply(#[trigger] self.reader.count(t) > 0,
190            equal(self.storage, Option::Some(t)))
191    }
192
193    #[invariant]
194    pub fn writer_agrees_storage(&self) -> bool {
195        imply(self.writer is Some, self.storage is None)
196    }
197
198    #[invariant]
199    pub fn writer_agrees_storage_rev(&self) -> bool {
200        imply(self.storage is None, self.writer is Some)
201    }
202
203    #[invariant]
204    #[verifier::prophetic]
205    pub fn sto_user_inv(&self) -> bool {
206        self.storage.is_some() ==> Pred::inv(self.k, self.storage.unwrap())
207    }
208
209    #[inductive(acquire_read_start)]
210    fn acquire_read_start_inductive(pre: Self, post: Self) {
211        broadcast use group_multiset_axioms;
212    }
213
214    #[inductive(acquire_read_end)]
215    fn acquire_read_end_inductive(pre: Self, post: Self) {
216        broadcast use group_multiset_axioms;
217    }
218
219    #[inductive(acquire_read_abandon)]
220    fn acquire_read_abandon_inductive(pre: Self, post: Self) {
221        broadcast use group_multiset_axioms;
222    }
223
224    #[inductive(acquire_exc_start)]
225    fn acquire_exc_start_inductive(pre: Self, post: Self) { }
226
227    #[inductive(acquire_exc_end)]
228    fn acquire_exc_end_inductive(pre: Self, post: Self) { }
229
230    #[inductive(release_exc)]
231    fn release_exc_inductive(pre: Self, post: Self, x: V) { }
232
233    #[inductive(release_shared)]
234    fn release_shared_inductive(pre: Self, post: Self, x: V) {
235        broadcast use group_multiset_axioms;
236        assert(equal(pre.storage, Option::Some(x)));
237    }
238});
239
240verus! {
241
242pub trait RwLockPredicate<V>: Sized {
243    spec fn inv(self, v: V) -> bool;
244}
245
246impl<V> RwLockPredicate<V> for spec_fn(V) -> bool {
247    open spec fn inv(self, v: V) -> bool {
248        self(v)
249    }
250}
251
252ghost struct InternalPred<V, Pred> {
253    v: V,
254    pred: Pred,
255}
256
257impl<V, Pred: RwLockPredicate<V>> InvariantPredicate<
258    (Pred, CellId),
259    un::PointsTo<V>,
260> for InternalPred<V, Pred> {
261    closed spec fn inv(k: (Pred, CellId), v: un::PointsTo<V>) -> bool {
262        v.id() == k.1 && v.is_init() && k.0.inv(v.value())
263    }
264}
265
266struct_with_invariants!{
267    /** A verified implementation of a reader-writer lock,
268    implemented using atomics and a reference count.
269
270    When constructed, you can provide an invariant via the `Pred` parameter,
271    specifying the allowed values that can go in the lock.
272
273    Note that this specification does *not* verify the absence of dead-locks.
274
275    ### Examples
276
277    On construction of a lock, we can specify an invariant for the object that goes inside.
278    One way to do this is by providing a `spec_fn`, which implements the [`RwLockPredicate`]
279    trait.
280
281    ```rust,ignore
282    fn example1() {
283        // We can create a lock with an invariant: `v == 5 || v == 13`.
284        // Thus only 5 or 13 can be stored in the lock.
285        let lock = RwLock::<u64, spec_fn(u64) -> bool>::new(5, Ghost(|v| v == 5 || v == 13));
286
287        let (val, write_handle) = lock.acquire_write();
288        assert(val == 5 || val == 13);
289        write_handle.release_write(13);
290
291        let read_handle1 = lock.acquire_read();
292        let read_handle2 = lock.acquire_read();
293
294        // We can take multiple read handles at the same time:
295
296        let val1 = read_handle1.borrow();
297        let val2 = read_handle2.borrow();
298
299        // RwLock has a lemma that both read handles have the same value:
300
301        proof { ReadHandle::lemma_readers_match(&read_handle1, &read_handle2); }
302        assert(*val1 == *val2);
303
304        read_handle1.release_read();
305        read_handle2.release_read();
306    }
307    ```
308
309    It's often easier to implement the [`RwLockPredicate`] trait yourself. This way you can
310    have a configurable predicate without needing to work with higher-order functions.
311
312    ```rust,ignore
313    struct FixedParity {
314        pub parity: int,
315    }
316
317    impl RwLockPredicate<u64> for FixedParity {
318        open spec fn inv(self, v: u64) -> bool {
319            v % 2 == self.parity
320        }
321    }
322
323    fn example2() {
324        // Create a lock that can only store even integers
325        let lock_even = RwLock::<u64, FixedParity>::new(20, Ghost(FixedParity { parity: 0 }));
326
327        // Create a lock that can only store odd integers
328        let lock_odd = RwLock::<u64, FixedParity>::new(23, Ghost(FixedParity { parity: 1 }));
329
330        let read_handle_even = lock_even.acquire_read();
331        let val_even = *read_handle_even.borrow();
332        assert(val_even % 2 == 0);
333
334        let read_handle_odd = lock_odd.acquire_read();
335        let val_odd = *read_handle_odd.borrow();
336        assert(val_odd % 2 == 1);
337    }
338    ```
339    */
340
341    pub struct RwLock<V, Pred: RwLockPredicate<V>> {
342        cell: un::PCell<V>,
343        exc: AtomicBool<_, RwLockToks::flag_exc<(Pred, CellId), un::PointsTo<V>, InternalPred<V, Pred>>, _>,
344        rc: AtomicUsize<_, RwLockToks::flag_rc<(Pred, CellId), un::PointsTo<V>, InternalPred<V, Pred>>, _>,
345
346        inst: Tracked<RwLockToks::Instance<(Pred, CellId), un::PointsTo<V>, InternalPred<V, Pred>>>,
347        pred: Ghost<Pred>,
348    }
349
350    #[verifier::type_invariant]
351    spec fn wf(&self) -> bool {
352        invariant on exc with (inst) is (v: bool, g: RwLockToks::flag_exc<(Pred, CellId), un::PointsTo<V>, InternalPred<V, Pred>>) {
353            g.instance_id() == inst@.id()
354                && g.value() == v
355        }
356
357        invariant on rc with (inst) is (v: usize, g: RwLockToks::flag_rc<(Pred, CellId), un::PointsTo<V>, InternalPred<V, Pred>>) {
358            g.instance_id() == inst@.id()
359                && g.value() == v
360        }
361
362        predicate {
363            self.inst@.k() == (self.pred@, self.cell.id())
364        }
365    }
366}
367
368/// Handle obtained for an exclusive write-lock from an [`RwLock`].
369///
370/// Note that this handle does not contain a reference to the lock-protected object;
371/// ownership of the object is obtained separately from [`RwLock::acquire_write`].
372/// This may be changed in the future.
373///
374/// **Warning:** The lock is _NOT_ released automatically when the handle
375/// is dropped. You must call [`release_write`](WriteHandle::release_write).
376/// Verus does not check that lock is released.
377pub struct WriteHandle<'a, V, Pred: RwLockPredicate<V>> {
378    handle: Tracked<RwLockToks::writer<(Pred, CellId), un::PointsTo<V>, InternalPred<V, Pred>>>,
379    perm: Tracked<un::PointsTo<V>>,
380    rwlock: &'a RwLock<V, Pred>,
381}
382
383/// Handle obtained for a shared read-lock from an [`RwLock`].
384///
385/// **Warning:** The lock is _NOT_ released automatically when the handle
386/// is dropped. You must call [`release_read`](ReadHandle::release_read).
387/// Verus does not check that lock is released.
388pub struct ReadHandle<'a, V, Pred: RwLockPredicate<V>> {
389    handle: Tracked<RwLockToks::reader<(Pred, CellId), un::PointsTo<V>, InternalPred<V, Pred>>>,
390    rwlock: &'a RwLock<V, Pred>,
391}
392
393impl<'a, V, Pred: RwLockPredicate<V>> WriteHandle<'a, V, Pred> {
394    #[verifier::type_invariant]
395    spec fn wf_write_handle(self) -> bool {
396        equal(self.perm@.id(), self.rwlock.cell.id()) && self.perm@.is_uninit() && equal(
397            self.handle@.instance_id(),
398            self.rwlock.inst@.id(),
399        ) && self.rwlock.wf()
400    }
401
402    pub closed spec fn rwlock(self) -> RwLock<V, Pred> {
403        *self.rwlock
404    }
405
406    pub fn release_write(self, new_val: V)
407        requires
408            self.rwlock().inv(new_val),
409    {
410        proof {
411            use_type_invariant(&self);
412        }
413        let WriteHandle { handle: Tracked(handle), perm: Tracked(mut perm), rwlock } = self;
414        self.rwlock.cell.put(Tracked(&mut perm), new_val);
415
416        atomic_with_ghost!(
417            &rwlock.exc => store(false);
418            ghost g =>
419        {
420            self.rwlock.inst.borrow().release_exc(perm, &mut g, perm, handle);
421        });
422    }
423}
424
425impl<'a, V, Pred: RwLockPredicate<V>> ReadHandle<'a, V, Pred> {
426    #[verifier::type_invariant]
427    spec fn wf_read_handle(self) -> bool {
428        equal(self.handle@.instance_id(), self.rwlock.inst@.id())
429            && self.handle@.element().is_init() && equal(
430            self.handle@.element().id(),
431            self.rwlock.cell.id(),
432        ) && self.rwlock.wf()
433    }
434
435    pub closed spec fn view(self) -> V {
436        self.handle@.element().value()
437    }
438
439    pub closed spec fn rwlock(self) -> RwLock<V, Pred> {
440        *self.rwlock
441    }
442
443    /// Obtain a shared reference to the object contained in the lock.
444    pub fn borrow<'b>(&'b self) -> (val: &'b V)
445        ensures
446            val == self.view(),
447    {
448        proof {
449            use_type_invariant(self);
450        }
451        let tracked perm = self.rwlock.inst.borrow().read_guard(
452            self.handle@.element(),
453            self.handle.borrow(),
454        );
455        self.rwlock.cell.borrow(Tracked(&perm))
456    }
457
458    pub proof fn lemma_readers_match(
459        tracked read_handle1: &ReadHandle<V, Pred>,
460        tracked read_handle2: &ReadHandle<V, Pred>,
461    )
462        requires
463            read_handle1.rwlock() == read_handle2.rwlock(),
464        ensures
465            (equal(read_handle1.view(), read_handle2.view())),
466    {
467        use_type_invariant(read_handle1);
468        use_type_invariant(read_handle2);
469        read_handle1.rwlock.inst.borrow().read_match(
470            read_handle1.handle@.element(),
471            read_handle2.handle@.element(),
472            &read_handle1.handle.borrow(),
473            &read_handle2.handle.borrow(),
474        );
475    }
476
477    pub fn release_read(self) {
478        proof {
479            use_type_invariant(&self);
480        }
481        let ReadHandle { handle: Tracked(handle), rwlock } = self;
482
483        let _ =
484            atomic_with_ghost!(
485            &rwlock.rc => fetch_sub(1);
486            ghost g =>
487        {
488            rwlock.inst.borrow().release_shared(handle.element(), &mut g, handle);
489        });
490    }
491}
492
493impl<V, Pred: RwLockPredicate<V>> RwLock<V, Pred> {
494    /// Predicate configured for this lock instance.
495    pub closed spec fn pred(&self) -> Pred {
496        self.pred@
497    }
498
499    /// Indicates if the value `v` can be stored in the lock. Per the definition,
500    /// it depends on `[self.pred()]`, which is configured upon lock construction ([`RwLock::new`]).
501    pub open spec fn inv(&self, val: V) -> bool {
502        self.pred().inv(val)
503    }
504
505    pub fn new(val: V, Ghost(pred): Ghost<Pred>) -> (s: Self)
506        requires
507            pred.inv(val),
508        ensures
509            s.pred() == pred,
510    {
511        let (cell, Tracked(perm)) = un::PCell::<V>::new(val);
512
513        let tracked (Tracked(inst), Tracked(flag_exc), Tracked(flag_rc), _, _, _, _) =
514            RwLockToks::Instance::<
515            (Pred, CellId),
516            un::PointsTo<V>,
517            InternalPred<V, Pred>,
518        >::initialize_full((pred, cell.id()), perm, Option::Some(perm));
519        let inst = Tracked(inst);
520
521        let exc = AtomicBool::new(Ghost(inst), false, Tracked(flag_exc));
522        let rc = AtomicUsize::new(Ghost(inst), 0, Tracked(flag_rc));
523
524        RwLock { cell, exc, rc, inst, pred: Ghost(pred) }
525    }
526
527    /// Acquires an exclusive write-lock. To release it, use [`WriteHandle::release_write`].
528    ///
529    /// **Warning:** The lock is _NOT_ released automatically when the handle
530    /// is dropped. You must call [`WriteHandle::release_write`].
531    /// Verus does not check that lock is released.
532    #[verifier::exec_allows_no_decreases_clause]
533    pub fn acquire_write(&self) -> (ret: (V, WriteHandle<'_, V, Pred>))
534        ensures
535            ({
536                let val = ret.0;
537                let write_handle = ret.1;
538                &&& write_handle.rwlock() == *self
539                &&& self.inv(val)
540            }),
541    {
542        proof {
543            use_type_invariant(self);
544        }
545        let mut done = false;
546        let tracked mut token: Option<
547            RwLockToks::pending_writer<(Pred, CellId), un::PointsTo<V>, InternalPred<V, Pred>>,
548        > = Option::None;
549        while !done
550            invariant
551                done ==> token.is_some() && equal(token->0.instance_id(), self.inst@.id()),
552                self.wf(),
553        {
554            let result =
555                atomic_with_ghost!(
556                &self.exc => compare_exchange(false, true);
557                returning res;
558                ghost g =>
559            {
560                if res is Ok {
561                    token = Option::Some(self.inst.borrow().acquire_exc_start(&mut g));
562                }
563            });
564
565            done =
566            match result {
567                Result::Ok(_) => true,
568                _ => false,
569            };
570        }
571        loop
572            invariant
573                token is Some && equal(token->0.instance_id(), self.inst@.id()),
574                self.wf(),
575        {
576            let tracked mut perm_opt: Option<un::PointsTo<V>> = None;
577            let tracked mut handle_opt: Option<
578                RwLockToks::writer<(Pred, CellId), un::PointsTo<V>, InternalPred<V, Pred>>,
579            > = None;
580
581            let result =
582                atomic_with_ghost!(
583                &self.rc => load();
584                returning res;
585                ghost g =>
586            {
587                if res == 0 {
588                    let tracked tok = match token { Option::Some(t) => t, Option::None => proof_from_false() };
589                    let tracked x = self.inst.borrow().acquire_exc_end(&g, tok);
590                    token = None;
591                    let tracked (_, Tracked(perm), Tracked(exc_handle)) = x;
592                    perm_opt = Some(perm);
593                    handle_opt = Some(exc_handle);
594                }
595            });
596
597            if result == 0 {
598                let tracked mut perm = match perm_opt {
599                    Option::Some(t) => t,
600                    Option::None => proof_from_false(),
601                };
602                let tracked handle = match handle_opt {
603                    Option::Some(t) => t,
604                    Option::None => proof_from_false(),
605                };
606                let t = self.cell.take(Tracked(&mut perm));
607                let write_handle = WriteHandle {
608                    perm: Tracked(perm),
609                    handle: Tracked(handle),
610                    rwlock: self,
611                };
612                return (t, write_handle);
613            }
614        }
615    }
616
617    /// Acquires a shared read-lock. To release it, use [`ReadHandle::release_read`].
618    ///
619    /// **Warning:** The lock is _NOT_ released automatically when the handle
620    /// is dropped. You must call [`ReadHandle::release_read`].
621    /// Verus does not check that lock is released.
622    #[verifier::exec_allows_no_decreases_clause]
623    pub fn acquire_read(&self) -> (read_handle: ReadHandle<'_, V, Pred>)
624        ensures
625            read_handle.rwlock() == *self,
626            self.inv(read_handle.view()),
627    {
628        proof {
629            use_type_invariant(self);
630        }
631        loop
632            invariant
633                self.wf(),
634        {
635            let val = atomic_with_ghost!(&self.rc => load(); ghost g => { });
636
637            let tracked mut token: Option<
638                RwLockToks::pending_reader<(Pred, CellId), un::PointsTo<V>, InternalPred<V, Pred>>,
639            > = Option::None;
640
641            if val < usize::MAX {
642                let result =
643                    atomic_with_ghost!(
644                    &self.rc => compare_exchange(val, val + 1);
645                    returning res;
646                    ghost g =>
647                {
648                    if res is Ok {
649                        token = Option::Some(self.inst.borrow().acquire_read_start(&mut g));
650                    }
651                });
652
653                match result {
654                    Result::Ok(_) => {
655                        let tracked mut handle_opt: Option<
656                            RwLockToks::reader<
657                                (Pred, CellId),
658                                un::PointsTo<V>,
659                                InternalPred<V, Pred>,
660                            >,
661                        > = None;
662
663                        let result =
664                            atomic_with_ghost!(
665                            &self.exc => load();
666                            returning res;
667                            ghost g =>
668                        {
669                            if res == false {
670                                let tracked tok = match token { Option::Some(t) => t, Option::None => proof_from_false() };
671                                let tracked x = self.inst.borrow().acquire_read_end(&g, tok);
672                                token = None;
673                                let tracked (_, Tracked(exc_handle)) = x;
674                                handle_opt = Some(exc_handle);
675                            }
676                        });
677
678                        if result == false {
679                            let tracked handle = match handle_opt {
680                                Option::Some(t) => t,
681                                Option::None => proof_from_false(),
682                            };
683                            let read_handle = ReadHandle { handle: Tracked(handle), rwlock: self };
684                            return read_handle;
685                        } else {
686                            let _ =
687                                atomic_with_ghost!(
688                                &self.rc => fetch_sub(1);
689                                ghost g =>
690                            {
691                                let tracked tok = match token { Option::Some(t) => t, Option::None => proof_from_false() };
692                                self.inst.borrow().acquire_read_abandon(&mut g, tok);
693                            });
694                        }
695                    },
696                    _ => {},
697                }
698            }
699        }
700    }
701
702    /// Destroys the lock and returns the inner object.
703    /// Note that this may deadlock if not all locks have been released.
704    #[verifier::exec_allows_no_decreases_clause]
705    pub fn into_inner(self) -> (v: V)
706        ensures
707            self.inv(v),
708    {
709        let (v, _write_handle) = self.acquire_write();
710        v
711    }
712}
713
714} // verus!