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
// MIT/Apache2 License

//! Implementation of a basic spin-based RwLock.
//! 
//! ## This is now deprecated in favor of [`spin-rs`].
//! 
//! [`spin-rs`]: https://crates.io/crates/spin

#![no_std]
#![warn(clippy::pedantic)]
#![allow(clippy::same_item_push)]
#![deprecated(since = "0.2.4", note = "Use spin-rs instead")]

#[cfg(any(test, loom))]
extern crate std;

use lock_api::{
    GuardSend, RawRwLock, RawRwLockDowngrade, RawRwLockUpgrade, RwLock as LARwLock,
    RwLockReadGuard as LARwLockReadGuard, RwLockUpgradableReadGuard as LARwLockUpgradableReadGuard,
    RwLockWriteGuard as LARwLockWriteGuard,
};

#[cfg(not(loom))]
use core::{
    hint::spin_loop,
    sync::atomic::{AtomicUsize, Ordering},
};
#[cfg(loom)]
use loom::{
    hint::spin_loop,
    sync::atomic::{AtomicUsize, Ordering},
};
#[cfg(loom)]
use once_cell::sync::OnceCell;

#[cfg(not(loom))]
/// Raw spinlock rwlock, wrapped in the `lock_api` RwLock struct.
pub struct RawRwSpinlock(AtomicUsize);

#[cfg(loom)]
/// Raw spinlock rwlock, wrapped in the `lock_api` RwLock struct.
pub struct RawRwSpinlock(OnceCell<AtomicUsize>);

#[cfg(not(loom))]
impl RawRwSpinlock {
    #[inline]
    fn ulock(&self) -> &AtomicUsize {
        &self.0
    }
}

#[cfg(loom)]
impl RawRwSpinlock {
    #[inline]
    fn ulock(&self) -> &AtomicUsize {
        self.0.get_or_init(|| AtomicUsize::new(0))
    }
}

// flags stored in the usize struct
const READER: usize = 1 << 2;
const UPGRADED: usize = 1 << 1;
const WRITER: usize = 1 << 0;

unsafe impl RawRwLock for RawRwSpinlock {
    #[cfg(not(loom))]
    const INIT: RawRwSpinlock = RawRwSpinlock(AtomicUsize::new(0));
    #[cfg(loom)]
    const INIT: RawRwSpinlock = RawRwSpinlock(OnceCell::new());

    type GuardMarker = GuardSend;

    fn lock_shared(&self) {
        while !self.try_lock_shared() {
            spin_loop()
        }
    }

    fn try_lock_shared(&self) -> bool {
        let value = self.ulock().fetch_add(READER, Ordering::Acquire);

        if value & (WRITER | UPGRADED) != 0 {
            self.ulock().fetch_sub(READER, Ordering::Relaxed);
            false
        } else {
            true
        }
    }

    fn try_lock_exclusive(&self) -> bool {
        self.ulock()
            .compare_exchange(0, WRITER, Ordering::Acquire, Ordering::Relaxed)
            .is_ok()
    }

    fn lock_exclusive(&self) {
        loop {
            match self.ulock().compare_exchange_weak(
                0,
                WRITER,
                Ordering::Acquire,
                Ordering::Relaxed,
            ) {
                Ok(_) => return,
                Err(_) => spin_loop(),
            }
        }
    }

    unsafe fn unlock_shared(&self) {
        self.ulock().fetch_sub(READER, Ordering::Release);
    }

    unsafe fn unlock_exclusive(&self) {
        self.ulock()
            .fetch_and(!(WRITER | UPGRADED), Ordering::Release);
    }
}

unsafe impl RawRwLockUpgrade for RawRwSpinlock {
    fn lock_upgradable(&self) {
        while !self.try_lock_upgradable() {
            spin_loop()
        }
    }

    fn try_lock_upgradable(&self) -> bool {
        self.ulock().fetch_or(UPGRADED, Ordering::Acquire) & (WRITER | UPGRADED) == 0
    }

    unsafe fn try_upgrade(&self) -> bool {
        self.ulock()
            .compare_exchange(UPGRADED, WRITER, Ordering::Acquire, Ordering::Relaxed)
            .is_ok()
    }

    unsafe fn upgrade(&self) {
        loop {
            match self.ulock().compare_exchange_weak(
                UPGRADED,
                WRITER,
                Ordering::Acquire,
                Ordering::Relaxed,
            ) {
                Ok(_) => return,
                Err(_) => spin_loop(),
            }
        }
    }

    unsafe fn unlock_upgradable(&self) {
        self.ulock().fetch_sub(UPGRADED, Ordering::AcqRel);
    }
}

unsafe impl RawRwLockDowngrade for RawRwSpinlock {
    unsafe fn downgrade(&self) {
        self.ulock().fetch_add(READER, Ordering::Acquire);
        self.unlock_exclusive();
    }
}

/// A read-write lock that uses a spinlock internally.
pub type RwLock<T> = LARwLock<RawRwSpinlock, T>;
/// A read guard for the read-write lock.
pub type RwLockReadGuard<'a, T> = LARwLockReadGuard<'a, RawRwSpinlock, T>;
/// A write guard fo the read-write lock.
pub type RwLockWriteGuard<'a, T> = LARwLockWriteGuard<'a, RawRwSpinlock, T>;
/// An upgradable read guard for the read-write lock.
pub type RwLockUpgradableReadGuard<'a, T> = LARwLockUpgradableReadGuard<'a, RawRwSpinlock, T>;

#[test]
fn basics() {
    let rwlock = RwLock::new(8);
    assert_eq!(*rwlock.read(), 8);
    *rwlock.write() = 7;
    assert_eq!(*rwlock.read(), 7);
}

#[cfg(test)]
mod tests {
    use super::{RwLock, RwLockUpgradableReadGuard};

    #[cfg(loom)]
    use loom::thread;
    #[cfg(not(loom))]
    use std::thread;

    use std::{sync::Arc, vec::Vec};

    // test multiple reads
    fn multiread_kernel() {
        let rwlock = Arc::new(RwLock::new(7));
        let mut joiners = Vec::new();
        for _ in 0..1 {
            let rclone = rwlock.clone();
            joiners.push(thread::spawn(move || {
                let lock = rclone.read();
                assert_eq!(*lock, 7);
            }));
        }

        joiners.into_iter().for_each(|j| j.join().unwrap());
    }

    #[cfg(loom)]
    #[test]
    fn multiread() {
        loom::model(|| multiread_kernel());
    }

    #[cfg(not(loom))]
    #[test]
    fn multiread() {
        multiread_kernel();
    }

    // test multiple writes
    fn multiwrite_kernel() {
        let rwlock = Arc::new(RwLock::new(0));
        let mut joiners = Vec::new();
        for _ in 0..2 {
            let rclone = rwlock.clone();
            joiners.push(thread::spawn(move || {
                let mut lock = rclone.write();
                *lock += 1;
            }));
        }

        joiners.into_iter().for_each(|j| j.join().unwrap());
        assert_eq!(*rwlock.read(), 2);
    }

    #[cfg(loom)]
    #[test]
    fn multiwrite() {
        loom::model(|| multiwrite_kernel());
    }

    #[cfg(not(loom))]
    #[test]
    fn multiwrite() {
        multiwrite_kernel();
    }

    // test upgrading
    fn upgrade_kernel() {
        let rwlock = Arc::new(RwLock::new((false, 0)));
        let mut joiners = Vec::new();
        for i in 0..2 {
            let rclone = rwlock.clone();
            joiners.push(thread::spawn(move || {
                let lock = RwLock::upgradable_read(&rclone);

                // even numbers just read the lock, determine the first element is false, then return
                if i & 1 == 0 {
                    assert_eq!(lock.0, false);
                } else {
                    // odd numbers increment the number
                    let mut lock = RwLockUpgradableReadGuard::upgrade(lock);
                    lock.1 += 1;
                }
            }));
        }

        joiners.into_iter().for_each(|j| j.join().unwrap());
        assert_eq!(rwlock.read().1, 1);
    }

    #[cfg(loom)]
    #[test]
    fn upgrade() {
        loom::model(|| upgrade_kernel());
    }

    #[cfg(not(loom))]
    #[test]
    fn upgrade() {
        upgrade_kernel();
    }
}