1// SPDX-License-Identifier: Apache-2.0 OR MIT
23// Adapted from https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.7/crossbeam-utils/src/atomic/seq_lock.rs.
45use core::{
6 mem::ManuallyDrop,
7 sync::atomic::{self, Ordering},
8};
910use super::utils::Backoff;
1112// See mod.rs for details.
13#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
14pub(super) use core::sync::atomic::AtomicU64 as AtomicStamp;
15#[cfg(not(any(target_pointer_width = "16", target_pointer_width = "32")))]
16pub(super) use core::sync::atomic::AtomicUsize as AtomicStamp;
17#[cfg(not(any(target_pointer_width = "16", target_pointer_width = "32")))]
18pub(super) type Stamp = usize;
19#[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))]
20pub(super) type Stamp = u64;
2122// See mod.rs for details.
23pub(super) type AtomicChunk = AtomicStamp;
24pub(super) type Chunk = Stamp;
2526/// A simple stamped lock.
27pub(super) struct SeqLock {
28/// The current state of the lock.
29 ///
30 /// All bits except the least significant one hold the current stamp. When locked, the state
31 /// equals 1 and doesn't contain a valid stamp.
32state: AtomicStamp,
33}
3435impl SeqLock {
36#[inline]
37pub(super) const fn new() -> Self {
38Self { state: AtomicStamp::new(0) }
39 }
4041/// If not locked, returns the current stamp.
42 ///
43 /// This method should be called before optimistic reads.
44#[inline]
45pub(super) fn optimistic_read(&self) -> Option<Stamp> {
46let state = self.state.load(Ordering::Acquire);
47if state == 1 { None } else { Some(state) }
48 }
4950/// Returns `true` if the current stamp is equal to `stamp`.
51 ///
52 /// This method should be called after optimistic reads to check whether they are valid. The
53 /// argument `stamp` should correspond to the one returned by method `optimistic_read`.
54#[inline]
55pub(super) fn validate_read(&self, stamp: Stamp) -> bool {
56 atomic::fence(Ordering::Acquire);
57self.state.load(Ordering::Relaxed) == stamp
58 }
5960/// Grabs the lock for writing.
61#[inline]
62pub(super) fn write(&self) -> SeqLockWriteGuard<'_> {
63let mut backoff = Backoff::new();
64loop {
65let previous = self.state.swap(1, Ordering::Acquire);
6667if previous != 1 {
68 atomic::fence(Ordering::Release);
6970return SeqLockWriteGuard { lock: self, state: previous };
71 }
7273while self.state.load(Ordering::Relaxed) == 1 {
74 backoff.snooze();
75 }
76 }
77 }
78}
7980/// An RAII guard that releases the lock and increments the stamp when dropped.
81#[must_use]
82pub(super) struct SeqLockWriteGuard<'a> {
83/// The parent lock.
84lock: &'a SeqLock,
8586/// The stamp before locking.
87state: Stamp,
88}
8990impl SeqLockWriteGuard<'_> {
91/// Releases the lock without incrementing the stamp.
92#[inline]
93pub(super) fn abort(self) {
94// We specifically don't want to call drop(), since that's
95 // what increments the stamp.
96let this = ManuallyDrop::new(self);
9798// Restore the stamp.
99 //
100 // Release ordering for synchronizing with `optimistic_read`.
101this.lock.state.store(this.state, Ordering::Release);
102 }
103}
104105impl Drop for SeqLockWriteGuard<'_> {
106#[inline]
107fn drop(&mut self) {
108// Release the lock and increment the stamp.
109 //
110 // Release ordering for synchronizing with `optimistic_read`.
111self.lock.state.store(self.state.wrapping_add(2), Ordering::Release);
112 }
113}
114115#[cfg(test)]
116mod tests {
117use super::SeqLock;
118119#[test]
120fn smoke() {
121let lock = SeqLock::new();
122let before = lock.optimistic_read().unwrap();
123assert!(lock.validate_read(before));
124 {
125let _guard = lock.write();
126 }
127assert!(!lock.validate_read(before));
128let after = lock.optimistic_read().unwrap();
129assert_ne!(before, after);
130 }
131132#[test]
133fn test_abort() {
134let lock = SeqLock::new();
135let before = lock.optimistic_read().unwrap();
136 {
137let guard = lock.write();
138 guard.abort();
139 }
140let after = lock.optimistic_read().unwrap();
141assert_eq!(before, after, "aborted write does not update the stamp");
142 }
143}