hazard3_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#[cfg(not(feature = "portable-atomic"))]
6use core::sync::atomic::{AtomicBool, Ordering};
7
8#[cfg(feature = "portable-atomic")]
9use portable_atomic::{AtomicBool, Ordering};
10
11/// Raw mutex trait.
12///
13/// This mutex is "raw", which means it does not actually contain the protected data, it
14/// just implements the mutex mechanism. For most uses you should use [`super::Mutex`] instead,
15/// which is generic over a RawMutex and contains the protected data.
16///
17/// Note that, unlike other mutexes, implementations only guarantee no
18/// concurrent access from other threads: concurrent access from the current
19/// thread is allowed. For example, it's possible to lock the same mutex multiple times reentrantly.
20///
21/// Therefore, locking a `RawMutex` is only enough to guarantee safe shared (`&`) access
22/// to the data, it is not enough to guarantee exclusive (`&mut`) access.
23///
24/// # Safety
25///
26/// RawMutex implementations must ensure that, while locked, no other thread can lock
27/// the RawMutex concurrently.
28///
29/// Unsafe code is allowed to rely on this fact, so incorrect implementations will cause undefined behavior.
30pub unsafe trait RawMutex {
31 /// Create a new `RawMutex` instance.
32 ///
33 /// This is a const instead of a method to allow creating instances in const context.
34 const INIT: Self;
35
36 /// Lock this `RawMutex`.
37 fn lock<R>(&self, f: impl FnOnce() -> R) -> R;
38}
39
40/// A mutex that allows borrowing data across executors and interrupts.
41///
42/// # Safety
43///
44/// This mutex is safe to share between different executors and interrupts.
45#[derive(Debug, Clone, Copy)]
46pub struct CriticalSectionRawMutex {
47 _phantom: PhantomData<()>,
48}
49unsafe impl Send for CriticalSectionRawMutex {}
50unsafe impl Sync for CriticalSectionRawMutex {}
51
52impl CriticalSectionRawMutex {
53 /// Create a new `CriticalSectionRawMutex`.
54 pub const fn new() -> Self {
55 Self { _phantom: PhantomData }
56 }
57}
58
59unsafe impl RawMutex for CriticalSectionRawMutex {
60 const INIT: Self = Self::new();
61
62 fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
63 critical_section::with(|_| f())
64 }
65}
66
67/// A mutex that panics if locked from multiple contexts.
68///
69/// # Safety
70///
71/// This mutex is safe to share between different executors and interrupts.
72#[derive(Debug)]
73pub struct PanicRawMutex {
74 locked: AtomicBool,
75}
76unsafe impl Send for PanicRawMutex {}
77unsafe impl Sync for PanicRawMutex {}
78
79impl PanicRawMutex {
80 /// Create a new `PanicRawMutex`.
81 pub const fn new() -> Self {
82 Self {
83 locked: AtomicBool::new(false),
84 }
85 }
86}
87
88unsafe impl RawMutex for PanicRawMutex {
89 const INIT: Self = Self::new();
90
91 fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
92 #[cfg(target_has_atomic = "8")]
93 if self.locked.swap(true, Ordering::Relaxed) {
94 panic!("PanicRawMutex locked from multiple contexts")
95 }
96
97 #[cfg(not(target_has_atomic = "8"))]
98 critical_section::with(|_| {
99 if self.locked.load(Ordering::Acquire) {
100 panic!("PanicRawMutex locked from multiple contexts")
101 }
102 self.locked.store(true, Ordering::Release);
103 });
104
105 let ret = f();
106
107 self.locked.store(false, Ordering::Relaxed);
108 ret
109 }
110}
111
112// ================
113
114/// A mutex that allows borrowing data in the context of a single executor.
115///
116/// # Safety
117///
118/// **This Mutex is only safe within a single executor.**
119#[derive(Debug)]
120pub struct NoopRawMutex {
121 _phantom: PhantomData<*mut ()>,
122}
123
124unsafe impl Send for NoopRawMutex {}
125
126impl NoopRawMutex {
127 /// Create a new `NoopRawMutex`.
128 pub const fn new() -> Self {
129 Self { _phantom: PhantomData }
130 }
131}
132
133unsafe impl RawMutex for NoopRawMutex {
134 const INIT: Self = Self::new();
135 fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
136 f()
137 }
138}
139
140// ================
141
142#[cfg(any(cortex_m, doc, feature = "std"))]
143mod thread_mode {
144 use super::*;
145
146 /// A "mutex" that only allows borrowing from thread mode.
147 ///
148 /// # Safety
149 ///
150 /// **This Mutex is only safe on single-core systems.**
151 ///
152 /// On multi-core systems, a `ThreadModeRawMutex` **is not sufficient** to ensure exclusive access.
153 pub struct ThreadModeRawMutex {
154 _phantom: PhantomData<()>,
155 }
156
157 unsafe impl Send for ThreadModeRawMutex {}
158 unsafe impl Sync for ThreadModeRawMutex {}
159
160 impl ThreadModeRawMutex {
161 /// Create a new `ThreadModeRawMutex`.
162 pub const fn new() -> Self {
163 Self { _phantom: PhantomData }
164 }
165 }
166
167 unsafe impl RawMutex for ThreadModeRawMutex {
168 const INIT: Self = Self::new();
169 fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
170 assert!(in_thread_mode(), "ThreadModeMutex can only be locked from thread mode.");
171
172 f()
173 }
174 }
175
176 impl Drop for ThreadModeRawMutex {
177 fn drop(&mut self) {
178 // Only allow dropping from thread mode. Dropping calls drop on the inner `T`, so
179 // `drop` needs the same guarantees as `lock`. `ThreadModeMutex<T>` is Send even if
180 // T isn't, so without this check a user could create a ThreadModeMutex in thread mode,
181 // send it to interrupt context and drop it there, which would "send" a T even if T is not Send.
182 assert!(
183 in_thread_mode(),
184 "ThreadModeMutex can only be dropped from thread mode."
185 );
186
187 // Drop of the inner `T` happens after this.
188 }
189 }
190
191 pub(crate) fn in_thread_mode() -> bool {
192 #[cfg(feature = "std")]
193 return Some("main") == std::thread::current().name();
194
195 #[cfg(not(feature = "std"))]
196 // ICSR.VECTACTIVE == 0
197 return unsafe { (0xE000ED04 as *const u32).read_volatile() } & 0x1FF == 0;
198 }
199}
200#[cfg(any(cortex_m, doc, feature = "std"))]
201pub use thread_mode::*;