rtsc 0.4.5

Real-time Synchronization Components
Documentation
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
use std::{
    sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering},
    thread,
    time::{Duration, Instant},
};

use linux_futex::{AsFutex as _, Futex, PiFutex, Private, TimedWaitError, WaitError};
use lock_api::{GuardSend, RawMutex as RawMutexTrait, RawMutexTimed};

use crate::condvar_api::{RawCondvar, WaitTimeoutResult};

thread_local! {
    #[allow(clippy::cast_possible_truncation)]
    static TID: libc::pid_t = unsafe { libc::syscall(libc::SYS_gettid) as i32 }
}

#[inline]
fn tid() -> libc::pid_t {
    TID.with(|it| *it)
}

/// Priority-inheritance based Condvar implementation for the priority-inheritance [`Mutex`].
#[derive(Default)]
pub struct Condvar {
    waiters: AtomicI32,
    fx: AtomicU32,
}

impl Condvar {
    /// Creates a new [`Condvar`]. Unlike traditional approach, a single Condvar can be used with
    /// any number of mutexes.
    pub const fn new() -> Self {
        Self {
            waiters: AtomicI32::new(0),
            fx: AtomicU32::new(0),
        }
    }

    /// Blocks the current thread until being notified. The mutex guard is unlocked before blocking
    #[inline]
    pub fn wait<T>(&self, mutex_guard: &mut MutexGuard<T>) {
        self.wait_with_timeout(mutex_guard, None);
    }

    /// Blocks the current thread until being notified or the timeout is reached. The mutex guard
    /// is unlocked before blocking
    #[inline]
    pub fn wait_for<T>(
        &self,
        mutex_guard: &mut MutexGuard<T>,
        timeout: Duration,
    ) -> WaitTimeoutResult {
        self.wait_with_timeout(mutex_guard, Some(timeout))
    }

    fn wait_with_timeout<T>(
        &self,
        mutex_guard: &mut MutexGuard<T>,
        timeout: Option<Duration>,
    ) -> WaitTimeoutResult {
        let mutex = unsafe { lock_api::MutexGuard::<'_, PiLock, T>::mutex(mutex_guard).raw() };
        macro_rules! unlock {
            () => {
                assert!(
                    self.waiters.fetch_add(1, Ordering::SeqCst) < i32::MAX,
                    "CRITICAL: too many waiters"
                );
                if mutex.is_locked() {
                    mutex.perform_unlock();
                }
            };
        }
        let fx: &Futex<Private> = self.fx.as_futex();
        let result = if let Some(timeout) = timeout {
            let now = Instant::now();
            unlock!();
            loop {
                let Some(remaining) = timeout.checked_sub(now.elapsed()) else {
                    break WaitTimeoutResult::new(true);
                };
                match fx.wait_for(0, remaining) {
                    Ok(()) => break WaitTimeoutResult::new(false),
                    Err(TimedWaitError::TimedOut) => break WaitTimeoutResult::new(true),
                    Err(TimedWaitError::Interrupted) => continue,
                    Err(TimedWaitError::WrongValue) => unreachable!(),
                }
            }
        } else {
            unlock!();
            loop {
                match fx.wait(0) {
                    Ok(()) => break WaitTimeoutResult::new(false),
                    Err(WaitError::Interrupted) => continue,
                    Err(WaitError::WrongValue) => unreachable!(),
                }
            }
        };
        self.waiters.fetch_sub(1, Ordering::SeqCst);
        mutex.perform_lock();
        result
    }

    /// Notifies one thread waiting on this condvar.
    pub fn notify_one(&self) {
        let fx: &Futex<Private> = self.fx.as_futex();
        let mut backoff = Backoff::new();
        while self.waiters.load(Ordering::SeqCst) > 0 && fx.wake(1) == 0 {
            // there is a chance that some waiter has not been entered into the futex yet, waiting
            // for it in a tiny spin loop
            backoff.backoff();
        }
    }

    /// Notifies all threads waiting on this condvar.
    pub fn notify_all(&self) {
        let fx: &Futex<Private> = self.fx.as_futex();
        let mut backoff = Backoff::new();
        loop {
            let to_wake = self.waiters.load(Ordering::SeqCst);
            if to_wake == 0 || fx.wake(to_wake) == to_wake {
                break;
            }
            // there is a chance that some waiter has not been entered into the futex yet, waiting
            // for it in a tiny spin loop
            backoff.backoff();
        }
    }
}

// Backoff strategy for the conditional variable.
//
// If the notify thread is running with higher priority, the waiter might be blocked between
// mutex.unlock() and futex.wait(). So, it is necessary to backoff in notify_one() and
// notify_all().
//
// It is proven by tests that yelding is not enough, as futex.wake() is a relatively expensive
// operation so it should be called as less as possible (ideal case is <=2).
//
// The initial 50us quant has been chosen as a trade-off between performance and fairness. It is
// proven to be enough to let a waiter with sched=1 to enter the futex.wait() from the first time
// even if the notify thread is spinning with sched=99 (in case if both are on the same CPU).
//
// Tested on: ARM Cortex-A53, ARM Cortex-A72
//
// The backoff time is increased by 25us each time, to make sure the loop does not block
// the waiter on different (possibly slower) CPU models.
//
// Note that conditional variables might still face priority inversion problem for certain cases
// when a waiter is being blocked by a 3rd party thread with higher priority. However the chosen
// strategy is still much more reliable and 3-4 times faster than traditional 3rd party
// Mutex+Condvar implementations.
struct Backoff {
    n: u32,
}

impl Backoff {
    fn new() -> Self {
        Self { n: 50 }
    }

    fn backoff(&mut self) {
        thread::sleep(Duration::from_micros(self.n.into()));
        if self.n < 200 {
            // max sleep time = 200us
            self.n += 25;
        }
    }
}

/// The lock implementation for the priority-inheritance based mutex.
#[allow(clippy::module_name_repetitions)]
pub struct PiLock {
    futex: PiFutex<Private>,
    blocked: AtomicBool,
}

impl PiLock {
    fn perform_lock(&self) {
        if self.blocked.load(Ordering::SeqCst) {
            // spin forever
            loop {
                thread::park();
            }
        }
        let tid = tid();
        #[allow(clippy::cast_sign_loss)]
        let locked =
            self.futex
                .value
                .compare_exchange(0, tid as u32, Ordering::SeqCst, Ordering::SeqCst);

        if locked.is_err() {
            while self.futex.lock_pi().is_err() {
                thread::yield_now();
            }
        }
    }
    fn perform_try_lock(&self) -> bool {
        if self.blocked.load(Ordering::SeqCst) {
            return false;
        }
        let tid = tid();
        #[allow(clippy::cast_sign_loss)]
        let locked =
            self.futex
                .value
                .compare_exchange(0, tid as u32, Ordering::SeqCst, Ordering::SeqCst);

        if locked.is_ok() {
            true
        } else {
            self.futex.trylock_pi().is_ok()
        }
    }
    fn perform_unlock(&self) {
        let tid = tid();
        #[allow(clippy::cast_sign_loss)]
        let fast_unlocked =
            self.futex
                .value
                .compare_exchange(tid as u32, 0, Ordering::SeqCst, Ordering::SeqCst);

        if fast_unlocked.is_err() {
            self.futex.unlock_pi();
        }
    }
    #[inline]
    fn is_locked(&self) -> bool {
        self.blocked.load(Ordering::SeqCst) || self.futex.value.load(Ordering::SeqCst) != 0
    }
    #[inline]
    fn block_forever(&self) {
        self.blocked.store(true, Ordering::SeqCst);
    }
}

unsafe impl RawMutexTrait for PiLock {
    #[allow(clippy::declare_interior_mutable_const)]
    const INIT: Self = Self {
        futex: PiFutex::new(0),
        blocked: AtomicBool::new(false),
    };

    type GuardMarker = GuardSend;

    #[inline]
    fn lock(&self) {
        self.perform_lock();
    }

    #[inline]
    fn try_lock(&self) -> bool {
        self.perform_try_lock()
    }

    #[inline]
    unsafe fn unlock(&self) {
        self.perform_unlock();
    }
}

unsafe impl RawMutexTimed for PiLock {
    type Duration = Duration;

    type Instant = Instant;

    #[inline]
    fn try_lock_for(&self, timeout: Self::Duration) -> bool {
        self.try_lock_until(Self::Instant::now() + timeout)
    }

    fn try_lock_until(&self, ts: Self::Instant) -> bool {
        let tid = tid();
        #[allow(clippy::cast_sign_loss)]
        let locked =
            self.futex
                .value
                .compare_exchange(0, tid as u32, Ordering::SeqCst, Ordering::SeqCst);

        if locked.is_ok() {
            return true;
        }

        loop {
            match self.futex.lock_pi_until(ts) {
                Ok(()) => return true,
                Err(linux_futex::TimedLockError::TryAgain) => (),
                Err(linux_futex::TimedLockError::TimedOut) => return false,
            }
        }
    }
}

/// Priority-inheritance based mutex implementation.
pub type Mutex<T> = lock_api::Mutex<PiLock, T>;
/// Priority-inheritance based mutex guard.
pub type MutexGuard<'a, T> = lock_api::MutexGuard<'a, PiLock, T>;

/// Leaks the mutex guard and returns a mutable reference to the data protected by the mutex.
/// The lock is blocked forever causing all lock attempts to spin (with a tiny delay to release
/// quants).
pub fn block_forever<T>(guard: MutexGuard<T>) -> &mut T {
    unsafe {
        lock_api::MutexGuard::<'_, PiLock, T>::mutex(&guard)
            .raw()
            .block_forever();
    }
    lock_api::MutexGuard::<'_, PiLock, T>::leak(guard)
}

/// Compatibility name
pub type RawMutex = PiLock;

impl RawCondvar for Condvar {
    type RawMutex = PiLock;

    fn new() -> Self {
        Self::new()
    }

    fn wait<T, M>(&self, guard: &mut MutexGuard<T>) {
        self.wait(guard);
    }

    fn wait_for<T, M>(&self, guard: &mut MutexGuard<T>, timeout: Duration) -> WaitTimeoutResult {
        self.wait_for(guard, timeout)
    }

    fn notify_one(&self) {
        self.notify_one();
    }

    fn notify_all(&self) {
        self.notify_all();
    }
}

#[cfg(test)]
mod tests {
    use std::{sync::Arc, thread, time::Duration};

    use super::{Condvar, Mutex};

    const NUM_THREADS: usize = 100;
    const ITERS: usize = 100;

    #[test]
    fn test_mutex_lock_loop() {
        for _ in 0..ITERS {
            let mutex = Arc::new(Mutex::new(0));
            let mut handles = vec![];

            for _ in 0..NUM_THREADS {
                let m = Arc::clone(&mutex);
                handles.push(thread::spawn(move || {
                    let mut num = m.lock();
                    *num += 1;
                }));
            }

            for handle in handles {
                handle.join().unwrap();
            }

            assert_eq!(*mutex.lock(), NUM_THREADS);
        }
    }

    #[test]
    fn test_mutex_try_lock_loop() {
        for _ in 0..ITERS {
            let mutex = Arc::new(Mutex::new(0));
            let mut handles = vec![];

            for _ in 0..NUM_THREADS {
                let m = Arc::clone(&mutex);
                handles.push(thread::spawn(move || {
                    if let Some(mut num) = m.try_lock() {
                        *num += 1;
                    }
                }));
                thread::sleep(Duration::from_micros(200));
            }

            for handle in handles {
                handle.join().unwrap();
            }

            assert_eq!(*mutex.try_lock().unwrap(), NUM_THREADS);
        }
    }

    #[test]
    fn test_condvar_wait_notify_one_loop() {
        for _ in 0..ITERS {
            let pair = Arc::new((Mutex::new(false), Condvar::new()));
            let mut handles = vec![];

            for _ in 0..NUM_THREADS {
                let pair_clone = Arc::clone(&pair);
                handles.push(thread::spawn(move || {
                    let (lock, cvar) = &*pair_clone;
                    let mut started = lock.lock();
                    while !*started {
                        cvar.wait(&mut started);
                    }
                }));
            }

            thread::sleep(Duration::from_millis(10));
            for _ in 0..NUM_THREADS {
                let (lock, cvar) = &*pair;
                let mut started = lock.lock();
                *started = true;
                cvar.notify_one();
            }

            for handle in handles {
                handle.join().unwrap();
            }
        }
    }

    #[test]
    fn test_condvar_wait_notify_all_loop() {
        for _ in 0..ITERS {
            let pair = Arc::new((Mutex::new(false), Condvar::new()));
            let mut handles = vec![];

            for _ in 0..NUM_THREADS {
                let pair_clone = Arc::clone(&pair);
                handles.push(thread::spawn(move || {
                    let (lock, cvar) = &*pair_clone;
                    let mut started = lock.lock();
                    while !*started {
                        cvar.wait(&mut started);
                    }
                }));
            }

            thread::sleep(Duration::from_millis(10));
            {
                let (lock, cvar) = &*pair;
                let mut started = lock.lock();
                *started = true;
                cvar.notify_all();
            }

            for handle in handles {
                handle.join().unwrap();
            }
        }
    }

    #[test]
    fn test_condvar_timeout_wait_loop_notify_one() {
        for _ in 0..ITERS {
            let pair = Arc::new((Mutex::new(false), Condvar::new()));
            let mut handles = vec![];

            for _ in 0..NUM_THREADS {
                let pair_clone = Arc::clone(&pair);
                handles.push(thread::spawn(move || {
                    let (lock, cvar) = &*pair_clone;
                    let mut mx = lock.lock();
                    if cvar
                        .wait_for(&mut mx, Duration::from_millis(100))
                        .timed_out()
                    {
                        panic!("timed out");
                    }
                }));
            }

            thread::sleep(Duration::from_millis(50));
            {
                let (lock, cvar) = &*pair;
                for _ in 0..NUM_THREADS {
                    let mut started = lock.lock();
                    *started = true;
                    cvar.notify_one();
                }
            }

            for handle in handles {
                handle.join().unwrap();
            }
        }
    }
    #[test]
    fn test_block_forever() {
        let mutex = Mutex::new(0);
        {
            let guard = mutex.lock();
            super::block_forever(guard);
        }
        assert!(mutex.try_lock().is_none());
    }

    #[test]
    fn test_condvar_timeout_wait_loop_notify_all() {
        for _ in 0..ITERS {
            let pair = Arc::new((Mutex::new(false), Condvar::new()));
            let mut handles = vec![];

            for _ in 0..NUM_THREADS {
                let pair_clone = Arc::clone(&pair);
                handles.push(thread::spawn(move || {
                    let (lock, cvar) = &*pair_clone;
                    let mut mx = lock.lock();
                    if cvar
                        .wait_for(&mut mx, Duration::from_millis(100))
                        .timed_out()
                    {
                        panic!("timed out");
                    }
                }));
            }

            thread::sleep(Duration::from_millis(50));
            {
                let (lock, cvar) = &*pair;
                let mut started = lock.lock();
                *started = true;
                cvar.notify_all();
            }

            for handle in handles {
                handle.join().unwrap();
            }
        }
    }
}