Skip to main content

embassy_executor/platform/
cortex_m.rs

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