Skip to main content

kovan_stm/
lib.rs

1#![doc(
2    html_logo_url = "https://raw.githubusercontent.com/vertexclique/kovan/master/art/kovan-square.svg"
3)]
4//! High-performance STM using Kovan for memory reclamation.
5//!
6//! # Architecture
7//!
8//! This STM uses a TL2-style (Transactional Locking II) algorithm with a global
9//! version clock.
10//!
11//! - **Reads**: Optimistic. No locks are acquired. Validity is checked via versioning.
12//!   Memory safety is guaranteed by Kovan's safe memory reclamation.
13//! - **Writes**: Buffered locally. Locks are acquired only during the commit phase.
14//! - **Reclamation**: Old data versions are passed to Kovan's `retire` mechanism.
15
16extern crate alloc;
17
18mod errors;
19mod node;
20mod transaction;
21mod var;
22
23pub use errors::StmError;
24pub use transaction::Transaction;
25pub use var::TVar;
26
27use kovan::pin;
28use std::sync::atomic::AtomicU64;
29
30/// The STM engine containing global state (like the version clock).
31pub struct Stm {
32    /// Global version clock.
33    /// Even numbers represent stable timestamps.
34    /// Odd numbers are not used for global clock, but typically indicate locked states in vars.
35    global_clock: AtomicU64,
36}
37
38impl Stm {
39    /// Create a new STM engine instance.
40    pub const fn new() -> Self {
41        Self {
42            global_clock: AtomicU64::new(0),
43        }
44    }
45}
46
47impl Default for Stm {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53impl Stm {
54    /// Execute a closure atomically.
55    ///
56    /// This function handles transaction retries automatically.
57    ///
58    /// DANGER AHEAD: Don't use IO bound operations inside the closure. It will block the entire STM.
59    /// They might be retried multiple times, which is not what you may want for IO bound operations.
60    ///
61    /// # Panics
62    ///
63    /// If the closure returns an error other than [`StmError::Retry`] (a
64    /// [`StmError::User`]): [`try_atomically`](Self::try_atomically) answers it
65    /// instead.
66    ///
67    /// # Example
68    ///
69    /// ```
70    /// use kovan_stm::Stm;
71    /// let stm = Stm::new();
72    /// let var = stm.tvar(10);
73    ///
74    /// stm.atomically(|tx| {
75    ///     let val = tx.load(&var)?;
76    ///     tx.store(&var, val + 1)?;
77    ///     Ok(())
78    /// });
79    /// ```
80    pub fn atomically<F, T>(&self, f: F) -> T
81    where
82        F: FnMut(&mut Transaction) -> Result<T, StmError>,
83    {
84        match self.try_atomically(f) {
85            Ok(result) => result,
86            Err(e) => panic!("Transaction failed with error: {:?}", e),
87        }
88    }
89
90    /// Execute a closure atomically, answering the error it returns.
91    ///
92    /// As [`atomically`](Self::atomically): a conflict or an
93    /// [`StmError::Retry`] runs the closure again; any other error (a
94    /// [`StmError::User`]) rolls the transaction back (its rollback hooks run,
95    /// nothing it stored is published) and is returned.
96    ///
97    /// # Example
98    ///
99    /// ```
100    /// use kovan_stm::{Stm, StmError};
101    /// let stm = Stm::new();
102    /// let balance = stm.tvar(5);
103    ///
104    /// let withdrawn = stm.try_atomically(|tx| {
105    ///     let b = tx.load(&balance)?;
106    ///     if b < 10 {
107    ///         return Err(StmError::User("insufficient funds".into()));
108    ///     }
109    ///     tx.store(&balance, b - 10)?;
110    ///     Ok(b - 10)
111    /// });
112    /// assert!(matches!(withdrawn, Err(StmError::User(_))));
113    /// assert_eq!(stm.atomically(|tx| tx.load(&balance)), 5);
114    /// ```
115    pub fn try_atomically<F, T>(&self, mut f: F) -> Result<T, StmError>
116    where
117        F: FnMut(&mut Transaction) -> Result<T, StmError>,
118    {
119        // Commits that failed in a row: each waits a little longer before the
120        // next attempt, so transactions that keep meeting on a hot variable
121        // stop aborting each other at full speed.
122        #[cfg(not(feature = "shuttle"))]
123        let mut conflicts = 0u32;
124        loop {
125            let committed = {
126                // 1. Enter Kovan critical section
127                // This ensures any pointer we read from Kovan Atomics remains valid
128                // throughout the transaction attempt.
129                let guard = pin();
130
131                // 2. Create transaction context
132                let mut tx = Transaction::new(self, &guard);
133
134                // 3. Run user logic
135                match f(&mut tx) {
136                    // 4. Attempt to commit
137                    Ok(result) => tx.commit().then_some(result),
138                    // User explicitly asked to retry
139                    Err(StmError::Retry) => {
140                        drop(tx);
141                        drop(guard);
142                        // In a real scheduler, we might backoff/park here.
143                        // Under shuttle this yield must be the scheduler's
144                        // own (see the fairness note below); a real
145                        // `std::thread::yield_now()` is a no-op for
146                        // shuttle's cooperative scheduler (every other task
147                        // is genuinely parked, not merely de-prioritized).
148                        #[cfg(feature = "shuttle")]
149                        shuttle::hint::spin_loop();
150                        #[cfg(not(feature = "shuttle"))]
151                        std::thread::yield_now();
152                        continue;
153                    }
154                    // A user error: rolled back (the transaction's drop runs
155                    // its rollback hooks), and answered.
156                    Err(e) => return Err(e),
157                }
158            };
159            if let Some(result) = committed {
160                return Ok(result);
161            }
162            // Commit failed (conflict): retry, the guard already dropped.
163            //
164            // vertexia: under shuttle, an explicit yield here (not
165            // just the instrumented `version_lock` reads/CASes the
166            // next attempt performs) is required for the scheduler
167            // to guarantee the *other* side of the conflict a turn.
168            // Without it, PCT/random can keep re-selecting this
169            // thread's retries indefinitely under an unlucky
170            // priority draw -- both sides livelocking each other
171            // out until shuttle's step budget is exhausted
172            // ("exceeded max_steps bound", an unfair schedule, not
173            // a real bug -- see `kovan-map`'s `resize_spin_hint` for
174            // the identical failure mode and full reasoning).
175            #[cfg(feature = "shuttle")]
176            shuttle::hint::spin_loop();
177            #[cfg(not(feature = "shuttle"))]
178            back_off(&mut conflicts);
179        }
180    }
181
182    /// Create a new transactional variable managed by this STM.
183    pub fn tvar<T: Send + Sync + 'static>(&self, data: T) -> TVar<T> {
184        TVar::new(data)
185    }
186}
187
188/// Global singleton for easier usage if preferred, though explicitly passing Stm is cleaner.
189pub static STM: Stm = Stm::new();
190
191/// Convenience helper using the global STM instance.
192pub fn atomically<F, T>(f: F) -> T
193where
194    F: FnMut(&mut Transaction) -> Result<T, StmError>,
195{
196    STM.atomically(f)
197}
198
199/// [`Stm::try_atomically`] on the global STM instance.
200pub fn try_atomically<F, T>(f: F) -> Result<T, StmError>
201where
202    F: FnMut(&mut Transaction) -> Result<T, StmError>,
203{
204    STM.try_atomically(f)
205}
206
207/// The wait after the `conflicts`-th failed commit in a row: spins that
208/// double up to 64, then a yield of the thread.
209#[cfg(not(feature = "shuttle"))]
210fn back_off(conflicts: &mut u32) {
211    if *conflicts < 6 {
212        for _ in 0..1u32 << *conflicts {
213            core::hint::spin_loop();
214        }
215        *conflicts += 1;
216    } else {
217        std::thread::yield_now();
218    }
219}