1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
#![allow(non_snake_case)]
#![allow(unused_imports)]
#![allow(non_shorthand_field_patterns)]

use super::atomic_ghost::*;
use super::cell::{CellId, PCell, PointsTo};
use super::invariant::InvariantPredicate;
use super::modes::*;
use super::multiset::*;
use super::prelude::*;
use super::set::*;
use core::marker::PhantomData;
#[cfg(verus_keep_ghost)]
use state_machines_macros::tokenized_state_machine_vstd;

#[cfg(verus_keep_ghost)]
tokenized_state_machine_vstd!(
RwLockToks<K, V, Pred: InvariantPredicate<K, V>> {
    fields {
        #[sharding(constant)]
        pub k: K,

        #[sharding(constant)]
        pub pred: PhantomData<Pred>,

        #[sharding(variable)]
        pub flag_exc: bool,

        #[sharding(variable)]
        pub flag_rc: nat,

        #[sharding(storage_option)]
        pub storage: Option<V>,

        #[sharding(option)]
        pub pending_writer: Option<()>,

        #[sharding(option)]
        pub writer: Option<()>,

        #[sharding(multiset)]
        pub pending_reader: Multiset<()>,

        #[sharding(multiset)]
        pub reader: Multiset<V>,
    }

    init!{
        initialize_full(k: K, t: V) {
            require Pred::inv(k, t);
            init k = k;
            init pred = PhantomData;
            init flag_exc = false;
            init flag_rc = 0;
            init storage = Option::Some(t);
            init pending_writer = Option::None;
            init writer = Option::None;
            init pending_reader = Multiset::empty();
            init reader = Multiset::empty();
        }
    }

    #[inductive(initialize_full)]
    fn initialize_full_inductive(post: Self, k: K, t: V) {
        broadcast use group_multiset_axioms;
    }

    /// Increment the 'rc' counter, obtain a pending_reader
    transition!{
        acquire_read_start() {
            update flag_rc = pre.flag_rc + 1;
            add pending_reader += {()};
        }
    }

    /// Exchange the pending_reader for a reader by checking
    /// that the 'exc' bit is 0
    transition!{
        acquire_read_end() {
            require(pre.flag_exc == false);

            remove pending_reader -= {()};

            birds_eye let x: V = pre.storage.get_Some_0();
            add reader += {x};

            assert Pred::inv(pre.k, x);
        }
    }

    /// Decrement the 'rc' counter, abandon the attempt to gain
    /// the 'read' lock.
    transition!{
        acquire_read_abandon() {
            remove pending_reader -= {()};
            assert(pre.flag_rc >= 1);
            update flag_rc = (pre.flag_rc - 1) as nat;
        }
    }

    /// Atomically set 'exc' bit from 'false' to 'true'
    /// Obtain a pending_writer
    transition!{
        acquire_exc_start() {
            require(pre.flag_exc == false);
            update flag_exc = true;
            add pending_writer += Some(());
        }
    }

    /// Finish obtaining the write lock by checking that 'rc' is 0.
    /// Exchange the pending_writer for a writer and withdraw the
    /// stored object.
    transition!{
        acquire_exc_end() {
            require(pre.flag_rc == 0);

            remove pending_writer -= Some(());

            add writer += Some(());

            birds_eye let x = pre.storage.get_Some_0();
            withdraw storage -= Some(x);

            assert Pred::inv(pre.k, x);
        }
    }

    /// Release the write-lock. Update the 'exc' bit back to 'false'.
    /// Return the 'writer' and also deposit an object back into storage.
    transition!{
        release_exc(x: V) {
            require Pred::inv(pre.k, x);
            remove writer -= Some(());

            update flag_exc = false;

            deposit storage += Some(x);
        }
    }

    /// Check that the 'reader' is actually a guard for the given object.
    property!{
        read_guard(x: V) {
            have reader >= {x};
            guard storage >= Some(x);
        }
    }

    property!{
        read_match(x: V, y: V) {
            have reader >= {x};
            have reader >= {y};
            assert(equal(x, y));
        }
    }

    /// Release the reader-lock. Decrement 'rc' and return the 'reader' object.
    #[transition]
    transition!{
        release_shared(x: V) {
            remove reader -= {x};

            assert(pre.flag_rc >= 1) by {
                //assert(pre.reader.count(x) >= 1);
                assert(equal(pre.storage, Option::Some(x)));
                //assert(equal(x, pre.storage.get_Some_0()));
            };
            update flag_rc = (pre.flag_rc - 1) as nat;
        }
    }

    #[invariant]
    pub fn exc_bit_matches(&self) -> bool {
        (if self.flag_exc { 1 } else { 0 as int }) ==
            (if self.pending_writer.is_Some() { 1 } else { 0 as int }) as int
            + (if self.writer.is_Some() { 1 } else { 0 as int }) as int
    }

    #[invariant]
    pub fn count_matches(&self) -> bool {
        self.flag_rc == self.pending_reader.count(())
            + self.reader.count(self.storage.get_Some_0())
    }

    #[invariant]
    pub fn reader_agrees_storage(&self) -> bool {
        forall |t: V| imply(#[trigger] self.reader.count(t) > 0,
            equal(self.storage, Option::Some(t)))
    }

    #[invariant]
    pub fn writer_agrees_storage(&self) -> bool {
        imply(self.writer.is_Some(), self.storage.is_None())
    }

    #[invariant]
    pub fn writer_agrees_storage_rev(&self) -> bool {
        imply(self.storage.is_None(), self.writer.is_Some())
    }

    #[invariant]
    pub fn sto_user_inv(&self) -> bool {
        self.storage.is_some() ==> Pred::inv(self.k, self.storage.unwrap())
    }

    #[inductive(acquire_read_start)]
    fn acquire_read_start_inductive(pre: Self, post: Self) {
        broadcast use group_multiset_axioms;
    }

    #[inductive(acquire_read_end)]
    fn acquire_read_end_inductive(pre: Self, post: Self) {
        broadcast use group_multiset_axioms;
    }

    #[inductive(acquire_read_abandon)]
    fn acquire_read_abandon_inductive(pre: Self, post: Self) {
        broadcast use group_multiset_axioms;
    }

    #[inductive(acquire_exc_start)]
    fn acquire_exc_start_inductive(pre: Self, post: Self) { }

    #[inductive(acquire_exc_end)]
    fn acquire_exc_end_inductive(pre: Self, post: Self) { }

    #[inductive(release_exc)]
    fn release_exc_inductive(pre: Self, post: Self, x: V) { }

    #[inductive(release_shared)]
    fn release_shared_inductive(pre: Self, post: Self, x: V) {
        broadcast use group_multiset_axioms;
        assert(equal(pre.storage, Option::Some(x)));
    }
});

verus! {

pub trait RwLockPredicate<V>: Sized {
    spec fn inv(self, v: V) -> bool;
}

impl<V> RwLockPredicate<V> for spec_fn(V) -> bool {
    open spec fn inv(self, v: V) -> bool {
        self(v)
    }
}

ghost struct InternalPred<V, Pred> {
    v: V,
    pred: Pred,
}

impl<V, Pred: RwLockPredicate<V>> InvariantPredicate<(Pred, CellId), PointsTo<V>> for InternalPred<
    V,
    Pred,
> {
    closed spec fn inv(k: (Pred, CellId), v: PointsTo<V>) -> bool {
        v.view().pcell == k.1 && v.view().value.is_Some() && k.0.inv(v.view().value.get_Some_0())
    }
}

struct_with_invariants_vstd!{
    /** A verified implementation of a reader-writer lock,
    implemented using atomics and a reference count.

    When constructed, you can provide an invariant via the `Pred` parameter,
    specifying the allowed values that can go in the lock.

    Note that this specification does *not* verify the absence of dead-locks.

    ### Examples

    On construction of a lock, we can specify an invariant for the object that goes inside.
    One way to do this is by providing a `spec_fn`, which implements the [`RwLockPredicate`]
    trait.

    ```rust,ignore
    fn example1() {
        // We can create a lock with an invariant: `v == 5 || v == 13`.
        // Thus only 5 or 13 can be stored in the lock.
        let lock = RwLock::<u64, spec_fn(u64) -> bool>::new(5, Ghost(|v| v == 5 || v == 13));

        let (val, write_handle) = lock.acquire_write();
        assert(val == 5 || val == 13);
        write_handle.release_write(13);

        let read_handle1 = lock.acquire_read();
        let read_handle2 = lock.acquire_read();

        // We can take multiple read handles at the same time:

        let val1 = read_handle1.borrow();
        let val2 = read_handle2.borrow();

        // RwLock has a lemma that both read handles have the same value:

        proof { ReadHandle::lemma_readers_match(&read_handle1, &read_handle2); }
        assert(*val1 == *val2);

        read_handle1.release_read();
        read_handle2.release_read();
    }
    ```

    It's often easier to implement the [`RwLockPredicate`] trait yourself. This way you can
    have a configurable predicate without needing to work with higher-order functions.

    ```rust,ignore
    struct FixedParity {
        pub parity: int,
    }

    impl RwLockPredicate<u64> for FixedParity {
        open spec fn inv(self, v: u64) -> bool {
            v % 2 == self.parity
        }
    }

    fn example2() {
        // Create a lock that can only store even integers
        let lock_even = RwLock::<u64, FixedParity>::new(20, Ghost(FixedParity { parity: 0 }));

        // Create a lock that can only store odd integers
        let lock_odd = RwLock::<u64, FixedParity>::new(23, Ghost(FixedParity { parity: 1 }));

        let read_handle_even = lock_even.acquire_read();
        let val_even = *read_handle_even.borrow();
        assert(val_even % 2 == 0);

        let read_handle_odd = lock_odd.acquire_read();
        let val_odd = *read_handle_odd.borrow();
        assert(val_odd % 2 == 1);
    }
    ```
    */

    pub struct RwLock<V, Pred: RwLockPredicate<V>> {
        cell: PCell<V>,
        exc: AtomicBool<_, RwLockToks::flag_exc<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>, _>,
        rc: AtomicU64<_, RwLockToks::flag_rc<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>, _>,

        inst: Tracked<RwLockToks::Instance<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>>,
        pred: Ghost<Pred>,
    }

    #[verifier::type_invariant]
    spec fn wf(&self) -> bool {
        invariant on exc with (inst) is (v: bool, g: RwLockToks::flag_exc<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>) {
            g@.instance == inst@
                && g@.value == v
        }

        invariant on rc with (inst) is (v: u64, g: RwLockToks::flag_rc<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>) {
            g@.instance == inst@
                && g@.value == v
        }

        predicate {
            self.inst@.k() == (self.pred@, self.cell.id())
        }
    }
}
//
/// Handle obtained for an exclusive write-lock from an [`RwLock`].
///
/// Note that this handle does not contain a reference to the lock-protected object;
/// ownership of the object is obtained separately from [`RwLock::acquire_write`].
/// This may be changed in the future.


pub struct WriteHandle<'a, V, Pred: RwLockPredicate<V>> {
    handle: Tracked<RwLockToks::writer<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>>,
    perm: Tracked<PointsTo<V>>,
    rwlock: &'a RwLock<V, Pred>,
}

/// Handle obtained for a shared read-lock from an [`RwLock`].
pub struct ReadHandle<'a, V, Pred: RwLockPredicate<V>> {
    handle: Tracked<RwLockToks::reader<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>>,
    rwlock: &'a RwLock<V, Pred>,
}

impl<'a, V, Pred: RwLockPredicate<V>> WriteHandle<'a, V, Pred> {
    #[verifier::type_invariant]
    spec fn wf_write_handle(self) -> bool {
        equal(self.perm@.view().pcell, self.rwlock.cell.id()) && self.perm@.view().value.is_None()
            && equal(self.handle@.view().instance, self.rwlock.inst@) && self.rwlock.wf()
    }

    pub closed spec fn rwlock(self) -> RwLock<V, Pred> {
        *self.rwlock
    }

    pub fn release_write(self, t: V)
        requires
            self.rwlock().inv(t),
    {
        proof {
            use_type_invariant(&self);
        }
        let WriteHandle { handle: Tracked(handle), perm: Tracked(mut perm), rwlock } = self;
        self.rwlock.cell.put(Tracked(&mut perm), t);

        atomic_with_ghost!(
            &rwlock.exc => store(false);
            ghost g =>
        {
            self.rwlock.inst.borrow().release_exc(perm, &mut g, perm, handle);
        });
    }
}

impl<'a, V, Pred: RwLockPredicate<V>> ReadHandle<'a, V, Pred> {
    #[verifier::type_invariant]
    spec fn wf_read_handle(self) -> bool {
        equal(self.handle@.view().instance, self.rwlock.inst@)
            && self.handle@.view().key.view().value.is_Some() && equal(
            self.handle@.view().key.view().pcell,
            self.rwlock.cell.id(),
        ) && self.handle@.view().count == 1 && self.rwlock.wf()
    }

    pub closed spec fn view(self) -> V {
        self.handle@.view().key.view().value.unwrap()
    }

    pub closed spec fn rwlock(self) -> RwLock<V, Pred> {
        *self.rwlock
    }

    /// Obtain a shared reference to the object contained in the lock.
    pub fn borrow<'b>(&'b self) -> (t: &'b V)
        ensures
            t == self.view(),
    {
        proof {
            use_type_invariant(self);
        }
        let tracked perm = self.rwlock.inst.borrow().read_guard(
            self.handle@.view().key,
            self.handle.borrow(),
        );
        self.rwlock.cell.borrow(Tracked(&perm))
    }

    pub proof fn lemma_readers_match(
        tracked read_handle1: &ReadHandle<V, Pred>,
        tracked read_handle2: &ReadHandle<V, Pred>,
    )
        requires
            read_handle1.rwlock() == read_handle2.rwlock(),
        ensures
            (equal(read_handle1.view(), read_handle2.view())),
    {
        use_type_invariant(read_handle1);
        use_type_invariant(read_handle2);
        read_handle1.rwlock.inst.borrow().read_match(
            read_handle1.handle@.view().key,
            read_handle2.handle@.view().key,
            &read_handle1.handle.borrow(),
            &read_handle2.handle.borrow(),
        );
    }

    pub fn release_read(self) {
        proof {
            use_type_invariant(&self);
        }
        let ReadHandle { handle: Tracked(handle), rwlock } = self;

        let _ =
            atomic_with_ghost!(
            &rwlock.rc => fetch_sub(1);
            ghost g =>
        {
            rwlock.inst.borrow().release_shared(handle.view().key, &mut g, handle);
        });
    }
}

impl<V, Pred: RwLockPredicate<V>> RwLock<V, Pred> {
    /// Predicate configured for this lock instance.
    pub closed spec fn pred(&self) -> Pred {
        self.pred@
    }

    /// Indicates if the value `v` can be stored in the lock. Per the definition,
    /// it depends on `[self.pred()]`, which is configured upon lock construction ([`RwLock::new`]).
    pub open spec fn inv(&self, t: V) -> bool {
        self.pred().inv(t)
    }

    pub fn new(t: V, Ghost(pred): Ghost<Pred>) -> (s: Self)
        requires
            pred.inv(t),
        ensures
            s.pred() == pred,
    {
        let (cell, Tracked(perm)) = PCell::<V>::new(t);

        let tracked (Tracked(inst), Tracked(flag_exc), Tracked(flag_rc), _, _, _, _) =
            RwLockToks::Instance::<
            (Pred, CellId),
            PointsTo<V>,
            InternalPred<V, Pred>,
        >::initialize_full((pred, cell.id()), perm, Option::Some(perm));
        let inst = Tracked(inst);

        let exc = AtomicBool::new(Ghost(inst), false, Tracked(flag_exc));
        let rc = AtomicU64::new(Ghost(inst), 0, Tracked(flag_rc));

        RwLock { cell, exc, rc, inst, pred: Ghost(pred) }
    }

    /// Acquires an exclusive write-lock. To release it, use [`WriteHandle::release_write`].
    pub fn acquire_write(&self) -> (ret: (V, WriteHandle<V, Pred>))
        ensures
            ({
                let t = ret.0;
                let write_handle = ret.1;
                &&write_handle.rwlock() == *self && self.inv(t)
            }),
    {
        proof {
            use_type_invariant(self);
        }
        let mut done = false;
        let tracked mut token: Option<
            RwLockToks::pending_writer<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>,
        > = Option::None;
        while !done
            invariant
                done ==> token.is_Some() && equal(token.get_Some_0().view().instance, self.inst@),
                self.wf(),
        {
            let result =
                atomic_with_ghost!(
                &self.exc => compare_exchange(false, true);
                returning res;
                ghost g =>
            {
                if res.is_Ok() {
                    token = Option::Some(self.inst.borrow().acquire_exc_start(&mut g));
                }
            });

            done =
            match result {
                Result::Ok(_) => true,
                _ => false,
            };
        }
        loop
            invariant
                token.is_Some() && equal(token.get_Some_0().view().instance, self.inst@),
                self.wf(),
        {
            let tracked mut perm_opt: Option<PointsTo<V>> = None;
            let tracked mut handle_opt: Option<
                RwLockToks::writer<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>,
            > = None;

            let result =
                atomic_with_ghost!(
                &self.rc => load();
                returning res;
                ghost g =>
            {
                if res == 0 {
                    let tracked tok = match token { Option::Some(t) => t, Option::None => proof_from_false() };
                    let tracked x = self.inst.borrow().acquire_exc_end(&g, tok);
                    token = None;
                    let tracked (_, Tracked(perm), Tracked(exc_handle)) = x;
                    perm_opt = Some(perm);
                    handle_opt = Some(exc_handle);
                }
            });

            if result == 0 {
                let tracked mut perm = match perm_opt {
                    Option::Some(t) => t,
                    Option::None => proof_from_false(),
                };
                let tracked handle = match handle_opt {
                    Option::Some(t) => t,
                    Option::None => proof_from_false(),
                };
                let t = self.cell.take(Tracked(&mut perm));
                let write_handle = WriteHandle {
                    perm: Tracked(perm),
                    handle: Tracked(handle),
                    rwlock: self,
                };
                return (t, write_handle);
            }
        }
    }

    /// Acquires a shared read-lock. To release it, use [`ReadHandle::release_read`].
    pub fn acquire_read(&self) -> (read_handle: ReadHandle<V, Pred>)
        ensures
            read_handle.rwlock() == *self,
            self.inv(read_handle.view()),
    {
        proof {
            use_type_invariant(self);
        }
        loop
            invariant
                self.wf(),
        {
            let val = atomic_with_ghost!(&self.rc => load(); ghost g => { });

            let tracked mut token: Option<
                RwLockToks::pending_reader<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>,
            > = Option::None;

            if val < 0xffff_ffff_ffff_ffff {
                let result =
                    atomic_with_ghost!(
                    &self.rc => compare_exchange(val, val + 1);
                    returning res;
                    ghost g =>
                {
                    if res.is_Ok() {
                        token = Option::Some(self.inst.borrow().acquire_read_start(&mut g));
                    }
                });

                match result {
                    Result::Ok(_) => {
                        let tracked mut handle_opt: Option<
                            RwLockToks::reader<(Pred, CellId), PointsTo<V>, InternalPred<V, Pred>>,
                        > = None;

                        let result =
                            atomic_with_ghost!(
                            &self.exc => load();
                            returning res;
                            ghost g =>
                        {
                            if res == false {
                                let tracked tok = match token { Option::Some(t) => t, Option::None => proof_from_false() };
                                let tracked x = self.inst.borrow().acquire_read_end(&g, tok);
                                token = None;
                                let tracked (_, Tracked(exc_handle)) = x;
                                handle_opt = Some(exc_handle);
                            }
                        });

                        if result == false {
                            let tracked handle = match handle_opt {
                                Option::Some(t) => t,
                                Option::None => proof_from_false(),
                            };
                            let read_handle = ReadHandle { handle: Tracked(handle), rwlock: self };
                            return read_handle;
                        } else {
                            let _ =
                                atomic_with_ghost!(
                                &self.rc => fetch_sub(1);
                                ghost g =>
                            {
                                let tracked tok = match token { Option::Some(t) => t, Option::None => proof_from_false() };
                                self.inst.borrow().acquire_read_abandon(&mut g, tok);
                            });
                        }
                    },
                    _ => {},
                }
            }
        }
    }

    /// Destroys the lock and returns the inner object.
    /// Note that this may deadlock if not all locks have been released.
    pub fn into_inner(self) -> (v: V)
        ensures
            self.inv(v),
    {
        let (v, _write_handle) = self.acquire_write();
        v
    }
}

} // verus!