Skip to main content

hazard3_executor/platform/
cortex_m.rs

1#[cfg(any(feature = "executor-thread", feature = "executor-interrupt"))]
2struct CortexMPender;
3
4#[cfg(any(feature = "executor-thread", feature = "executor-interrupt"))]
5pender_impl!(CortexMPender);
6
7#[cfg(any(feature = "executor-thread", feature = "executor-interrupt"))]
8impl crate::pender::Pender for CortexMPender {
9    fn pend(context: *mut ()) {
10        unsafe {
11            // Safety: `context` is either `usize::MAX` created by `Executor::run`, or a valid interrupt
12            // request number given to `InterruptExecutor::start`.
13
14            let context = context as usize;
15
16            #[cfg(feature = "executor-thread")]
17            // Try to make Rust optimize the branching away if we only use thread mode.
18            if !cfg!(feature = "executor-interrupt") || context == THREAD_PENDER {
19                core::arch::asm!("sev");
20                return;
21            }
22
23            #[cfg(feature = "executor-interrupt")]
24            {
25                use cortex_m::interrupt::InterruptNumber;
26                use cortex_m::peripheral::NVIC;
27
28                #[derive(Clone, Copy)]
29                struct Irq(u16);
30                unsafe impl InterruptNumber for Irq {
31                    fn number(self) -> u16 {
32                        self.0
33                    }
34                }
35
36                let irq = Irq(context as u16);
37
38                // STIR is faster, but is only available in v7 and higher.
39                #[cfg(not(armv6m))]
40                {
41                    let mut nvic: NVIC = core::mem::transmute(());
42                    nvic.request(irq);
43                }
44
45                #[cfg(armv6m)]
46                NVIC::pend(irq);
47            }
48        }
49    }
50}
51
52#[cfg(feature = "executor-thread")]
53pub use thread::*;
54#[cfg(feature = "executor-thread")]
55mod thread {
56    pub(super) const THREAD_PENDER: usize = usize::MAX;
57
58    use core::arch::asm;
59    use core::marker::PhantomData;
60
61    pub use hazard3_executor_macros::main_cortex_m as main;
62
63    use crate::{Spawner, raw};
64
65    /// Thread mode executor, using WFE/SEV.
66    ///
67    /// This is the simplest and most common kind of executor. It runs on
68    /// thread mode (at the lowest priority level), and uses the `WFE` ARM instruction
69    /// to sleep when it has no more work to do. When a task is woken, a `SEV` instruction
70    /// is executed, to make the `WFE` exit from sleep and poll the task.
71    ///
72    /// This executor allows for ultra low power consumption for chips where `WFE`
73    /// triggers low-power sleep without extra steps. If your chip requires extra steps,
74    /// you may use [`raw::Executor`] directly to program custom behavior.
75    pub struct Executor {
76        inner: raw::Executor,
77        not_send: PhantomData<*mut ()>,
78    }
79
80    impl Executor {
81        /// Create a new Executor.
82        pub fn new() -> Self {
83            Self {
84                inner: raw::Executor::new(THREAD_PENDER as *mut ()),
85                not_send: PhantomData,
86            }
87        }
88
89        /// Run the executor.
90        ///
91        /// The `init` closure is called with a [`Spawner`] that spawns tasks on
92        /// this executor. Use it to spawn the initial task(s). After `init` returns,
93        /// the executor starts running the tasks.
94        ///
95        /// To spawn more tasks later, you may keep copies of the [`Spawner`] (it is `Copy`),
96        /// for example by passing it as an argument to the initial tasks.
97        ///
98        /// This function requires `&'static mut self`. This means you have to store the
99        /// Executor instance in a place where it'll live forever and grants you mutable
100        /// access. There's a few ways to do this:
101        ///
102        /// - a [StaticCell](https://docs.rs/static_cell/latest/static_cell/) (safe)
103        /// - a `static mut` (unsafe)
104        /// - a local variable in a function you know never returns (like `fn main() -> !`), upgrading its lifetime with `transmute`. (unsafe)
105        ///
106        /// This function never returns.
107        pub fn run(&'static mut self, init: impl FnOnce(Spawner)) -> ! {
108            init(self.inner.spawner());
109
110            loop {
111                unsafe {
112                    self.inner.poll();
113                    crate::trace_idle();
114                    asm!("wfe");
115                };
116            }
117        }
118    }
119}
120
121#[cfg(feature = "executor-interrupt")]
122pub use interrupt::*;
123#[cfg(feature = "executor-interrupt")]
124mod interrupt {
125    use core::cell::{Cell, UnsafeCell};
126    use core::mem::MaybeUninit;
127
128    use cortex_m::interrupt::InterruptNumber;
129    use cortex_m::peripheral::NVIC;
130    use critical_section::Mutex;
131
132    use crate::raw;
133
134    /// Interrupt mode executor.
135    ///
136    /// This executor runs tasks in interrupt mode. The interrupt handler is set up
137    /// to poll tasks, and when a task is woken the interrupt is pended from software.
138    ///
139    /// This allows running async tasks at a priority higher than thread mode. One
140    /// use case is to leave thread mode free for non-async tasks. Another use case is
141    /// to run multiple executors: one in thread mode for low priority tasks and another in
142    /// interrupt mode for higher priority tasks. Higher priority tasks will preempt lower
143    /// priority ones.
144    ///
145    /// It is even possible to run multiple interrupt mode executors at different priorities,
146    /// by assigning different priorities to the interrupts. For an example on how to do this,
147    /// See the 'multiprio' example for 'embassy-nrf'.
148    ///
149    /// To use it, you have to pick an interrupt that won't be used by the hardware.
150    /// Some chips reserve some interrupts for this purpose, sometimes named "software interrupts" (SWI).
151    /// If this is not the case, you may use an interrupt from any unused peripheral.
152    ///
153    /// It is somewhat more complex to use, it's recommended to use the thread-mode
154    /// [`Executor`](crate::Executor) instead, if it works for your use case.
155    pub struct InterruptExecutor {
156        started: Mutex<Cell<bool>>,
157        executor: UnsafeCell<MaybeUninit<raw::Executor>>,
158    }
159
160    unsafe impl Send for InterruptExecutor {}
161    unsafe impl Sync for InterruptExecutor {}
162
163    impl InterruptExecutor {
164        /// Create a new, not started `InterruptExecutor`.
165        #[inline]
166        pub const fn new() -> Self {
167            Self {
168                started: Mutex::new(Cell::new(false)),
169                executor: UnsafeCell::new(MaybeUninit::uninit()),
170            }
171        }
172
173        /// Executor interrupt callback.
174        ///
175        /// # Safety
176        ///
177        /// - You MUST call this from the interrupt handler, and from nowhere else.
178        /// - You must not call this before calling `start()`.
179        pub unsafe fn on_interrupt(&'static self) {
180            let executor = unsafe { (&*self.executor.get()).assume_init_ref() };
181            executor.poll();
182        }
183
184        /// Start the executor.
185        ///
186        /// This initializes the executor, enables the interrupt, and returns.
187        /// The executor keeps running in the background through the interrupt.
188        ///
189        /// This returns a [`SendSpawner`] you can use to spawn tasks on it. A [`SendSpawner`]
190        /// is returned instead of a [`Spawner`](crate::Spawner) because the executor effectively runs in a
191        /// different "thread" (the interrupt), so spawning tasks on it is effectively
192        /// sending them.
193        ///
194        /// To obtain a [`Spawner`](crate::Spawner) for this executor, use [`Spawner::for_current_executor()`](crate::Spawner::for_current_executor()) from
195        /// a task running in it.
196        ///
197        /// # Interrupt requirements
198        ///
199        /// You must write the interrupt handler yourself, and make it call [`on_interrupt()`](Self::on_interrupt).
200        ///
201        /// This method already enables (unmasks) the interrupt, you must NOT do it yourself.
202        ///
203        /// You must set the interrupt priority before calling this method. You MUST NOT
204        /// do it after.
205        ///
206        /// [`SendSpawner`]: crate::SendSpawner
207        pub fn start(&'static self, irq: impl InterruptNumber) -> crate::SendSpawner {
208            if critical_section::with(|cs| self.started.borrow(cs).replace(true)) {
209                panic!("InterruptExecutor::start() called multiple times on the same executor.");
210            }
211
212            unsafe {
213                (&mut *self.executor.get())
214                    .as_mut_ptr()
215                    .write(raw::Executor::new(irq.number() as *mut ()))
216            }
217
218            let executor = unsafe { (&*self.executor.get()).assume_init_ref() };
219
220            unsafe { NVIC::unmask(irq) }
221
222            executor.spawner().make_send()
223        }
224
225        /// Get a SendSpawner for this executor
226        ///
227        /// This returns a [`SendSpawner`](crate::SendSpawner) you can use to spawn tasks on this
228        /// executor.
229        ///
230        /// This MUST only be called on an executor that has already been started.
231        /// The function will panic otherwise.
232        pub fn spawner(&'static self) -> crate::SendSpawner {
233            if !critical_section::with(|cs| self.started.borrow(cs).get()) {
234                panic!("InterruptExecutor::spawner() called on uninitialized executor.");
235            }
236            let executor = unsafe { (&*self.executor.get()).assume_init_ref() };
237            executor.spawner().make_send()
238        }
239    }
240}