embassy_sync/blocking_mutex/
raw.rs

1//! Mutex primitives.
2//!
3//! This module provides a trait for mutexes that can be used in different contexts.
4use core::marker::PhantomData;
5
6/// Raw mutex trait.
7///
8/// This mutex is "raw", which means it does not actually contain the protected data, it
9/// just implements the mutex mechanism. For most uses you should use [`super::Mutex`] instead,
10/// which is generic over a RawMutex and contains the protected data.
11///
12/// Note that, unlike other mutexes, implementations only guarantee no
13/// concurrent access from other threads: concurrent access from the current
14/// thread is allowed. For example, it's possible to lock the same mutex multiple times reentrantly.
15///
16/// Therefore, locking a `RawMutex` is only enough to guarantee safe shared (`&`) access
17/// to the data, it is not enough to guarantee exclusive (`&mut`) access.
18///
19/// # Safety
20///
21/// RawMutex implementations must ensure that, while locked, no other thread can lock
22/// the RawMutex concurrently.
23///
24/// Unsafe code is allowed to rely on this fact, so incorrect implementations will cause undefined behavior.
25pub unsafe trait RawMutex {
26    /// Create a new `RawMutex` instance.
27    ///
28    /// This is a const instead of a method to allow creating instances in const context.
29    const INIT: Self;
30
31    /// Lock this `RawMutex`.
32    fn lock<R>(&self, f: impl FnOnce() -> R) -> R;
33}
34
35/// A mutex that allows borrowing data across executors and interrupts.
36///
37/// # Safety
38///
39/// This mutex is safe to share between different executors and interrupts.
40pub struct CriticalSectionRawMutex {
41    _phantom: PhantomData<()>,
42}
43unsafe impl Send for CriticalSectionRawMutex {}
44unsafe impl Sync for CriticalSectionRawMutex {}
45
46impl CriticalSectionRawMutex {
47    /// Create a new `CriticalSectionRawMutex`.
48    pub const fn new() -> Self {
49        Self { _phantom: PhantomData }
50    }
51}
52
53unsafe impl RawMutex for CriticalSectionRawMutex {
54    const INIT: Self = Self::new();
55
56    fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
57        critical_section::with(|_| f())
58    }
59}
60
61// ================
62
63/// A mutex that allows borrowing data in the context of a single executor.
64///
65/// # Safety
66///
67/// **This Mutex is only safe within a single executor.**
68pub struct NoopRawMutex {
69    _phantom: PhantomData<*mut ()>,
70}
71
72unsafe impl Send for NoopRawMutex {}
73
74impl NoopRawMutex {
75    /// Create a new `NoopRawMutex`.
76    pub const fn new() -> Self {
77        Self { _phantom: PhantomData }
78    }
79}
80
81unsafe impl RawMutex for NoopRawMutex {
82    const INIT: Self = Self::new();
83    fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
84        f()
85    }
86}
87
88// ================
89
90#[cfg(any(cortex_m, feature = "std"))]
91mod thread_mode {
92    use super::*;
93
94    /// A "mutex" that only allows borrowing from thread mode.
95    ///
96    /// # Safety
97    ///
98    /// **This Mutex is only safe on single-core systems.**
99    ///
100    /// On multi-core systems, a `ThreadModeRawMutex` **is not sufficient** to ensure exclusive access.
101    pub struct ThreadModeRawMutex {
102        _phantom: PhantomData<()>,
103    }
104
105    unsafe impl Send for ThreadModeRawMutex {}
106    unsafe impl Sync for ThreadModeRawMutex {}
107
108    impl ThreadModeRawMutex {
109        /// Create a new `ThreadModeRawMutex`.
110        pub const fn new() -> Self {
111            Self { _phantom: PhantomData }
112        }
113    }
114
115    unsafe impl RawMutex for ThreadModeRawMutex {
116        const INIT: Self = Self::new();
117        fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
118            assert!(in_thread_mode(), "ThreadModeMutex can only be locked from thread mode.");
119
120            f()
121        }
122    }
123
124    impl Drop for ThreadModeRawMutex {
125        fn drop(&mut self) {
126            // Only allow dropping from thread mode. Dropping calls drop on the inner `T`, so
127            // `drop` needs the same guarantees as `lock`. `ThreadModeMutex<T>` is Send even if
128            // T isn't, so without this check a user could create a ThreadModeMutex in thread mode,
129            // send it to interrupt context and drop it there, which would "send" a T even if T is not Send.
130            assert!(
131                in_thread_mode(),
132                "ThreadModeMutex can only be dropped from thread mode."
133            );
134
135            // Drop of the inner `T` happens after this.
136        }
137    }
138
139    pub(crate) fn in_thread_mode() -> bool {
140        #[cfg(feature = "std")]
141        return Some("main") == std::thread::current().name();
142
143        #[cfg(not(feature = "std"))]
144        // ICSR.VECTACTIVE == 0
145        return unsafe { (0xE000ED04 as *const u32).read_volatile() } & 0x1FF == 0;
146    }
147}
148#[cfg(any(cortex_m, feature = "std"))]
149pub use thread_mode::*;