1#[path = "fp.rs"]
2mod fp;
3#[path = "stack.rs"]
4mod stack;
5use stack::{Backing, check_guard_at};
6pub use stack::{
7 DEFAULT_MIN_STACK_SIZE, MIN_STACK_SIZE, Stack, StackAllocateFn, StackAllocator,
8 StackDeallocateFn, set_stack_allocator,
9};
10
11use alloc::rc::Rc;
12use core::{
13 cell::{Cell, RefCell, UnsafeCell},
14 future::Future,
15 pin::Pin,
16 ptr::NonNull,
17 task::{Context, Poll, Waker},
18};
19
20type Native = corosensei::Coroutine<(), (), (), Backing>;
21type Yielder = corosensei::Yielder<(), ()>;
22
23const INITIAL_FRAME: usize = 128;
25const MIN_ENTRY_STACK: usize = 1024;
27
28pub const TLS_SLOTS: usize = 4;
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum TlsError {
34 NotInCoroutine,
36 InvalidSlot,
38}
39
40type ErasedFuture = *mut (dyn Future<Output = ()> + 'static);
41#[derive(Clone, Copy)]
42struct Pending {
43 future: ErasedFuture,
44 cancel: bool,
45}
46struct Control {
47 native: UnsafeCell<Native>,
49 guard: NonNull<u8>,
51 #[cfg(all(feature = "crash", target_arch = "xtensa"))]
52 stack_bounds: StackBounds,
53 yielder: Cell<*const Yielder>,
55 pending: Cell<Option<Pending>>,
56 started: Cell<bool>,
57 result: Cell<Option<Result<i32, Cancelled>>>,
58 waker: RefCell<Option<Waker>>,
59 tls: [Cell<usize>; TLS_SLOTS],
60 native_context: Cell<*const ()>,
61}
62pub const MAX_CORES: usize = 8;
64
65pub type CoreIdProvider = fn() -> usize;
67
68#[cfg(any(not(target_os = "linux"), test))]
69fn single_core_id() -> usize {
70 0
71}
72
73#[cfg(any(not(target_os = "linux"), test))]
74struct PerCoreCurrent {
75 provider: Cell<CoreIdProvider>,
76 slots: [Cell<usize>; MAX_CORES],
77}
78
79#[cfg(any(not(target_os = "linux"), test))]
80impl PerCoreCurrent {
81 const fn new() -> Self {
82 Self {
83 provider: Cell::new(single_core_id),
84 slots: [const { Cell::new(0) }; MAX_CORES],
85 }
86 }
87
88 fn core_index(&self) -> usize {
89 let core = (self.provider.get())();
90 assert!(
91 core < MAX_CORES,
92 "stackful core id {core} exceeds MAX_CORES ({MAX_CORES})"
93 );
94 core
95 }
96
97 fn get(&self) -> *const Control {
98 let core = self.core_index();
99 self.slots[core].get() as *const Control
100 }
101
102 fn set(&self, value: *const Control) {
103 let core = self.core_index();
104 self.slots[core].set(value as usize);
105 #[cfg(all(feature = "crash", target_arch = "xtensa"))]
106 {
107 let bounds = unsafe { value.as_ref() }.map(|control| control.stack_bounds);
109 if let Some(slot) = PUBLISHED_STACKS.get(core) {
110 slot.set(bounds);
111 }
112 }
113 }
114
115 fn set_provider(&self, provider: CoreIdProvider) {
116 assert!(
117 self.slots.iter().all(|slot| slot.get() == 0),
118 "cannot change stackful core id provider while a coroutine is active"
119 );
120 self.provider.set(provider);
121 }
122}
123
124#[cfg(target_os = "linux")]
125std::thread_local! { static CURRENT: Cell<*const Control> = const { Cell::new(core::ptr::null()) }; }
126#[cfg(target_os = "linux")]
127fn current() -> *const Control {
128 CURRENT.with(Cell::get)
129}
130#[cfg(target_os = "linux")]
131fn set_current(value: *const Control) {
132 CURRENT.with(|c| c.set(value));
133}
134
135#[cfg(not(target_os = "linux"))]
136static CURRENT: critical_section::Mutex<PerCoreCurrent> =
137 critical_section::Mutex::new(PerCoreCurrent::new());
138#[cfg(not(target_os = "linux"))]
139fn current() -> *const Control {
140 critical_section::with(|cs| CURRENT.borrow(cs).get())
141}
142#[cfg(not(target_os = "linux"))]
143fn set_current(value: *const Control) {
144 critical_section::with(|cs| CURRENT.borrow(cs).set(value));
145}
146
147#[cfg(all(feature = "crash", target_arch = "xtensa"))]
149#[derive(Clone, Copy)]
150pub struct StackBounds {
151 pub start: usize,
152 pub end: usize,
153}
154
155#[cfg(all(feature = "crash", target_arch = "xtensa"))]
156use core::sync::atomic::{AtomicUsize, Ordering};
157
158#[cfg(all(feature = "crash", target_arch = "xtensa"))]
159struct PublishedStack {
160 start: AtomicUsize,
161 end: AtomicUsize,
162}
163
164#[cfg(all(feature = "crash", target_arch = "xtensa"))]
165impl PublishedStack {
166 fn set(&self, bounds: Option<StackBounds>) {
167 self.end.store(0, Ordering::SeqCst);
168 if let Some(bounds) = bounds {
169 self.start.store(bounds.start, Ordering::Relaxed);
170 self.end.store(bounds.end, Ordering::SeqCst);
171 }
172 }
173}
174
175#[cfg(all(feature = "crash", target_arch = "xtensa"))]
176static PUBLISHED_STACKS: [PublishedStack; 2] = [const {
177 PublishedStack {
178 start: AtomicUsize::new(0),
179 end: AtomicUsize::new(0),
180 }
181}; 2];
182
183#[cfg(all(feature = "crash", target_arch = "xtensa"))]
186pub fn current_stack_bounds(core: usize) -> Option<StackBounds> {
187 let slot = PUBLISHED_STACKS.get(core)?;
188 let end = slot.end.load(Ordering::SeqCst);
189 (end != 0).then(|| StackBounds {
190 start: slot.start.load(Ordering::Relaxed),
191 end,
192 })
193}
194
195pub unsafe fn set_core_id_provider(provider: CoreIdProvider) {
211 #[cfg(not(target_os = "linux"))]
212 critical_section::with(|cs| CURRENT.borrow(cs).set_provider(provider));
213 #[cfg(target_os = "linux")]
214 let _ = provider;
215}
216
217pub struct Coroutine {
219 control: Rc<Control>,
220}
221#[derive(Clone, Copy, Debug, PartialEq, Eq)]
224pub struct Cancelled;
225pub struct JoinHandle {
227 control: Rc<Control>,
228}
229
230impl Coroutine {
231 pub unsafe fn new<F: FnOnce() -> i32 + 'static>(stack: Stack, entry: F) -> Self {
258 assert!(
260 stack.usable_size()
261 >= size_of::<F>() + align_of::<F>() + INITIAL_FRAME + MIN_ENTRY_STACK,
262 "entry leaves too little stack"
263 );
264 let guard = stack.guard();
265 #[cfg(all(feature = "crash", target_arch = "xtensa"))]
266 let stack_bounds = StackBounds {
267 start: stack.top() - stack.usable_size(),
268 end: stack.top(),
269 };
270 let native = Native::with_stack(Backing(stack), move |yielder, ()| {
271 let control = unsafe { &*current() };
273 control.yielder.set(yielder);
274 fp::Environment::INITIAL.write();
275 let status = entry();
276 unsafe { finish(control, status) }
278 });
279 Self {
280 control: Rc::new(Control {
281 native: UnsafeCell::new(native),
282 guard,
283 #[cfg(all(feature = "crash", target_arch = "xtensa"))]
284 stack_bounds,
285 yielder: Cell::new(core::ptr::null()),
286 pending: Cell::new(None),
287 started: Cell::new(false),
288 result: Cell::new(None),
289 waker: RefCell::new(None),
290 tls: [const { Cell::new(0) }; TLS_SLOTS],
291 native_context: Cell::new(core::ptr::null()),
292 }),
293 }
294 }
295 pub unsafe fn set_native_context(&mut self, value: *const ()) {
299 self.control.native_context.set(value);
300 }
301
302 pub fn join_handle(&self) -> JoinHandle {
304 assert_eq!(
306 Rc::strong_count(&self.control),
307 1,
308 "join handle already exists"
309 );
310 JoinHandle {
311 control: self.control.clone(),
312 }
313 }
314 pub fn resume(&mut self, cx: &mut Context<'_>) -> Poll<i32> {
317 let c = Rc::as_ptr(&self.control);
318 loop {
319 match self.control.result.get() {
320 Some(Ok(result)) => return Poll::Ready(result),
321 Some(Err(Cancelled)) => return Poll::Pending,
322 None => {}
323 }
324 if let Some(Pending { future, .. }) = self.control.pending.get() {
325 if unsafe { Pin::new_unchecked(&mut *future) }
328 .poll(cx)
329 .is_pending()
330 {
331 return Poll::Pending;
332 }
333 self.control.pending.set(None);
334 }
335 self.control.check_guard();
336 let previous = current();
337 set_current(c);
338 self.control.started.set(true);
339 let environment = fp::Environment::read();
340 unsafe {
343 let native = &mut *self.control.native.get();
344 native.resume(());
345 if matches!(self.control.result.get(), Some(Ok(_))) {
346 native.force_reset();
349 }
350 }
351 environment.write();
352 set_current(previous);
353 self.control.check_guard();
354 }
355 }
356}
357impl Future for Coroutine {
358 type Output = i32;
359 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<i32> {
360 self.resume(cx)
361 }
362}
363impl Coroutine {
364 pub fn stop(&mut self) {
382 if !self.control.started.get() || self.control.result.get().is_some() {
383 return;
384 }
385 self.control.result.set(Some(Err(Cancelled)));
386 if let Some(w) = self.control.waker.borrow_mut().take() {
387 w.wake();
388 }
389 self.control.check_guard();
393 if let Some(Pending {
396 future,
397 cancel: true,
398 }) = self.control.pending.take()
399 {
400 struct Restore(*const Control);
402 impl Drop for Restore {
403 fn drop(&mut self) {
404 set_current(self.0);
405 }
406 }
407 let _restore = Restore(current());
408 set_current(core::ptr::null());
409 unsafe { core::ptr::drop_in_place(future) };
412 }
413 }
414}
415impl Drop for Coroutine {
416 fn drop(&mut self) {
417 self.control.native_context.set(core::ptr::null());
418 if self.control.started.get() && !matches!(self.control.result.get(), Some(Ok(_))) {
419 self.stop();
421 unsafe { (*self.control.native.get()).force_reset() };
428 }
429 }
430}
431impl Future for JoinHandle {
432 type Output = Result<i32, Cancelled>;
433 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
434 if let Some(result) = self.control.result.get() {
435 Poll::Ready(result)
436 } else {
437 let mut w = self.control.waker.borrow_mut();
438 if w.as_ref().is_none_or(|w| !w.will_wake(cx.waker())) {
439 *w = Some(cx.waker().clone());
440 }
441 Poll::Pending
442 }
443 }
444}
445pub async fn drive(coroutine: Coroutine) -> i32 {
447 coroutine.await
448}
449
450pub fn is_in_coroutine() -> bool {
452 !current().is_null()
453}
454
455pub fn suspend_on<F: Future>(future: F) -> F::Output {
461 suspend(future, false)
462}
463
464pub fn suspend_on_cancellable<F: Future>(future: F) -> F::Output {
467 suspend(future, true)
468}
469
470fn suspend<F: Future>(future: F, cancel: bool) -> F::Output {
471 let c = current();
472 if c.is_null() {
473 return task::block_on(future);
474 }
475 let mut output = None;
476 {
477 let mut wrapper = core::pin::pin!(async {
478 output = Some(future.await);
479 });
480 let erased: ErasedFuture = unsafe {
484 core::mem::transmute::<*mut dyn Future<Output = ()>, ErasedFuture>(
485 wrapper.as_mut().get_unchecked_mut(),
486 )
487 };
488 unsafe {
489 suspend_pending(
490 c,
491 Pending {
492 future: erased,
493 cancel,
494 },
495 )
496 };
497 }
499 output.expect("coroutine resumed before future completed")
500}
501
502#[inline(never)]
503unsafe fn suspend_pending(control: *const Control, pending: Pending) {
504 unsafe {
507 (*control).check_guard();
508 (*control).pending.set(Some(pending));
509 let environment = fp::Environment::read();
510 (*(*control).yielder.get()).suspend(());
511 environment.write();
512 (*control).check_guard();
513 }
514}
515
516pub fn native_context() -> *const () {
518 unsafe { current().as_ref() }.map_or(core::ptr::null(), |control| control.native_context.get())
519}
520
521pub unsafe fn set_native_context(value: *const ()) {
526 if let Some(control) = unsafe { current().as_ref() } {
527 control.native_context.set(value);
528 }
529}
530
531pub fn tls_get(slot: usize) -> Result<usize, TlsError> {
536 if slot >= TLS_SLOTS {
537 return Err(TlsError::InvalidSlot);
538 }
539 let c = current();
540 if c.is_null() {
541 return Err(TlsError::NotInCoroutine);
542 }
543 let tls = unsafe { &(*c).tls };
545 Ok(tls[slot].get())
546}
547
548pub fn tls_set(slot: usize, value: usize) -> Result<(), TlsError> {
553 if slot >= TLS_SLOTS {
554 return Err(TlsError::InvalidSlot);
555 }
556 let c = current();
557 if c.is_null() {
558 return Err(TlsError::NotInCoroutine);
559 }
560 let tls = unsafe { &(*c).tls };
562 tls[slot].set(value);
563 Ok(())
564}
565
566impl Control {
567 fn check_guard(&self) {
568 unsafe { check_guard_at(self.guard) };
570 }
571}
572
573unsafe fn finish(c: *const Control, status: i32) -> ! {
578 unsafe {
579 (*c).native_context.set(core::ptr::null());
580 (*c).result.set(Some(Ok(status)));
581 let waker = (*c).waker.borrow_mut().take();
582 if let Some(w) = waker {
583 w.wake();
584 }
585 (*c).check_guard();
586 (*(*c).yielder.get()).suspend(());
588 }
589 panic!("completed coroutine resumed");
590}
591
592pub unsafe fn exit(status: i32) -> ! {
607 let c = current();
608 assert!(!c.is_null(), "exit outside a coroutine");
609 unsafe { finish(c, status) }
610}
611
612pub async unsafe fn spawn<F: FnOnce() -> i32 + 'static>(
619 manager: &'static task::Manager,
620 parent: task::TaskIdentifier,
621 name: &str,
622 stack: Stack,
623 entry: F,
624) -> task::Result<(task::JoinHandle<i32>, task::TaskIdentifier)> {
625 unsafe { spawn_with_result(manager, parent, name, stack, entry, core::convert::identity).await }
626}
627
628pub async unsafe fn spawn_with_result<F, Map, T>(
633 manager: &'static task::Manager,
634 parent: task::TaskIdentifier,
635 name: &str,
636 stack: Stack,
637 entry: F,
638 map: Map,
639) -> task::Result<(task::JoinHandle<T>, task::TaskIdentifier)>
640where
641 F: FnOnce() -> i32 + 'static,
642 Map: FnOnce(i32) -> T + 'static,
643 T: 'static,
644{
645 unsafe { spawn_with_driver(manager, parent, name, stack, entry, drive, map).await }
646}
647
648pub async unsafe fn spawn_with_driver<F, Driver, Run, Map, T>(
653 manager: &'static task::Manager,
654 parent: task::TaskIdentifier,
655 name: &str,
656 stack: Stack,
657 entry: F,
658 driver: Run,
659 map: Map,
660) -> task::Result<(task::JoinHandle<T>, task::TaskIdentifier)>
661where
662 F: FnOnce() -> i32 + 'static,
663 Driver: Future<Output = i32> + 'static,
664 Run: FnOnce(Coroutine) -> Driver + 'static,
665 Map: FnOnce(i32) -> T + 'static,
666 T: 'static,
667{
668 let caller = manager.get_current_task_identifier().await;
669 let spawner = manager.get_spawner(caller).await?;
670 let coroutine = unsafe { Coroutine::new(stack, entry) };
671 manager
672 .spawn(parent, name, Some(spawner), move |_| async move {
673 map(driver(coroutine).await)
674 })
675 .await
676}
677
678pub const fn control_allocation_size() -> usize {
680 core::mem::size_of::<Control>() + 2 * core::mem::size_of::<usize>()
681}
682
683#[cfg(test)]
684mod per_core_tests {
685 use super::*;
686
687 std::thread_local! {
688 static SIMULATED_CORE: Cell<usize> = const { Cell::new(0) };
689 }
690
691 fn simulated_core_id() -> usize {
692 SIMULATED_CORE.with(Cell::get)
693 }
694
695 fn out_of_range_core_id() -> usize {
696 MAX_CORES
697 }
698
699 #[test]
700 fn default_provider_uses_core_zero() {
701 let table = PerCoreCurrent::new();
702 assert!(table.get().is_null());
703 let sentinel = 0x1000usize as *const Control;
704 table.set(sentinel);
705 assert_eq!(table.get(), sentinel);
706 table.set(core::ptr::null());
707 assert!(table.get().is_null());
708 }
709
710 #[test]
711 fn isolates_current_pointer_per_core() {
712 let table = PerCoreCurrent::new();
713 table.set_provider(simulated_core_id);
714
715 let core0_ptr = 0x2000usize as *const Control;
716 let core1_ptr = 0x3000usize as *const Control;
717 let last_core_ptr = 0x4000usize as *const Control;
718
719 SIMULATED_CORE.with(|c| c.set(0));
720 table.set(core0_ptr);
721
722 SIMULATED_CORE.with(|c| c.set(1));
723 assert!(table.get().is_null());
724 table.set(core1_ptr);
725
726 SIMULATED_CORE.with(|c| c.set(MAX_CORES - 1));
727 assert!(table.get().is_null());
728 table.set(last_core_ptr);
729
730 SIMULATED_CORE.with(|c| c.set(0));
731 assert_eq!(table.get(), core0_ptr);
732 SIMULATED_CORE.with(|c| c.set(1));
733 assert_eq!(table.get(), core1_ptr);
734 SIMULATED_CORE.with(|c| c.set(MAX_CORES - 1));
735 assert_eq!(table.get(), last_core_ptr);
736
737 table.set(core::ptr::null());
739 SIMULATED_CORE.with(|c| c.set(1));
740 table.set(core::ptr::null());
741 SIMULATED_CORE.with(|c| c.set(0));
742 table.set(core::ptr::null());
743 table.set_provider(single_core_id);
744 }
745
746 #[test]
747 #[should_panic(expected = "while a coroutine is active")]
748 fn rejects_provider_change_while_coroutine_active() {
749 let table = PerCoreCurrent::new();
750 table.set(0x5000usize as *const Control);
751 table.set_provider(simulated_core_id);
752 }
753
754 #[test]
755 #[should_panic(expected = "exceeds MAX_CORES")]
756 fn rejects_out_of_range_core_id() {
757 let table = PerCoreCurrent::new();
758 table.set_provider(out_of_range_core_id);
759 let _ = table.get();
760 }
761}