Skip to main content

task/manager/
lifecycle.rs

1use super::*;
2use alloc::boxed::Box;
3use core::{
4    future::{Future, poll_fn},
5    pin::Pin,
6    task::{Context, Poll, RawWakerVTable},
7    time::Duration,
8};
9use embassy_executor::{
10    SpawnToken, Spawner,
11    raw::{AvailableTask, TaskStorage},
12};
13use embassy_time::Timer;
14
15use portable_atomic::{AtomicPtr, Ordering};
16
17static EMBASSY_WAKER_VTABLE: AtomicPtr<RawWakerVTable> = AtomicPtr::new(core::ptr::null_mut());
18
19fn remember_vtable(vtable: &'static RawWakerVTable) {
20    EMBASSY_WAKER_VTABLE.store(core::ptr::from_ref(vtable).cast_mut(), Ordering::Relaxed);
21}
22
23fn embassy_vtable() -> *const RawWakerVTable {
24    EMBASSY_WAKER_VTABLE.load(Ordering::Relaxed)
25}
26
27/// Only TaskStorage polls this wrapper, so its context is an Embassy context.
28/// Embassy 0.10 keeps try_task_from_waker private. Remember its vtable here
29/// to reject foreign wakers before reading their opaque task identity.
30/// This avoids relying on TaskRef's layout or private executor symbols.
31pub(super) struct TaskFuture {
32    future: Pin<Box<dyn Future<Output = ()>>>,
33    #[cfg(feature = "crash")]
34    active_task: crate::active_task::ActiveTask,
35    #[cfg(feature = "metrics")]
36    instrumentation: crate::metrics::TaskInstrumentation,
37}
38
39// SAFETY: Embassy needs `Send` only to enqueue a token through a `SendSpawner`;
40// the storage itself is Sync whatever its future. `spawn_on` enqueues through
41// the caller's !Send `Spawner`, so its futures never leave the executor thread.
42// `spawn_send` futures cross threads exactly once, before their first poll,
43// while their state is only the captures checked `Send` there. Embassy then
44// creates the user future, polls it and drops it on the target executor only.
45// This is the contract of Embassy's `_spawn_async_fn` for `#[task]` functions.
46unsafe impl Send for TaskFuture {}
47
48impl Future for TaskFuture {
49    type Output = ();
50    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
51        remember_vtable(cx.waker().vtable());
52        #[cfg(feature = "crash")]
53        let _active_task = self.active_task.enter();
54        #[cfg(feature = "metrics")]
55        {
56            // Both times are read inside the executor's write sections, so
57            // readers rarely extrapolate a finished poll; they clamp the rest.
58            let instrumentation = self.instrumentation;
59            let start = instrumentation.executor.begin_poll();
60            let result = self.future.as_mut().poll(cx);
61            let end = instrumentation.executor.end_period();
62            instrumentation.task.record_poll(end.saturating_sub(start));
63            result
64        }
65        #[cfg(not(feature = "metrics"))]
66        self.future.as_mut().poll(cx)
67    }
68}
69
70impl Manager {
71    /// Spawn on the calling executor. An explicit foreign executor is rejected;
72    /// use `spawn_send` to start work on another executor.
73    /// Desktop and browser synchronous adapters may use the spawner registered on this thread.
74    pub async fn spawn<FunctionType, FutureType, ReturnType>(
75        &'static self,
76        parent_task: TaskIdentifier,
77        name: &str,
78        spawner: Option<usize>,
79        function: FunctionType,
80    ) -> Result<(JoinHandle<ReturnType>, TaskIdentifier)>
81    where
82        FunctionType: FnOnce(TaskIdentifier) -> FutureType + 'static,
83        FutureType: Future<Output = ReturnType> + 'static,
84        ReturnType: 'static,
85    {
86        let local = Self::local_spawner().await?;
87        self.spawn_on(local, parent_task, name, spawner, function)
88            .await
89    }
90
91    /// Bootstrap or spawn using a caller-owned local spawner. Its !Send type
92    /// enforces Embassy's thread affinity, including before the first poll.
93    pub async fn spawn_on<FunctionType, FutureType, ReturnType>(
94        &'static self,
95        local: Spawner,
96        parent_task: TaskIdentifier,
97        name: &str,
98        spawner: Option<usize>,
99        function: FunctionType,
100    ) -> Result<(JoinHandle<ReturnType>, TaskIdentifier)>
101    where
102        FunctionType: FnOnce(TaskIdentifier) -> FutureType + 'static,
103        FutureType: Future<Output = ReturnType> + 'static,
104        ReturnType: 'static,
105    {
106        let mut inner = self.0.write().await;
107        let (selected, _) = self.reserve_spawner(Some(local.executor_id()), spawner)?;
108        self.enqueue(&mut inner, selected, parent_task, name, function, |token| {
109            local.spawn(token)
110        })
111    }
112
113    /// Spawn a Send future on a specific registered executor.
114    ///
115    /// The task stays on that executor until it exits. An invalid identifier
116    /// returns `InvalidSpawnerIdentifier`.
117    ///
118    /// ```compile_fail
119    /// async fn non_send_future(manager: &'static task::Manager, executor: task::SpawnerIdentifier) {
120    ///     let root = task::Manager::ROOT_TASK_IDENTIFIER;
121    ///     manager.spawn_on_executor(root, "", executor, |_| async {
122    ///         let local = std::rc::Rc::new(());
123    ///         task::yield_now().await;
124    ///         drop(local);
125    ///     }).await.unwrap();
126    /// }
127    /// ```
128    pub async fn spawn_on_executor<FunctionType, FutureType, ReturnType>(
129        &'static self,
130        parent_task: TaskIdentifier,
131        name: &str,
132        executor: SpawnerIdentifier,
133        function: FunctionType,
134    ) -> Result<(JoinHandle<ReturnType>, TaskIdentifier)>
135    where
136        FunctionType: FnOnce(TaskIdentifier) -> FutureType + Send + 'static,
137        FutureType: Future<Output = ReturnType> + Send + 'static,
138        ReturnType: Send + 'static,
139    {
140        self.spawn_send(parent_task, name, Some(executor), function)
141            .await
142    }
143
144    /// Spawn on any registered executor: `spawner`, or the least-loaded one.
145    /// Only the closure and the result cross threads. The closure runs on the
146    /// target executor, so its future may be !Send, as with Embassy's tasks.
147    /// ```
148    /// async fn remote(manager: &'static task::Manager) {
149    ///     let state = synchronization::Arc::new(());
150    ///     let root = task::Manager::ROOT_TASK_IDENTIFIER;
151    ///     let _ = manager.spawn_send(root, "", None, move |_| async move {
152    ///         let local = std::rc::Rc::new(state);
153    ///         task::yield_now().await;
154    ///         drop(local)
155    ///     });
156    /// }
157    /// ```
158    /// ```compile_fail
159    /// async fn capture(manager: &'static task::Manager) {
160    ///     let state = std::rc::Rc::new(());
161    ///     let root = task::Manager::ROOT_TASK_IDENTIFIER;
162    ///     let _ = manager.spawn_send(root, "", None, move |_| async move { drop(state) });
163    /// }
164    /// ```
165    /// ```compile_fail
166    /// async fn output(manager: &'static task::Manager) {
167    ///     let root = task::Manager::ROOT_TASK_IDENTIFIER;
168    ///     let _ = manager.spawn_send(root, "", None, |_| async { std::rc::Rc::new(()) });
169    /// }
170    /// ```
171    pub async fn spawn_send<FunctionType, FutureType, ReturnType>(
172        &'static self,
173        parent_task: TaskIdentifier,
174        name: &str,
175        spawner: Option<usize>,
176        function: FunctionType,
177    ) -> Result<(JoinHandle<ReturnType>, TaskIdentifier)>
178    where
179        FunctionType: FnOnce(TaskIdentifier) -> FutureType + Send + 'static,
180        FutureType: Future<Output = ReturnType> + 'static,
181        ReturnType: Send + 'static,
182    {
183        // `enqueue`'s future owns only these, plus Send identifiers and name,
184        // until its first poll on the target executor (see TaskFuture's Send).
185        fn sendable<T: Send>(_: &T) {}
186        sendable(&self);
187        sendable(&function);
188        let mut inner = self.0.write().await;
189        let (selected, remote) = self.reserve_spawner(None, spawner)?;
190        self.enqueue(&mut inner, selected, parent_task, name, function, |token| {
191            remote.spawn(token)
192        })
193    }
194
195    /// Register, store and enqueue a task reserved on `selected`. No await
196    /// occurs between reservation and enqueueing; any failure rolls back.
197    fn enqueue<FunctionType, FutureType, ReturnType>(
198        &'static self,
199        inner: &mut Inner,
200        selected: usize,
201        parent_task: TaskIdentifier,
202        name: &str,
203        function: FunctionType,
204        start: impl FnOnce(SpawnToken<TaskFuture>),
205    ) -> Result<(JoinHandle<ReturnType>, TaskIdentifier)>
206    where
207        FunctionType: FnOnce(TaskIdentifier) -> FutureType + 'static,
208        FutureType: Future<Output = ReturnType> + 'static,
209        ReturnType: 'static,
210    {
211        let result = (|| {
212            let identifier = Self::register_inner(inner, parent_task, name)?;
213            #[cfg(all(feature = "profiling", target_os = "linux"))]
214            let profiling_name = inner.tasks[&identifier].name.clone();
215            let (parent, child) = JoinHandle::new();
216            #[cfg(feature = "metrics")]
217            let executor = self.spawner_counters(selected);
218            let mut future = Some(move || -> Pin<Box<dyn Future<Output = ()>>> {
219                Box::pin(async move {
220                    #[cfg(all(feature = "profiling", target_os = "linux"))]
221                    let result = crate::profiling::instrument(
222                        self as *const Manager as usize,
223                        identifier.into(),
224                        &profiling_name,
225                        selected,
226                        function(identifier),
227                    )
228                    .await;
229                    #[cfg(not(all(feature = "profiling", target_os = "linux")))]
230                    let result = function(identifier).await;
231                    // Complete metadata cleanup before publishing the result.
232                    let _ = self.unregister(identifier).await;
233                    child.signal(result);
234                })
235            });
236            // TaskStorage is retained forever: stale wakers and queued exited
237            // tasks can still touch its header. Only the boxed future is freed
238            // by Embassy's drop_in_place on Poll::Ready. Claiming fails while
239            // Embassy still owns a slot, so reuse is executor-safe, including
240            // on another executor, which Embassy explicitly allows.
241            loop {
242                for (index, slot) in inner.slots.iter().enumerate() {
243                    if let Some(available) = AvailableTask::claim(slot) {
244                        let future = future.take().unwrap();
245                        #[cfg(feature = "metrics")]
246                        let instrumentation = crate::metrics::TaskInstrumentation {
247                            task: inner.counters[index],
248                            executor,
249                        };
250                        // The claim orders this reset after the previous
251                        // task's last poll, so the slot has one writer.
252                        #[cfg(feature = "metrics")]
253                        instrumentation.task.reset();
254                        #[cfg(not(feature = "metrics"))]
255                        let _ = index;
256                        let token = available.initialize(move || TaskFuture {
257                            future: future(),
258                            #[cfg(feature = "crash")]
259                            active_task: crate::active_task::ActiveTask::new(identifier, name),
260                            #[cfg(feature = "metrics")]
261                            instrumentation,
262                        });
263                        // Embassy's id() truncates pointers to u32 on 64-bit hosts.
264                        // Use the full public waker data identity instead; TaskStorage
265                        // is repr(C), with its header at offset zero.
266                        let internal = core::ptr::from_ref(*slot) as usize;
267                        let metadata = inner.tasks.get_mut(&identifier).unwrap();
268                        metadata.internal_identifier = internal;
269                        metadata.spawner_identifier = selected;
270                        #[cfg(feature = "metrics")]
271                        {
272                            metadata.instrumentation = Some(instrumentation);
273                        }
274                        inner.identifiers.insert(internal, identifier);
275                        start(token);
276                        return Ok((parent, identifier));
277                    }
278                }
279                if inner.slots.len() >= inner.maximum_tasks {
280                    inner.tasks.remove(&identifier);
281                    return Err(Error::TooManyTasks);
282                }
283                // Two slots per allocation, capped exactly at the configured limit.
284                let first = inner.slots.len();
285                let count = (inner.maximum_tasks - first).min(2);
286                if inner.static_slots.is_empty() {
287                    let chunk = (0..count)
288                        .map(|_| TaskStorage::<TaskFuture>::new())
289                        .collect::<alloc::vec::Vec<_>>()
290                        .into_boxed_slice();
291                    inner.slots.extend(Box::leak(chunk).iter());
292                } else {
293                    inner.slots.extend(
294                        inner.static_slots[first..first + count]
295                            .iter()
296                            .map(|slot| &slot.0),
297                    );
298                }
299                #[cfg(feature = "metrics")]
300                {
301                    let counters = (0..count)
302                        .map(|_| crate::metrics::TaskCounters::new())
303                        .collect::<alloc::vec::Vec<_>>()
304                        .into_boxed_slice();
305                    inner.counters.extend(Box::leak(counters).iter());
306                }
307            }
308        })();
309        if result.is_err() {
310            self.release_spawner(selected);
311        }
312        result
313    }
314
315    pub async fn sleep(duration: Duration) {
316        let nanoseconds = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX);
317        Timer::at(deadline_after_nanoseconds(nanoseconds)).await
318    }
319
320    /// Return an error under block_on or any executor with a foreign waker.
321    pub async fn get_current_internal_identifier() -> Result<usize> {
322        poll_fn(|cx| {
323            let expected = embassy_vtable();
324            Poll::Ready(if core::ptr::eq(cx.waker().vtable(), expected) {
325                Ok(cx.waker().data() as usize)
326            } else {
327                Err(Error::ThreadNotRegistered)
328            })
329        })
330        .await
331    }
332
333    pub async fn try_get_current_task_identifier(&self) -> Result<TaskIdentifier> {
334        let internal = Self::get_current_internal_identifier().await?;
335        let mut inner = self.0.write().await;
336        if let Some(identifier) = inner.identifiers.get(&internal) {
337            return Ok(*identifier);
338        }
339        // A new independent manager may adopt its first Embassy task as root.
340        // Once established, an unknown task can never replace it.
341        if inner.root_established {
342            return Err(Error::ThreadNotRegistered);
343        }
344        let root = Self::register_inner(&mut inner, Self::ROOT_TASK_IDENTIFIER, "Root")?;
345        inner.tasks.get_mut(&root).unwrap().internal_identifier = internal;
346        inner.identifiers.insert(internal, root);
347        Ok(root)
348    }
349
350    /// Compatibility API. Unknown tasks fail closed; use the fallible variant
351    /// when callers need to handle missing registration.
352    pub async fn get_current_task_identifier(&self) -> TaskIdentifier {
353        self.try_get_current_task_identifier()
354            .await
355            .expect("task is not registered")
356    }
357}