diff options
Diffstat (limited to 'embassy-sync/src/blocking_mutex')
| -rw-r--r-- | embassy-sync/src/blocking_mutex/mod.rs | 189 | ||||
| -rw-r--r-- | embassy-sync/src/blocking_mutex/raw.rs | 149 |
2 files changed, 338 insertions, 0 deletions
diff --git a/embassy-sync/src/blocking_mutex/mod.rs b/embassy-sync/src/blocking_mutex/mod.rs new file mode 100644 index 000000000..8a4a4c642 --- /dev/null +++ b/embassy-sync/src/blocking_mutex/mod.rs | |||
| @@ -0,0 +1,189 @@ | |||
| 1 | //! Blocking mutex. | ||
| 2 | //! | ||
| 3 | //! This module provides a blocking mutex that can be used to synchronize data. | ||
| 4 | pub mod raw; | ||
| 5 | |||
| 6 | use core::cell::UnsafeCell; | ||
| 7 | |||
| 8 | use self::raw::RawMutex; | ||
| 9 | |||
| 10 | /// Blocking mutex (not async) | ||
| 11 | /// | ||
| 12 | /// Provides a blocking mutual exclusion primitive backed by an implementation of [`raw::RawMutex`]. | ||
| 13 | /// | ||
| 14 | /// Which implementation you select depends on the context in which you're using the mutex, and you can choose which kind | ||
| 15 | /// of interior mutability fits your use case. | ||
| 16 | /// | ||
| 17 | /// Use [`CriticalSectionMutex`] when data can be shared between threads and interrupts. | ||
| 18 | /// | ||
| 19 | /// Use [`NoopMutex`] when data is only shared between tasks running on the same executor. | ||
| 20 | /// | ||
| 21 | /// Use [`ThreadModeMutex`] when data is shared between tasks running on the same executor but you want a global singleton. | ||
| 22 | /// | ||
| 23 | /// In all cases, the blocking mutex is intended to be short lived and not held across await points. | ||
| 24 | /// Use the async [`Mutex`](crate::mutex::Mutex) if you need a lock that is held across await points. | ||
| 25 | pub struct Mutex<R, T: ?Sized> { | ||
| 26 | // NOTE: `raw` must be FIRST, so when using ThreadModeMutex the "can't drop in non-thread-mode" gets | ||
| 27 | // to run BEFORE dropping `data`. | ||
| 28 | raw: R, | ||
| 29 | data: UnsafeCell<T>, | ||
| 30 | } | ||
| 31 | |||
| 32 | unsafe impl<R: RawMutex + Send, T: ?Sized + Send> Send for Mutex<R, T> {} | ||
| 33 | unsafe impl<R: RawMutex + Sync, T: ?Sized + Send> Sync for Mutex<R, T> {} | ||
| 34 | |||
| 35 | impl<R: RawMutex, T> Mutex<R, T> { | ||
| 36 | /// Creates a new mutex in an unlocked state ready for use. | ||
| 37 | #[inline] | ||
| 38 | pub const fn new(val: T) -> Mutex<R, T> { | ||
| 39 | Mutex { | ||
| 40 | raw: R::INIT, | ||
| 41 | data: UnsafeCell::new(val), | ||
| 42 | } | ||
| 43 | } | ||
| 44 | |||
| 45 | /// Creates a critical section and grants temporary access to the protected data. | ||
| 46 | pub fn lock<U>(&self, f: impl FnOnce(&T) -> U) -> U { | ||
| 47 | self.raw.lock(|| { | ||
| 48 | let ptr = self.data.get() as *const T; | ||
| 49 | let inner = unsafe { &*ptr }; | ||
| 50 | f(inner) | ||
| 51 | }) | ||
| 52 | } | ||
| 53 | } | ||
| 54 | |||
| 55 | impl<R, T> Mutex<R, T> { | ||
| 56 | /// Creates a new mutex based on a pre-existing raw mutex. | ||
| 57 | /// | ||
| 58 | /// This allows creating a mutex in a constant context on stable Rust. | ||
| 59 | #[inline] | ||
| 60 | pub const fn const_new(raw_mutex: R, val: T) -> Mutex<R, T> { | ||
| 61 | Mutex { | ||
| 62 | raw: raw_mutex, | ||
| 63 | data: UnsafeCell::new(val), | ||
| 64 | } | ||
| 65 | } | ||
| 66 | |||
| 67 | /// Consumes this mutex, returning the underlying data. | ||
| 68 | #[inline] | ||
| 69 | pub fn into_inner(self) -> T { | ||
| 70 | self.data.into_inner() | ||
| 71 | } | ||
| 72 | |||
| 73 | /// Returns a mutable reference to the underlying data. | ||
| 74 | /// | ||
| 75 | /// Since this call borrows the `Mutex` mutably, no actual locking needs to | ||
| 76 | /// take place---the mutable borrow statically guarantees no locks exist. | ||
| 77 | #[inline] | ||
| 78 | pub fn get_mut(&mut self) -> &mut T { | ||
| 79 | unsafe { &mut *self.data.get() } | ||
| 80 | } | ||
| 81 | } | ||
| 82 | |||
| 83 | /// A mutex that allows borrowing data across executors and interrupts. | ||
| 84 | /// | ||
| 85 | /// # Safety | ||
| 86 | /// | ||
| 87 | /// This mutex is safe to share between different executors and interrupts. | ||
| 88 | pub type CriticalSectionMutex<T> = Mutex<raw::CriticalSectionRawMutex, T>; | ||
| 89 | |||
| 90 | /// A mutex that allows borrowing data in the context of a single executor. | ||
| 91 | /// | ||
| 92 | /// # Safety | ||
| 93 | /// | ||
| 94 | /// **This Mutex is only safe within a single executor.** | ||
| 95 | pub type NoopMutex<T> = Mutex<raw::NoopRawMutex, T>; | ||
| 96 | |||
| 97 | impl<T> Mutex<raw::CriticalSectionRawMutex, T> { | ||
| 98 | /// Borrows the data for the duration of the critical section | ||
| 99 | pub fn borrow<'cs>(&'cs self, _cs: critical_section::CriticalSection<'cs>) -> &'cs T { | ||
| 100 | let ptr = self.data.get() as *const T; | ||
| 101 | unsafe { &*ptr } | ||
| 102 | } | ||
| 103 | } | ||
| 104 | |||
| 105 | impl<T> Mutex<raw::NoopRawMutex, T> { | ||
| 106 | /// Borrows the data | ||
| 107 | pub fn borrow(&self) -> &T { | ||
| 108 | let ptr = self.data.get() as *const T; | ||
| 109 | unsafe { &*ptr } | ||
| 110 | } | ||
| 111 | } | ||
| 112 | |||
| 113 | // ThreadModeMutex does NOT use the generic mutex from above because it's special: | ||
| 114 | // it's Send+Sync even if T: !Send. There's no way to do that without specialization (I think?). | ||
| 115 | // | ||
| 116 | // There's still a ThreadModeRawMutex for use with the generic Mutex (handy with Channel, for example), | ||
| 117 | // but that will require T: Send even though it shouldn't be needed. | ||
| 118 | |||
| 119 | #[cfg(any(cortex_m, feature = "std"))] | ||
| 120 | pub use thread_mode_mutex::*; | ||
| 121 | #[cfg(any(cortex_m, feature = "std"))] | ||
| 122 | mod thread_mode_mutex { | ||
| 123 | use super::*; | ||
| 124 | |||
| 125 | /// A "mutex" that only allows borrowing from thread mode. | ||
| 126 | /// | ||
| 127 | /// # Safety | ||
| 128 | /// | ||
| 129 | /// **This Mutex is only safe on single-core systems.** | ||
| 130 | /// | ||
| 131 | /// On multi-core systems, a `ThreadModeMutex` **is not sufficient** to ensure exclusive access. | ||
| 132 | pub struct ThreadModeMutex<T: ?Sized> { | ||
| 133 | inner: UnsafeCell<T>, | ||
| 134 | } | ||
| 135 | |||
| 136 | // NOTE: ThreadModeMutex only allows borrowing from one execution context ever: thread mode. | ||
| 137 | // Therefore it cannot be used to send non-sendable stuff between execution contexts, so it can | ||
| 138 | // be Send+Sync even if T is not Send (unlike CriticalSectionMutex) | ||
| 139 | unsafe impl<T: ?Sized> Sync for ThreadModeMutex<T> {} | ||
| 140 | unsafe impl<T: ?Sized> Send for ThreadModeMutex<T> {} | ||
| 141 | |||
| 142 | impl<T> ThreadModeMutex<T> { | ||
| 143 | /// Creates a new mutex | ||
| 144 | pub const fn new(value: T) -> Self { | ||
| 145 | ThreadModeMutex { | ||
| 146 | inner: UnsafeCell::new(value), | ||
| 147 | } | ||
| 148 | } | ||
| 149 | } | ||
| 150 | |||
| 151 | impl<T: ?Sized> ThreadModeMutex<T> { | ||
| 152 | /// Lock the `ThreadModeMutex`, granting access to the data. | ||
| 153 | /// | ||
| 154 | /// # Panics | ||
| 155 | /// | ||
| 156 | /// This will panic if not currently running in thread mode. | ||
| 157 | pub fn lock<R>(&self, f: impl FnOnce(&T) -> R) -> R { | ||
| 158 | f(self.borrow()) | ||
| 159 | } | ||
| 160 | |||
| 161 | /// Borrows the data | ||
| 162 | /// | ||
| 163 | /// # Panics | ||
| 164 | /// | ||
| 165 | /// This will panic if not currently running in thread mode. | ||
| 166 | pub fn borrow(&self) -> &T { | ||
| 167 | assert!( | ||
| 168 | raw::in_thread_mode(), | ||
| 169 | "ThreadModeMutex can only be borrowed from thread mode." | ||
| 170 | ); | ||
| 171 | unsafe { &*self.inner.get() } | ||
| 172 | } | ||
| 173 | } | ||
| 174 | |||
| 175 | impl<T: ?Sized> Drop for ThreadModeMutex<T> { | ||
| 176 | fn drop(&mut self) { | ||
| 177 | // Only allow dropping from thread mode. Dropping calls drop on the inner `T`, so | ||
| 178 | // `drop` needs the same guarantees as `lock`. `ThreadModeMutex<T>` is Send even if | ||
| 179 | // T isn't, so without this check a user could create a ThreadModeMutex in thread mode, | ||
| 180 | // send it to interrupt context and drop it there, which would "send" a T even if T is not Send. | ||
| 181 | assert!( | ||
| 182 | raw::in_thread_mode(), | ||
| 183 | "ThreadModeMutex can only be dropped from thread mode." | ||
| 184 | ); | ||
| 185 | |||
| 186 | // Drop of the inner `T` happens after this. | ||
| 187 | } | ||
| 188 | } | ||
| 189 | } | ||
diff --git a/embassy-sync/src/blocking_mutex/raw.rs b/embassy-sync/src/blocking_mutex/raw.rs new file mode 100644 index 000000000..15796f1b2 --- /dev/null +++ b/embassy-sync/src/blocking_mutex/raw.rs | |||
| @@ -0,0 +1,149 @@ | |||
| 1 | //! Mutex primitives. | ||
| 2 | //! | ||
| 3 | //! This module provides a trait for mutexes that can be used in different contexts. | ||
| 4 | use 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 allwed. 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. | ||
| 25 | pub 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 | pub struct CriticalSectionRawMutex { | ||
| 41 | _phantom: PhantomData<()>, | ||
| 42 | } | ||
| 43 | unsafe impl Send for CriticalSectionRawMutex {} | ||
| 44 | unsafe impl Sync for CriticalSectionRawMutex {} | ||
| 45 | |||
| 46 | impl CriticalSectionRawMutex { | ||
| 47 | /// Create a new `CriticalSectionRawMutex`. | ||
| 48 | pub const fn new() -> Self { | ||
| 49 | Self { _phantom: PhantomData } | ||
| 50 | } | ||
| 51 | } | ||
| 52 | |||
| 53 | unsafe 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.** | ||
| 68 | pub struct NoopRawMutex { | ||
| 69 | _phantom: PhantomData<*mut ()>, | ||
| 70 | } | ||
| 71 | |||
| 72 | unsafe impl Send for NoopRawMutex {} | ||
| 73 | |||
| 74 | impl NoopRawMutex { | ||
| 75 | /// Create a new `NoopRawMutex`. | ||
| 76 | pub const fn new() -> Self { | ||
| 77 | Self { _phantom: PhantomData } | ||
| 78 | } | ||
| 79 | } | ||
| 80 | |||
| 81 | unsafe 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"))] | ||
| 91 | mod 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"))] | ||
| 149 | pub use thread_mode::*; | ||
