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.
40#[derive(Debug)]
41pub struct CriticalSectionRawMutex {
42    _phantom: PhantomData<()>,
43}
44unsafe impl Send for CriticalSectionRawMutex {}
45unsafe impl Sync for CriticalSectionRawMutex {}
46
47impl CriticalSectionRawMutex {
48    /// Create a new `CriticalSectionRawMutex`.
49    pub const fn new() -> Self {
50        Self { _phantom: PhantomData }
51    }
52}
53
54unsafe impl RawMutex for CriticalSectionRawMutex {
55    const INIT: Self = Self::new();
56
57    fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
58        critical_section::with(|_| f())
59    }
60}
61
62// ================
63
64/// A mutex that allows borrowing data in the context of a single executor.
65///
66/// # Safety
67///
68/// **This Mutex is only safe within a single executor.**
69#[derive(Debug)]
70pub struct NoopRawMutex {
71    _phantom: PhantomData<*mut ()>,
72}
73
74unsafe impl Send for NoopRawMutex {}
75
76impl NoopRawMutex {
77    /// Create a new `NoopRawMutex`.
78    pub const fn new() -> Self {
79        Self { _phantom: PhantomData }
80    }
81}
82
83unsafe impl RawMutex for NoopRawMutex {
84    const INIT: Self = Self::new();
85    fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
86        f()
87    }
88}
89
90// ================
91
92#[cfg(any(cortex_m, feature = "std"))]
93mod thread_mode {
94    use super::*;
95
96    /// A "mutex" that only allows borrowing from thread mode.
97    ///
98    /// # Safety
99    ///
100    /// **This Mutex is only safe on single-core systems.**
101    ///
102    /// On multi-core systems, a `ThreadModeRawMutex` **is not sufficient** to ensure exclusive access.
103    pub struct ThreadModeRawMutex {
104        _phantom: PhantomData<()>,
105    }
106
107    unsafe impl Send for ThreadModeRawMutex {}
108    unsafe impl Sync for ThreadModeRawMutex {}
109
110    impl ThreadModeRawMutex {
111        /// Create a new `ThreadModeRawMutex`.
112        pub const fn new() -> Self {
113            Self { _phantom: PhantomData }
114        }
115    }
116
117    unsafe impl RawMutex for ThreadModeRawMutex {
118        const INIT: Self = Self::new();
119        fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
120            assert!(in_thread_mode(), "ThreadModeMutex can only be locked from thread mode.");
121
122            f()
123        }
124    }
125
126    impl Drop for ThreadModeRawMutex {
127        fn drop(&mut self) {
128            // Only allow dropping from thread mode. Dropping calls drop on the inner `T`, so
129            // `drop` needs the same guarantees as `lock`. `ThreadModeMutex<T>` is Send even if
130            // T isn't, so without this check a user could create a ThreadModeMutex in thread mode,
131            // send it to interrupt context and drop it there, which would "send" a T even if T is not Send.
132            assert!(
133                in_thread_mode(),
134                "ThreadModeMutex can only be dropped from thread mode."
135            );
136
137            // Drop of the inner `T` happens after this.
138        }
139    }
140
141    pub(crate) fn in_thread_mode() -> bool {
142        #[cfg(feature = "std")]
143        return Some("main") == std::thread::current().name();
144
145        #[cfg(not(feature = "std"))]
146        // ICSR.VECTACTIVE == 0
147        return unsafe { (0xE000ED04 as *const u32).read_volatile() } & 0x1FF == 0;
148    }
149}
150#[cfg(any(cortex_m, feature = "std"))]
151pub use thread_mode::*;