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
//! Naive implementation of spin based locking mechanisms
//!
//! This module provides implementations for locking mechanisms required.
//!
//! # Acknowledgement
//!
//! This implementation is largely inspired by the book
//! ["Rust Atomics and Locks" by Mara Bos](https://marabos.nl/atomics/).

use core::cell::UnsafeCell;
use core::hint::{self};
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicU32, Ordering};

/// A spinlock based, read-write lock which favours writers over readers
///
/// # Properties
///
/// - Read-write semantics allow for multiple readers at the same time, but require exclusive access
///   for a writer
/// - Spin based, e.g. waiting for the lock wastes CPU cycles in a busy loop
///    - This design however enables an implementation independent of operating system features like
///      condition variables, the only requirement are 32 bit atomics in the ISA
/// - Biased towards writes: once a writer waits for the lock, all new reader wait until that writer
///   got access
pub struct RwSpinLock<T> {
    /// The inner data protected by this lock
    inner: UnsafeCell<T>,

    /// Lock state (on ambiguity, the state closer to the top takes precedence)
    ///
    /// - `0` means there are no readers nor any writer
    /// - `u32::MAX` means there is a single active writer
    /// - `state % 2 == 0` means there are `state / 2` active readers
    /// - `state % 2 != 0` means there are `(state - 1) / 2` active readers and at least one waiting
    ///    writer
    state: AtomicU32,
}

impl<T> RwSpinLock<T> {
    /// Create a new instance of self, wrapping the `value` of type `T`
    pub fn new(value: T) -> Self {
        Self {
            inner: UnsafeCell::new(value),
            state: AtomicU32::new(0),
        }
    }

    // Get read access to the value wrapped in this [`RwSpinLock`]
    pub fn read(&self) -> ReadLockGuard<T> {
        // get the current state
        let mut s = self.state.load(Ordering::Relaxed); // ordering by the book

        loop {
            // s is even, so there are maybe active readers but no active or waiting writer
            // -> reader can acquire read guard (as long as an overflow is avoided)
            if s % 2 == 0 && s < u32::MAX - 2 {
                match self.state.compare_exchange_weak(
                    s,
                    s + 2,
                    Ordering::Acquire,
                    Ordering::Relaxed,
                ) {
                    Ok(_) => return ReadLockGuard { lock: self },
                    Err(update_s) => s = update_s,
                }
            }

            // there is one active (`s == u32::MAX`) or at least one waiting (otherwise) writer
            // -> spin, re-load s and try again
            if s % 2 == 1 {
                hint::spin_loop();
                s = self.state.load(Ordering::Relaxed); // ordering by the book
            }
        }
    }

    // Get write access to the value wrapped in this [`RwSpinLock`]
    pub fn write(&self) -> WriteLockGuard<T> {
        let mut s = self.state.load(Ordering::Relaxed);

        loop {
            // there is no active reader (`s >= 2 && s % 2 == 0`) or writer (`s == u32::MAX`)
            if s <= 1 {
                match self
                    .state
                    .compare_exchange(s, u32::MAX, Ordering::Acquire, Ordering::Relaxed)
                {
                    Ok(_) => return WriteLockGuard { lock: self },
                    Err(updated_s) => {
                        s = updated_s;
                        continue;
                    }
                }
            }

            // announce that a writer is waiting if this is not yet announced
            if s % 2 == 0 {
                match self
                    .state
                    // ordering by the book
                    .compare_exchange(s, s + 1, Ordering::Relaxed, Ordering::Relaxed)
                {
                    Ok(_) => {}
                    Err(updated_s) => {
                        s = updated_s;
                        continue;
                    }
                }
            }

            // wait was announced, there are still active readers
            // -> spin, re-load s, continue from the start of the lop
            hint::spin_loop();
            s = self.state.load(Ordering::Relaxed);
        }
    }
}

unsafe impl<T> Sync for RwSpinLock<T> where T: Send + Sync {}

/// Read guard for the [`RwSpinLock`]
pub struct ReadLockGuard<'a, T> {
    lock: &'a RwSpinLock<T>,
}

impl<T> Deref for ReadLockGuard<'_, T> {
    type Target = T;
    fn deref(&self) -> &T {
        unsafe { &*self.lock.inner.get() }
    }
}

impl<T> Drop for ReadLockGuard<'_, T> {
    fn drop(&mut self) {
        self.lock.state.fetch_sub(2, Ordering::Release); // ordering by the book
    }
}

/// Write guard for the [`RwSpinLock`]
pub struct WriteLockGuard<'a, T> {
    lock: &'a RwSpinLock<T>,
}

impl<T> Deref for WriteLockGuard<'_, T> {
    type Target = T;
    fn deref(&self) -> &T {
        unsafe { &*self.lock.inner.get() }
    }
}

impl<T> DerefMut for WriteLockGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.lock.inner.get() }
    }
}

impl<T> Drop for WriteLockGuard<'_, T> {
    fn drop(&mut self) {
        self.lock.state.store(0, Ordering::Release); // ordering by the book
    }
}