Skip to main content

std/sys/sync/rwlock/
futex.rs

1use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release};
2use crate::sys::sync::futex::{Futex, Primitive, futex_wait, futex_wake, futex_wake_all};
3
4pub struct RwLock {
5    // The state consists of a 30-bit reader counter, a 'readers waiting' flag, and a 'writers waiting' flag.
6    // Bits 0..30:
7    //   0: Unlocked
8    //   1..=0x3FFF_FFFE: Locked by N readers
9    //   0x3FFF_FFFF: Write locked
10    // Bit 30: Readers are waiting on this futex.
11    // Bit 31: Writers are waiting on the writer_notify futex.
12    state: Futex,
13    // The 'condition variable' to notify writers through.
14    // Incremented on every signal.
15    writer_notify: Futex,
16    // The writers going to sleep on `writer_notify`, if this platform needs them counted.
17    blocked_writers: BlockedWriters,
18}
19
20const READ_LOCKED: Primitive = 1;
21const MASK: Primitive = (1 << 30) - 1;
22const WRITE_LOCKED: Primitive = MASK;
23const DOWNGRADE: Primitive = READ_LOCKED.wrapping_sub(WRITE_LOCKED); // READ_LOCKED - WRITE_LOCKED
24const MAX_READERS: Primitive = MASK - 1;
25const READERS_WAITING: Primitive = 1 << 30;
26const WRITERS_WAITING: Primitive = 1 << 31;
27
28#[inline]
29fn is_unlocked(state: Primitive) -> bool {
30    state & MASK == 0
31}
32
33#[inline]
34fn is_write_locked(state: Primitive) -> bool {
35    state & MASK == WRITE_LOCKED
36}
37
38#[inline]
39fn has_readers_waiting(state: Primitive) -> bool {
40    state & READERS_WAITING != 0
41}
42
43#[inline]
44fn has_writers_waiting(state: Primitive) -> bool {
45    state & WRITERS_WAITING != 0
46}
47
48#[inline]
49fn is_read_lockable(state: Primitive) -> bool {
50    // This also returns false if the counter could overflow if we tried to read lock it.
51    //
52    // We don't allow read-locking if there's readers waiting, even if the lock is unlocked
53    // and there's no writers waiting. The only situation when this happens is after unlocking,
54    // at which point the unlocking thread might be waking up writers, which have priority over readers.
55    // The unlocking thread will clear the readers waiting bit and wake up readers, if necessary.
56    state & MASK < MAX_READERS && !has_readers_waiting(state) && !has_writers_waiting(state)
57}
58
59#[inline]
60fn is_read_lockable_after_wakeup(state: Primitive) -> bool {
61    // We make a special case for checking if we can read-lock _after_ a reader thread that went to
62    // sleep has been woken up by a call to `downgrade`.
63    //
64    // `downgrade` will wake up all readers and place the lock in read mode. Thus, there should be
65    // no readers waiting and the lock should be read-locked (not write-locked or unlocked).
66    //
67    // Note that we do not check if any writers are waiting. This is because a call to `downgrade`
68    // implies that the caller wants other readers to read the value protected by the lock. If we
69    // did not allow readers to acquire the lock before writers after a `downgrade`, then only the
70    // original writer would be able to read the value, thus defeating the purpose of `downgrade`.
71    state & MASK < MAX_READERS
72        && !has_readers_waiting(state)
73        && !is_write_locked(state)
74        && !is_unlocked(state)
75}
76
77#[inline]
78fn has_reached_max_readers(state: Primitive) -> bool {
79    state & MASK == MAX_READERS
80}
81
82impl RwLock {
83    #[inline]
84    pub const fn new() -> Self {
85        Self {
86            state: Futex::new(0),
87            writer_notify: Futex::new(0),
88            blocked_writers: BlockedWriters::new(),
89        }
90    }
91
92    #[inline]
93    pub fn try_read(&self) -> bool {
94        self.state
95            .try_update(Acquire, Relaxed, |s| is_read_lockable(s).then(|| s + READ_LOCKED))
96            .is_ok()
97    }
98
99    #[inline]
100    pub fn read(&self) {
101        let state = self.state.load(Relaxed);
102        if !is_read_lockable(state)
103            || self
104                .state
105                .compare_exchange_weak(state, state + READ_LOCKED, Acquire, Relaxed)
106                .is_err()
107        {
108            self.read_contended();
109        }
110    }
111
112    /// # Safety
113    ///
114    /// The `RwLock` must be read-locked (N readers) in order to call this.
115    #[inline]
116    pub unsafe fn read_unlock(&self) {
117        let state = self.state.fetch_sub(READ_LOCKED, Release) - READ_LOCKED;
118
119        // It's impossible for a reader to be waiting on a read-locked RwLock,
120        // except if there is also a writer waiting.
121        if true {
    if !(!has_readers_waiting(state) || has_writers_waiting(state)) {
        ::core::panicking::panic("assertion failed: !has_readers_waiting(state) || has_writers_waiting(state)")
    };
};debug_assert!(!has_readers_waiting(state) || has_writers_waiting(state));
122
123        // Wake up a writer if we were the last reader and there's a writer waiting.
124        if is_unlocked(state) && has_writers_waiting(state) {
125            self.wake_writer_or_readers(state);
126        }
127    }
128
129    #[cold]
130    fn read_contended(&self) {
131        let mut has_slept = false;
132        let mut state = self.spin_read();
133
134        loop {
135            // If we have just been woken up, first check for a `downgrade` call.
136            // Otherwise, if we can read-lock it, lock it.
137            if (has_slept && is_read_lockable_after_wakeup(state)) || is_read_lockable(state) {
138                match self.state.compare_exchange_weak(state, state + READ_LOCKED, Acquire, Relaxed)
139                {
140                    Ok(_) => return, // Locked!
141                    Err(s) => {
142                        state = s;
143                        continue;
144                    }
145                }
146            }
147
148            // Check for overflow.
149            if !!has_reached_max_readers(state) {
    {
        ::core::panicking::panic_fmt(format_args!("too many active read locks on RwLock"));
    }
};assert!(!has_reached_max_readers(state), "too many active read locks on RwLock");
150
151            // Make sure the readers waiting bit is set before we go to sleep.
152            if !has_readers_waiting(state) {
153                if let Err(s) =
154                    self.state.compare_exchange(state, state | READERS_WAITING, Relaxed, Relaxed)
155                {
156                    state = s;
157                    continue;
158                }
159            }
160
161            // Wait for the state to change.
162            futex_wait(&self.state, state | READERS_WAITING, None);
163            has_slept = true;
164
165            // Spin again after waking up.
166            state = self.spin_read();
167        }
168    }
169
170    #[inline]
171    pub fn try_write(&self) -> bool {
172        self.state
173            .try_update(Acquire, Relaxed, |s| is_unlocked(s).then(|| s + WRITE_LOCKED))
174            .is_ok()
175    }
176
177    #[inline]
178    pub fn write(&self) {
179        if self.state.compare_exchange_weak(0, WRITE_LOCKED, Acquire, Relaxed).is_err() {
180            self.write_contended();
181        }
182    }
183
184    /// # Safety
185    ///
186    /// The `RwLock` must be write-locked (single writer) in order to call this.
187    #[inline]
188    pub unsafe fn write_unlock(&self) {
189        let state = self.state.fetch_sub(WRITE_LOCKED, Release) - WRITE_LOCKED;
190
191        if true {
    if !is_unlocked(state) {
        ::core::panicking::panic("assertion failed: is_unlocked(state)")
    };
};debug_assert!(is_unlocked(state));
192
193        if has_writers_waiting(state) || has_readers_waiting(state) {
194            self.wake_writer_or_readers(state);
195        }
196    }
197
198    /// # Safety
199    ///
200    /// The `RwLock` must be write-locked (single writer) in order to call this.
201    #[inline]
202    pub unsafe fn downgrade(&self) {
203        // Removes all write bits and adds a single read bit.
204        let state = self.state.fetch_add(DOWNGRADE, Release);
205        if true {
    if !is_write_locked(state) {
        {
            ::core::panicking::panic_fmt(format_args!("RwLock must be write locked to call `downgrade`"));
        }
    };
};debug_assert!(is_write_locked(state), "RwLock must be write locked to call `downgrade`");
206
207        if has_readers_waiting(state) {
208            // Since we had the exclusive lock, nobody else can unset this bit.
209            self.state.fetch_sub(READERS_WAITING, Relaxed);
210            futex_wake_all(&self.state);
211        }
212    }
213
214    #[cold]
215    fn write_contended(&self) {
216        let mut state = self.spin_write();
217
218        let mut other_writers_waiting = 0;
219
220        loop {
221            // If it's unlocked, we try to lock it.
222            if is_unlocked(state) {
223                match self.state.compare_exchange_weak(
224                    state,
225                    state | WRITE_LOCKED | other_writers_waiting,
226                    Acquire,
227                    Relaxed,
228                ) {
229                    Ok(_) => return, // Locked!
230                    Err(s) => {
231                        state = s;
232                        continue;
233                    }
234                }
235            }
236
237            // Set the waiting bit indicating that we're waiting on it.
238            if !has_writers_waiting(state) {
239                if let Err(s) =
240                    self.state.compare_exchange(state, state | WRITERS_WAITING, Relaxed, Relaxed)
241                {
242                    state = s;
243                    continue;
244                }
245            }
246
247            // Other writers might be waiting now too, so we should make sure
248            // we keep that bit on once we manage lock it.
249            other_writers_waiting = WRITERS_WAITING;
250
251            // Examine the notification counter before we check if `state` has changed,
252            // to make sure we don't miss any notifications.
253            let seq = self.writer_notify.load(Acquire);
254
255            // Don't go to sleep if the lock has become available,
256            // or if the writers waiting bit is no longer set.
257            state = self.state.load(Relaxed);
258            if is_unlocked(state) || !has_writers_waiting(state) {
259                continue;
260            }
261
262            // Wait for the state to change.
263            self.blocked_writers.wait(&self.writer_notify, seq);
264
265            // Spin again after waking up.
266            state = self.spin_write();
267        }
268    }
269
270    /// Wakes up waiting threads after unlocking.
271    ///
272    /// If both are waiting, this will wake up only one writer, but will fall
273    /// back to waking up readers if there was no writer to wake up.
274    #[cold]
275    fn wake_writer_or_readers(&self, mut state: Primitive) {
276        if !is_unlocked(state) {
    ::core::panicking::panic("assertion failed: is_unlocked(state)")
};assert!(is_unlocked(state));
277
278        // The readers waiting bit might be turned on at any point now,
279        // since readers will block when there's anything waiting.
280        // Writers will just lock the lock though, regardless of the waiting bits,
281        // so we don't have to worry about the writer waiting bit.
282        //
283        // If the lock gets locked in the meantime, we don't have to do
284        // anything, because then the thread that locked the lock will take
285        // care of waking up waiters when it unlocks.
286
287        // If only writers are waiting, wake one of them up.
288        if state == WRITERS_WAITING {
289            match self.state.compare_exchange(state, 0, Relaxed, Relaxed) {
290                Ok(_) => {
291                    self.wake_writer();
292                    return;
293                }
294                Err(s) => {
295                    // Maybe some readers are now waiting too. So, continue to the next `if`.
296                    state = s;
297                }
298            }
299        }
300
301        // If both writers and readers are waiting, leave the readers waiting
302        // and only wake up one writer.
303        if state == READERS_WAITING + WRITERS_WAITING {
304            // Acquire, so that `wake_writer` can't see a `blocked_writers` count from
305            // before the unlock of a writer that has already left.
306            if self.state.compare_exchange(state, READERS_WAITING, Acquire, Relaxed).is_err() {
307                // The lock got locked. Not our problem anymore.
308                return;
309            }
310            if self.wake_writer() {
311                return;
312            }
313            // No writers were actually blocked on futex_wait, so we continue
314            // to wake up readers instead, since we can't be sure if we notified a writer.
315            state = READERS_WAITING;
316        }
317
318        // If readers are waiting, wake them all up.
319        if state == READERS_WAITING {
320            if self.state.compare_exchange(state, 0, Relaxed, Relaxed).is_ok() {
321                futex_wake_all(&self.state);
322            }
323        }
324    }
325
326    /// This wakes one writer and returns true if we woke up a writer that was
327    /// blocked on futex_wait, or if `BlockedWriters` says such a writer may exist.
328    ///
329    /// If this returns false, it might still be the case that we notified a
330    /// writer that was about to go to sleep.
331    fn wake_writer(&self) -> bool {
332        self.writer_notify.fetch_add(1, Release);
333        self.blocked_writers.wake(&self.writer_notify)
334        // Note that FreeBSD and DragonFlyBSD don't tell us whether they woke
335        // up any threads or not, and always return `false` here. That still
336        // results in correct behavior: it just means readers get woken up as
337        // well in case both readers and writers were waiting.
338    }
339
340    /// Spin for a while, but stop directly at the given condition.
341    #[inline]
342    fn spin_until(&self, f: impl Fn(Primitive) -> bool) -> Primitive {
343        let mut spin = 100; // Chosen by fair dice roll.
344        loop {
345            let state = self.state.load(Relaxed);
346            if f(state) || spin == 0 {
347                return state;
348            }
349            crate::hint::spin_loop();
350            spin -= 1;
351        }
352    }
353
354    #[inline]
355    fn spin_write(&self) -> Primitive {
356        // Stop spinning when it's unlocked or when there's waiting writers, to keep things somewhat fair.
357        self.spin_until(|state| is_unlocked(state) || has_writers_waiting(state))
358    }
359
360    #[inline]
361    fn spin_read(&self) -> Primitive {
362        // Stop spinning when it's unlocked or read locked, or when there's waiting threads.
363        self.spin_until(|state| {
364            !is_write_locked(state) || has_readers_waiting(state) || has_writers_waiting(state)
365        })
366    }
367}
368
369cfg_select! {
370    // `wake_writer` needs to know if it reached a writer, and `futex_wake` doesn't report that
371    // here, so we count the writers going to sleep instead. A counted writer hasn't retried the
372    // lock yet. It either takes the lock or finds it held, and only writers can lock while
373    // `READERS_WAITING` is set, so whoever holds the lock sees that bit when it unlocks.
374    target_os = "windows" => {
375        use crate::sync::atomic::{Atomic, AtomicU32};
376
377        // Thread IDs are 32-bit on Windows, so this can't overflow.
378        struct BlockedWriters(Atomic<u32>);
379
380        impl BlockedWriters {
381            #[inline]
382            const fn new() -> Self {
383                Self(AtomicU32::new(0))
384            }
385
386            #[inline]
387            fn wait(&self, futex: &Futex, expected: Primitive) {
388                self.0.fetch_add(1, Relaxed);
389                futex_wait(futex, expected, None);
390                self.0.fetch_sub(1, Relaxed);
391            }
392
393            #[inline]
394            fn wake(&self, futex: &Futex) -> bool {
395                // Read this first: the writer we wake takes itself off the count.
396                let blocked = self.0.load(Relaxed) != 0;
397                futex_wake(futex) || blocked
398            }
399        }
400    }
401    _ => {
402        struct BlockedWriters;
403
404        impl BlockedWriters {
405            #[inline]
406            const fn new() -> Self {
407                Self
408            }
409
410            #[inline]
411            fn wait(&self, futex: &Futex, expected: Primitive) {
412                futex_wait(futex, expected, None);
413            }
414
415            #[inline]
416            fn wake(&self, futex: &Futex) -> bool {
417                futex_wake(futex)
418            }
419        }
420    }
421}