diff options
| author | Dario Nieuwenhuis <[email protected]> | 2025-04-07 23:13:35 +0000 |
|---|---|---|
| committer | GitHub <[email protected]> | 2025-04-07 23:13:35 +0000 |
| commit | a23e971d313e8098b8d3a13f3ddf7629aa79a98c (patch) | |
| tree | d45c6783176caa1131fcbb022e62433ed7f73674 | |
| parent | db3179cfb4be8596adbc601b27056bce03781407 (diff) | |
| parent | 313328c09a52ba6f8f30105a3a9f98a76a5aef69 (diff) | |
Merge pull request #4017 from shilga/SpinlockMutex
embassy-rp: Spinlock mutex implementation
| -rwxr-xr-x | ci.sh | 1 | ||||
| -rw-r--r-- | embassy-rp/src/critical_section_impl.rs | 43 | ||||
| -rw-r--r-- | embassy-rp/src/lib.rs | 2 | ||||
| -rw-r--r-- | embassy-rp/src/spinlock.rs | 75 | ||||
| -rw-r--r-- | embassy-rp/src/spinlock_mutex.rs | 93 | ||||
| -rw-r--r-- | tests/rp/src/bin/spinlock_mutex_multicore.rs | 54 |
6 files changed, 226 insertions, 42 deletions
| @@ -343,6 +343,7 @@ rm out/tests/stm32u5a5zj/usart | |||
| 343 | # As of 2025-02-17 these tests work when run from flash | 343 | # As of 2025-02-17 these tests work when run from flash |
| 344 | rm out/tests/pimoroni-pico-plus-2/multicore | 344 | rm out/tests/pimoroni-pico-plus-2/multicore |
| 345 | rm out/tests/pimoroni-pico-plus-2/gpio_multicore | 345 | rm out/tests/pimoroni-pico-plus-2/gpio_multicore |
| 346 | rm out/tests/pimoroni-pico-plus-2/spinlock_mutex_multicore | ||
| 346 | # Doesn't work when run from ram on the 2350 | 347 | # Doesn't work when run from ram on the 2350 |
| 347 | rm out/tests/pimoroni-pico-plus-2/flash | 348 | rm out/tests/pimoroni-pico-plus-2/flash |
| 348 | # This test passes locally but fails on the HIL, no idea why | 349 | # This test passes locally but fails on the HIL, no idea why |
diff --git a/embassy-rp/src/critical_section_impl.rs b/embassy-rp/src/critical_section_impl.rs index d233e6fab..2e4e8f716 100644 --- a/embassy-rp/src/critical_section_impl.rs +++ b/embassy-rp/src/critical_section_impl.rs | |||
| @@ -1,6 +1,7 @@ | |||
| 1 | use core::sync::atomic::{AtomicU8, Ordering}; | 1 | use core::sync::atomic::{AtomicU8, Ordering}; |
| 2 | 2 | ||
| 3 | use crate::pac; | 3 | use crate::pac; |
| 4 | use crate::spinlock::Spinlock; | ||
| 4 | 5 | ||
| 5 | struct RpSpinlockCs; | 6 | struct RpSpinlockCs; |
| 6 | critical_section::set_impl!(RpSpinlockCs); | 7 | critical_section::set_impl!(RpSpinlockCs); |
| @@ -92,46 +93,4 @@ impl RpSpinlockCs { | |||
| 92 | } | 93 | } |
| 93 | } | 94 | } |
| 94 | 95 | ||
| 95 | pub struct Spinlock<const N: usize>(core::marker::PhantomData<()>) | ||
| 96 | where | ||
| 97 | Spinlock<N>: SpinlockValid; | ||
| 98 | |||
| 99 | impl<const N: usize> Spinlock<N> | ||
| 100 | where | ||
| 101 | Spinlock<N>: SpinlockValid, | ||
| 102 | { | ||
| 103 | /// Try to claim the spinlock. Will return `Some(Self)` if the lock is obtained, and `None` if the lock is | ||
| 104 | /// already in use somewhere else. | ||
| 105 | pub fn try_claim() -> Option<Self> { | ||
| 106 | let lock = pac::SIO.spinlock(N).read(); | ||
| 107 | if lock > 0 { | ||
| 108 | Some(Self(core::marker::PhantomData)) | ||
| 109 | } else { | ||
| 110 | None | ||
| 111 | } | ||
| 112 | } | ||
| 113 | |||
| 114 | /// Clear a locked spin-lock. | ||
| 115 | /// | ||
| 116 | /// # Safety | ||
| 117 | /// | ||
| 118 | /// Only call this function if you hold the spin-lock. | ||
| 119 | pub unsafe fn release() { | ||
| 120 | // Write (any value): release the lock | ||
| 121 | pac::SIO.spinlock(N).write_value(1); | ||
| 122 | } | ||
| 123 | } | ||
| 124 | |||
| 125 | impl<const N: usize> Drop for Spinlock<N> | ||
| 126 | where | ||
| 127 | Spinlock<N>: SpinlockValid, | ||
| 128 | { | ||
| 129 | fn drop(&mut self) { | ||
| 130 | // This is safe because we own the object, and hence hold the lock. | ||
| 131 | unsafe { Self::release() } | ||
| 132 | } | ||
| 133 | } | ||
| 134 | |||
| 135 | pub(crate) type Spinlock31 = Spinlock<31>; | 96 | pub(crate) type Spinlock31 = Spinlock<31>; |
| 136 | pub trait SpinlockValid {} | ||
| 137 | impl SpinlockValid for Spinlock<31> {} | ||
diff --git a/embassy-rp/src/lib.rs b/embassy-rp/src/lib.rs index 35099d07b..f549446bc 100644 --- a/embassy-rp/src/lib.rs +++ b/embassy-rp/src/lib.rs | |||
| @@ -41,6 +41,8 @@ pub mod rom_data; | |||
| 41 | #[cfg(feature = "rp2040")] | 41 | #[cfg(feature = "rp2040")] |
| 42 | pub mod rtc; | 42 | pub mod rtc; |
| 43 | pub mod spi; | 43 | pub mod spi; |
| 44 | mod spinlock; | ||
| 45 | pub mod spinlock_mutex; | ||
| 44 | #[cfg(feature = "time-driver")] | 46 | #[cfg(feature = "time-driver")] |
| 45 | pub mod time_driver; | 47 | pub mod time_driver; |
| 46 | #[cfg(feature = "_rp235x")] | 48 | #[cfg(feature = "_rp235x")] |
diff --git a/embassy-rp/src/spinlock.rs b/embassy-rp/src/spinlock.rs new file mode 100644 index 000000000..7effd2ae0 --- /dev/null +++ b/embassy-rp/src/spinlock.rs | |||
| @@ -0,0 +1,75 @@ | |||
| 1 | use crate::pac; | ||
| 2 | |||
| 3 | pub struct Spinlock<const N: usize>(core::marker::PhantomData<()>) | ||
| 4 | where | ||
| 5 | Spinlock<N>: SpinlockValid; | ||
| 6 | |||
| 7 | impl<const N: usize> Spinlock<N> | ||
| 8 | where | ||
| 9 | Spinlock<N>: SpinlockValid, | ||
| 10 | { | ||
| 11 | /// Try to claim the spinlock. Will return `Some(Self)` if the lock is obtained, and `None` if the lock is | ||
| 12 | /// already in use somewhere else. | ||
| 13 | pub fn try_claim() -> Option<Self> { | ||
| 14 | let lock = pac::SIO.spinlock(N).read(); | ||
| 15 | if lock > 0 { | ||
| 16 | Some(Self(core::marker::PhantomData)) | ||
| 17 | } else { | ||
| 18 | None | ||
| 19 | } | ||
| 20 | } | ||
| 21 | |||
| 22 | /// Clear a locked spin-lock. | ||
| 23 | /// | ||
| 24 | /// # Safety | ||
| 25 | /// | ||
| 26 | /// Only call this function if you hold the spin-lock. | ||
| 27 | pub unsafe fn release() { | ||
| 28 | // Write (any value): release the lock | ||
| 29 | pac::SIO.spinlock(N).write_value(1); | ||
| 30 | } | ||
| 31 | } | ||
| 32 | |||
| 33 | impl<const N: usize> Drop for Spinlock<N> | ||
| 34 | where | ||
| 35 | Spinlock<N>: SpinlockValid, | ||
| 36 | { | ||
| 37 | fn drop(&mut self) { | ||
| 38 | // This is safe because we own the object, and hence hold the lock. | ||
| 39 | unsafe { Self::release() } | ||
| 40 | } | ||
| 41 | } | ||
| 42 | |||
| 43 | pub trait SpinlockValid {} | ||
| 44 | impl SpinlockValid for Spinlock<0> {} | ||
| 45 | impl SpinlockValid for Spinlock<1> {} | ||
| 46 | impl SpinlockValid for Spinlock<2> {} | ||
| 47 | impl SpinlockValid for Spinlock<3> {} | ||
| 48 | impl SpinlockValid for Spinlock<4> {} | ||
| 49 | impl SpinlockValid for Spinlock<5> {} | ||
| 50 | impl SpinlockValid for Spinlock<6> {} | ||
| 51 | impl SpinlockValid for Spinlock<7> {} | ||
| 52 | impl SpinlockValid for Spinlock<8> {} | ||
| 53 | impl SpinlockValid for Spinlock<9> {} | ||
| 54 | impl SpinlockValid for Spinlock<10> {} | ||
| 55 | impl SpinlockValid for Spinlock<11> {} | ||
| 56 | impl SpinlockValid for Spinlock<12> {} | ||
| 57 | impl SpinlockValid for Spinlock<13> {} | ||
| 58 | impl SpinlockValid for Spinlock<14> {} | ||
| 59 | impl SpinlockValid for Spinlock<15> {} | ||
| 60 | impl SpinlockValid for Spinlock<16> {} | ||
| 61 | impl SpinlockValid for Spinlock<17> {} | ||
| 62 | impl SpinlockValid for Spinlock<18> {} | ||
| 63 | impl SpinlockValid for Spinlock<19> {} | ||
| 64 | impl SpinlockValid for Spinlock<20> {} | ||
| 65 | impl SpinlockValid for Spinlock<21> {} | ||
| 66 | impl SpinlockValid for Spinlock<22> {} | ||
| 67 | impl SpinlockValid for Spinlock<23> {} | ||
| 68 | impl SpinlockValid for Spinlock<24> {} | ||
| 69 | impl SpinlockValid for Spinlock<25> {} | ||
| 70 | impl SpinlockValid for Spinlock<26> {} | ||
| 71 | impl SpinlockValid for Spinlock<27> {} | ||
| 72 | impl SpinlockValid for Spinlock<28> {} | ||
| 73 | impl SpinlockValid for Spinlock<29> {} | ||
| 74 | impl SpinlockValid for Spinlock<30> {} | ||
| 75 | impl SpinlockValid for Spinlock<31> {} | ||
diff --git a/embassy-rp/src/spinlock_mutex.rs b/embassy-rp/src/spinlock_mutex.rs new file mode 100644 index 000000000..85174cf86 --- /dev/null +++ b/embassy-rp/src/spinlock_mutex.rs | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | //! Mutex implementation utilizing an hardware spinlock | ||
| 2 | |||
| 3 | use core::marker::PhantomData; | ||
| 4 | use core::sync::atomic::Ordering; | ||
| 5 | |||
| 6 | use embassy_sync::blocking_mutex::raw::RawMutex; | ||
| 7 | |||
| 8 | use crate::spinlock::{Spinlock, SpinlockValid}; | ||
| 9 | |||
| 10 | /// A mutex that allows borrowing data across executors and interrupts by utilizing an hardware spinlock | ||
| 11 | /// | ||
| 12 | /// # Safety | ||
| 13 | /// | ||
| 14 | /// This mutex is safe to share between different executors and interrupts. | ||
| 15 | pub struct SpinlockRawMutex<const N: usize> { | ||
| 16 | _phantom: PhantomData<()>, | ||
| 17 | } | ||
| 18 | unsafe impl<const N: usize> Send for SpinlockRawMutex<N> {} | ||
| 19 | unsafe impl<const N: usize> Sync for SpinlockRawMutex<N> {} | ||
| 20 | |||
| 21 | impl<const N: usize> SpinlockRawMutex<N> { | ||
| 22 | /// Create a new `SpinlockRawMutex`. | ||
| 23 | pub const fn new() -> Self { | ||
| 24 | Self { _phantom: PhantomData } | ||
| 25 | } | ||
| 26 | } | ||
| 27 | |||
| 28 | unsafe impl<const N: usize> RawMutex for SpinlockRawMutex<N> | ||
| 29 | where | ||
| 30 | Spinlock<N>: SpinlockValid, | ||
| 31 | { | ||
| 32 | const INIT: Self = Self::new(); | ||
| 33 | |||
| 34 | fn lock<R>(&self, f: impl FnOnce() -> R) -> R { | ||
| 35 | // Store the initial interrupt state in stack variable | ||
| 36 | let interrupts_active = cortex_m::register::primask::read().is_active(); | ||
| 37 | |||
| 38 | // Spin until we get the lock | ||
| 39 | loop { | ||
| 40 | // Need to disable interrupts to ensure that we will not deadlock | ||
| 41 | // if an interrupt or higher prio locks the spinlock after we acquire the lock | ||
| 42 | cortex_m::interrupt::disable(); | ||
| 43 | // Ensure the compiler doesn't re-order accesses and violate safety here | ||
| 44 | core::sync::atomic::compiler_fence(Ordering::SeqCst); | ||
| 45 | if let Some(lock) = Spinlock::<N>::try_claim() { | ||
| 46 | // We just acquired the lock. | ||
| 47 | // 1. Forget it, so we don't immediately unlock | ||
| 48 | core::mem::forget(lock); | ||
| 49 | break; | ||
| 50 | } | ||
| 51 | // We didn't get the lock, enable interrupts if they were enabled before we started | ||
| 52 | if interrupts_active { | ||
| 53 | // safety: interrupts are only enabled, if they had been enabled before | ||
| 54 | unsafe { | ||
| 55 | cortex_m::interrupt::enable(); | ||
| 56 | } | ||
| 57 | } | ||
| 58 | } | ||
| 59 | |||
| 60 | let retval = f(); | ||
| 61 | |||
| 62 | // Ensure the compiler doesn't re-order accesses and violate safety here | ||
| 63 | core::sync::atomic::compiler_fence(Ordering::SeqCst); | ||
| 64 | // Release the spinlock to allow others to lock mutex again | ||
| 65 | // safety: this point is only reached a spinlock was acquired before | ||
| 66 | unsafe { | ||
| 67 | Spinlock::<N>::release(); | ||
| 68 | } | ||
| 69 | |||
| 70 | // Re-enable interrupts if they were enabled before the mutex was locked | ||
| 71 | if interrupts_active { | ||
| 72 | // safety: interrupts are only enabled, if they had been enabled before | ||
| 73 | unsafe { | ||
| 74 | cortex_m::interrupt::enable(); | ||
| 75 | } | ||
| 76 | } | ||
| 77 | |||
| 78 | retval | ||
| 79 | } | ||
| 80 | } | ||
| 81 | |||
| 82 | pub mod blocking_mutex { | ||
| 83 | //! Mutex implementation utilizing an hardware spinlock | ||
| 84 | use embassy_sync::blocking_mutex::Mutex; | ||
| 85 | |||
| 86 | use crate::spinlock_mutex::SpinlockRawMutex; | ||
| 87 | /// A mutex that allows borrowing data across executors and interrupts by utilizing an hardware spinlock. | ||
| 88 | /// | ||
| 89 | /// # Safety | ||
| 90 | /// | ||
| 91 | /// This mutex is safe to share between different executors and interrupts. | ||
| 92 | pub type SpinlockMutex<const N: usize, T> = Mutex<SpinlockRawMutex<N>, T>; | ||
| 93 | } | ||
diff --git a/tests/rp/src/bin/spinlock_mutex_multicore.rs b/tests/rp/src/bin/spinlock_mutex_multicore.rs new file mode 100644 index 000000000..ebcf1ca32 --- /dev/null +++ b/tests/rp/src/bin/spinlock_mutex_multicore.rs | |||
| @@ -0,0 +1,54 @@ | |||
| 1 | #![no_std] | ||
| 2 | #![no_main] | ||
| 3 | #[cfg(feature = "rp2040")] | ||
| 4 | teleprobe_meta::target!(b"rpi-pico"); | ||
| 5 | #[cfg(feature = "rp235xb")] | ||
| 6 | teleprobe_meta::target!(b"pimoroni-pico-plus-2"); | ||
| 7 | |||
| 8 | use defmt::{info, unwrap}; | ||
| 9 | use embassy_executor::Executor; | ||
| 10 | use embassy_rp::multicore::{spawn_core1, Stack}; | ||
| 11 | use embassy_rp::spinlock_mutex::SpinlockRawMutex; | ||
| 12 | use embassy_sync::channel::Channel; | ||
| 13 | use static_cell::StaticCell; | ||
| 14 | use {defmt_rtt as _, panic_probe as _}; | ||
| 15 | |||
| 16 | static mut CORE1_STACK: Stack<1024> = Stack::new(); | ||
| 17 | static EXECUTOR0: StaticCell<Executor> = StaticCell::new(); | ||
| 18 | static EXECUTOR1: StaticCell<Executor> = StaticCell::new(); | ||
| 19 | static CHANNEL0: Channel<SpinlockRawMutex<0>, bool, 1> = Channel::new(); | ||
| 20 | static CHANNEL1: Channel<SpinlockRawMutex<1>, bool, 1> = Channel::new(); | ||
| 21 | |||
| 22 | #[cortex_m_rt::entry] | ||
| 23 | fn main() -> ! { | ||
| 24 | let p = embassy_rp::init(Default::default()); | ||
| 25 | spawn_core1( | ||
| 26 | p.CORE1, | ||
| 27 | unsafe { &mut *core::ptr::addr_of_mut!(CORE1_STACK) }, | ||
| 28 | move || { | ||
| 29 | let executor1 = EXECUTOR1.init(Executor::new()); | ||
| 30 | executor1.run(|spawner| unwrap!(spawner.spawn(core1_task()))); | ||
| 31 | }, | ||
| 32 | ); | ||
| 33 | let executor0 = EXECUTOR0.init(Executor::new()); | ||
| 34 | executor0.run(|spawner| unwrap!(spawner.spawn(core0_task()))); | ||
| 35 | } | ||
| 36 | |||
| 37 | #[embassy_executor::task] | ||
| 38 | async fn core0_task() { | ||
| 39 | info!("CORE0 is running"); | ||
| 40 | let ping = true; | ||
| 41 | CHANNEL0.send(ping).await; | ||
| 42 | let pong = CHANNEL1.receive().await; | ||
| 43 | assert_eq!(ping, pong); | ||
| 44 | |||
| 45 | info!("Test OK"); | ||
| 46 | cortex_m::asm::bkpt(); | ||
| 47 | } | ||
| 48 | |||
| 49 | #[embassy_executor::task] | ||
| 50 | async fn core1_task() { | ||
| 51 | info!("CORE1 is running"); | ||
| 52 | let ping = CHANNEL0.receive().await; | ||
| 53 | CHANNEL1.send(ping).await; | ||
| 54 | } | ||
