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
27pub(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
39unsafe 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 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 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 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 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 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 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 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 let _ = self.unregister(identifier).await;
233 child.signal(result);
234 })
235 });
236 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 #[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 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 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 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 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 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}