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
use core::sync::atomic::Ordering;

use lock_api::RawMutex;

use crate::interrupts::{self, AtomicFlags};

/// An interrupt-safe mutex.
///
/// This mutex wraps another [`RawMutex`] and disables interrupts while locked.
/// Only has an effect if `target_os = "none"`.
pub struct RawInterruptMutex<I> {
    inner: I,
    interrupt_flags: AtomicFlags,
}

unsafe impl<I: RawMutex> RawMutex for RawInterruptMutex<I> {
    const INIT: Self = Self {
        inner: I::INIT,
        interrupt_flags: AtomicFlags::new(interrupts::DISABLE),
    };

    type GuardMarker = I::GuardMarker;

    #[inline]
    fn lock(&self) {
        let interrupt_flags = crate::interrupts::read_disable();
        self.inner.lock();
        self.interrupt_flags
            .store(interrupt_flags, Ordering::Relaxed);
    }

    #[inline]
    fn try_lock(&self) -> bool {
        let interrupt_flags = crate::interrupts::read_disable();
        let ok = self.inner.try_lock();
        if !ok {
            crate::interrupts::restore(interrupt_flags);
        }
        ok
    }

    #[inline]
    unsafe fn unlock(&self) {
        let interrupt_flags = self
            .interrupt_flags
            .swap(interrupts::DISABLE, Ordering::Relaxed);
        unsafe {
            self.inner.unlock();
        }
        crate::interrupts::restore(interrupt_flags);
    }

    #[inline]
    fn is_locked(&self) -> bool {
        self.inner.is_locked()
    }
}

/// A [`lock_api::Mutex`] based on [`RawInterruptMutex`].
pub type InterruptMutex<I, T> = lock_api::Mutex<RawInterruptMutex<I>, T>;

/// A [`lock_api::MutexGuard`] based on [`RawInterruptMutex`].
pub type InterruptMutexGuard<'a, I, T> = lock_api::MutexGuard<'a, RawInterruptMutex<I>, T>;