//! Fibers: stacks and the context switch (ADR 0011). //! //! Actors (`sched`) and `ctl` handler bodies (`handlers`) run on fibers: //! asymmetric coroutines that `resume` until they `suspend` or return. //! The runtime supports Linux on x86_64 and aarch64, and nothing else //! (ADR 0011, 2026-10-12 note). //! //! - **Stacks** are the runtime's own: an anonymous mapping with a guard //! page at its low end, committed lazily by the kernel. Their tops are //! aligned on [`REGION`], so that a stack's memory, page tables //! included, can be given back while its fiber is suspended //! ([`Coroutine::hibernate`], ADR 0028). //! - **The switch** is the runtime's own: it saves the callee-saved //! registers (and the floating-point control words) on the current //! stack, stores the stack pointer, and loads the other one. A suspended //! fiber is just its saved stack pointer, so it may resume on any //! thread, and its stack can be copied and written back //! ([`Coroutine::snapshot`]). `scripts/aarch64.sh` runs the tests on //! aarch64 under qemu. //! //! Rules: //! - a fiber is never dropped while suspended: its frames would never run //! their drops; //! - code on a fiber must not hold thread-local state across a suspension, //! since it may resume on another thread (see `sched::Fiber`). /// A fiber stack: at least `size` usable bytes above one guard page. pub(crate) struct Stack { /// The mapping, guard page first. base: *mut u8, len: usize, /// The usable size requested from [`Stack::new`], before guard, /// colouring and alignment overhead. Keeps the size-specific pools /// honest without exposing the mapping's geometry. size: usize, /// Aligned on [`REGION`]: what [`Stack::release`] gives back ends here. /// The mapping's last bytes, above it, are never used. region_top: usize, /// Where the stack starts (it grows down): `region_top` less this /// stack's color. top: usize, } /// Stacks start a varying distance below their aligned top, in steps of a /// page and a cache line. Aligned alike, the top frames of every stack fell /// in the same cache sets: a 1,000-actor ring (`tests/bench/messages.lse`) /// ran 5% slower, most of it in `tl_fiber_switch`. The pages above a /// stack's start are never touched, so a color costs no memory. const COLORS: usize = 32; static NEXT_COLOR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); // SAFETY: a stack is plain memory, owned by one fiber at a time. unsafe impl Send for Stack {} /// The kernel's page size: 4 KiB on x86_64, and 4, 16 or 64 KiB on /// aarch64, depending on the kernel. The guard page and `madvise` must /// use it. fn page() -> usize { static PAGE: std::sync::OnceLock = std::sync::OnceLock::new(); // SAFETY: `sysconf` has no preconditions. *PAGE.get_or_init(|| match unsafe { libc::sysconf(libc::_SC_PAGESIZE) } { n if n > 0 => n as usize, _ => 4096, }) } /// How far apart two stack colors start: a page and a cache line. fn color_step() -> usize { page() + 64 } /// What one page table maps with 4 KiB pages (x86_64, and aarch64's /// default). A stack's top is aligned on it, so the regions at its top /// belong to it alone: when [`Stack::release`] gives them back, the /// kernel frees their page tables too (Linux's `CONFIG_PT_RECLAIM` /// reclaims a page table only when the whole range it maps is released). /// Without that, an idle actor kept a 4 KiB page table for its one /// touched stack page (ADR 0028). With larger pages the alignment is only /// less useful. pub(crate) const REGION: usize = 2 << 20; impl Stack { pub(crate) fn new(size: usize) -> std::io::Result { // The guard page, the stack, and room to align its top: virtual // memory only, never touched. let page = page(); let len = page + size.div_ceil(page) * page + COLORS * color_step() + REGION; // SAFETY: a fresh private anonymous mapping; nothing aliases it. unsafe { let base = libc::mmap( std::ptr::null_mut(), len, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE, -1, 0, ); if base == libc::MAP_FAILED { return Err(std::io::Error::last_os_error()); } // The lowest page catches overflows (stacks grow down). if libc::mprotect(base, page, libc::PROT_NONE) != 0 { let e = std::io::Error::last_os_error(); libc::munmap(base, len); return Err(e); } // At least `page + size` above `base` once colored, since the // mapping is `REGION` and every color longer than that. let region_top = (base as usize + len) & !(REGION - 1); let color = NEXT_COLOR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % COLORS; Ok(Stack { base: base.cast(), len, size, region_top, top: region_top - color * color_step(), }) } } /// The highest address (exclusive): stacks grow down from here. pub(crate) fn top(&self) -> usize { self.top } /// The usable size requested from [`Stack::new`]. pub(crate) fn size(&self) -> usize { self.size } /// Exact map extent for checking ordinary, non-process teardown. Linux's /// `MAP_FIXED_NOREPLACE` lets the test verify that this extent is free /// without reading a dropped stack or reserving a replacement on failure. #[cfg(test)] pub(crate) fn map_extent(&self) -> (*mut u8, usize) { (self.base, self.len) } /// Give the stack's memory back to the kernel: its pages read as zeros /// afterwards, and the page tables of the whole regions at its top are /// freed. Nothing on it may be live: a finished fiber's stack, or a /// suspended one already saved ([`Coroutine::hibernate`]). pub(crate) fn release(&self) { let low = self.base as usize + page(); // SAFETY: `low..region_top` is inside the mapping, above the guard // page; the caller guarantees nothing on it is live. let r = unsafe { libc::madvise( low as *mut libc::c_void, self.region_top - low, libc::MADV_DONTNEED, ) }; debug_assert_eq!(r, 0, "louise: madvise: {}", std::io::Error::last_os_error()); } } impl Drop for Stack { fn drop(&mut self) { // SAFETY: the mapping made in `new`, unmapped once. unsafe { libc::munmap(self.base.cast(), self.len) }; } } /// The part in use of a suspended fiber's stack, and its stack pointer: a /// copy that can be written back in place to resume the fiber there again /// (multi-shot continuations, ADR 0017). Restoring at the same address /// keeps every pointer into the stack valid; the references the frames /// hold are the caller's business. pub(crate) struct Snapshot { sp: usize, words: Vec, /// ThreadSanitizer's call depth on the fiber then (`tsan::set_depth`). tsan_depth: usize, } /// Copy `n` words. Volatile, one word at a time: never a `memcpy`, which /// AddressSanitizer would check against the redzones of the frames being /// copied. /// /// # Safety /// Both ranges must be valid and not overlap. unsafe fn copy_words(src: *const usize, dst: *mut usize, n: usize) { for i in 0..n { // SAFETY: caller guarantees both ranges. unsafe { dst.add(i).write_volatile(src.add(i).read_volatile()) }; } } /// What `resume` returns: the fiber suspended with a value, or finished. pub(crate) enum CoroutineResult { Yield(Y), Return(R), } pub(crate) use imp::{Coroutine, Yielder}; /// ThreadSanitizer's view of fibers. With `--cfg louise_rt_tsan` (a runtime /// built with `-Zsanitizer=thread`, see `scripts/tsan.sh`), each fiber is /// registered with TSan and every switch is announced just before it /// happens, as TSan requires. Otherwise TSan believes each thread stays on /// one stack: its shadow call stack goes out of balance and it crashes at /// exit. Elsewhere these are no-ops. /// /// Switches synchronise (flag 0): the code before a switch happens before /// the code after it, which is true of a switch on one thread. Moving a /// fiber to another thread goes through a run queue, which TSan sees. mod tsan { #[derive(Clone, Copy)] pub(super) struct Fiber( #[cfg_attr(not(louise_rt_tsan), allow(dead_code))] *mut std::ffi::c_void, ); impl Fiber { pub(super) const NONE: Fiber = Fiber(std::ptr::null_mut()); } #[cfg(louise_rt_tsan)] unsafe extern "C" { fn __tsan_get_current_fiber() -> *mut std::ffi::c_void; fn __tsan_create_fiber(flags: u32) -> *mut std::ffi::c_void; fn __tsan_destroy_fiber(fiber: *mut std::ffi::c_void); fn __tsan_switch_to_fiber(fiber: *mut std::ffi::c_void, flags: u32); fn __tsan_testonly_shadow_stack_current_size() -> usize; fn __tsan_func_entry(pc: *const std::ffi::c_void); fn __tsan_func_exit(); } /// `__tsan_switch_to_fiber` without synchronising the two fibers. #[cfg(louise_rt_tsan)] const NO_SYNC: u32 = 1; /// TSan's call depth on the running fiber: the number of instrumented /// frames it believes are on the stack. Only TSan builds record it: /// even storing a constant on every suspension made the `ctl` /// generator of `tests/bench/effects` 25% slower. #[cfg(louise_rt_tsan)] pub(super) fn depth() -> usize { // SAFETY: a query of the TSan runtime. unsafe { __tsan_testonly_shadow_stack_current_size() } } /// Set TSan's call depth on suspended `fiber` to `depth`, after its /// stack was overwritten with a snapshot (multi-shot resumptions): pop /// frames, or push placeholders (their return addresses are unknown, /// so reports show them as 0). /// /// # Safety /// `fiber` came from [`create`], and is not running. pub(super) unsafe fn set_depth(fiber: Fiber, depth: usize) { #[cfg(louise_rt_tsan)] // SAFETY: `fiber` is suspended; nothing instrumented runs while // it is TSan's current fiber here (only TSan's own entry points), // and the caller's fiber is current again on return. unsafe { let me = __tsan_get_current_fiber(); __tsan_switch_to_fiber(fiber.0, NO_SYNC); let mut d = __tsan_testonly_shadow_stack_current_size(); while d > depth { __tsan_func_exit(); d -= 1; } while d < depth { __tsan_func_entry(std::ptr::null()); d += 1; } __tsan_switch_to_fiber(me, NO_SYNC); } #[cfg(not(louise_rt_tsan))] let _ = (fiber, depth); } pub(super) fn current() -> Fiber { #[cfg(louise_rt_tsan)] // SAFETY: a query of the TSan runtime. return Fiber(unsafe { __tsan_get_current_fiber() }); #[cfg(not(louise_rt_tsan))] Fiber::NONE } pub(super) fn create() -> Fiber { #[cfg(louise_rt_tsan)] // SAFETY: registers a new fiber; destroyed with its coroutine. return Fiber(unsafe { __tsan_create_fiber(0) }); #[cfg(not(louise_rt_tsan))] Fiber::NONE } /// # Safety /// `fiber` came from [`create`], and is not running. pub(super) unsafe fn destroy(fiber: Fiber) { #[cfg(louise_rt_tsan)] // SAFETY: forwarded caller guarantee. unsafe { __tsan_destroy_fiber(fiber.0) }; #[cfg(not(louise_rt_tsan))] let _ = fiber; } /// Announce the switch about to happen to `fiber`. /// /// Inlined: an instrumented function of its own would enter on one /// fiber and leave on the other, and so unbalance both their shadow /// call stacks (TSan crashes when one underflows). #[inline(always)] pub(super) fn switch_to(fiber: Fiber) { #[cfg(louise_rt_tsan)] // SAFETY: `fiber` is live: the caller switches to it next. unsafe { __tsan_switch_to_fiber(fiber.0, 0) }; #[cfg(not(louise_rt_tsan))] let _ = fiber; } } #[cfg(not(all( target_os = "linux", any(target_arch = "x86_64", target_arch = "aarch64") )))] compile_error!("louise_rt runs on Linux, on x86_64 or aarch64 (ADR 0011)"); /// The context switch: what is common to both architectures. mod imp { use std::marker::PhantomData; use self::arch::{initial_frame, tl_fiber_switch}; use super::{CoroutineResult, Snapshot, Stack, tsan}; /// Where a fiber and the code resuming it exchange values. Boxed, so /// its address is stable while the fiber is suspended. struct Channel { /// The resumer's saved stack pointer (while the fiber runs). caller_sp: usize, /// The fiber's saved stack pointer (while it is suspended). fiber_sp: usize, /// ThreadSanitizer's handles for the resumer and the fiber. caller_tsan: tsan::Fiber, fiber_tsan: tsan::Fiber, /// TSan's call depth on the fiber when it last suspended. tsan_depth: usize, input: Option, output: Option, finished: bool, } /// Handed to the fiber's body; `suspend` returns to the resumer. pub(crate) struct Yielder { channel: *mut Channel, } impl Yielder { /// Suspend the fiber with `value`; returns the next resume's input. pub(crate) fn suspend(&self, value: Y) -> I { // SAFETY: the channel outlives the fiber; only the running // fiber calls this, on its own stack. unsafe { let c = self.channel; (*c).output = Some(value); #[cfg(louise_rt_tsan)] { (*c).tsan_depth = tsan::depth(); } tsan::switch_to((*c).caller_tsan); tl_fiber_switch(&raw mut (*c).fiber_sp, (*c).caller_sp); (*c).input.take().expect("louise: resumed without input") } } } pub(crate) struct Coroutine { slots: Box>, stack: Option, _body: PhantomData R>, } /// What the fiber and its resumer share, at a stable address while the /// fiber lives: one allocation, as idle actors are many (ADR 0028). struct Slots { channel: Channel, result: Option, } /// What the new fiber's first frame needs: its body and where to put /// the result. struct Start { body: F, channel: *mut Channel, result: *mut Option, } impl Coroutine { pub(crate) fn with_stack(stack: Stack, body: F) -> Self where F: FnOnce(&Yielder, I) -> R, { let mut slots = Box::new(Slots { channel: Channel { caller_sp: 0, fiber_sp: 0, caller_tsan: tsan::Fiber::NONE, fiber_tsan: tsan::create(), tsan_depth: 0, input: None, output: None, finished: false, }, result: None, }); let start = Box::into_raw(Box::new(Start { body, channel: &raw mut slots.channel, result: &raw mut slots.result, })); slots.channel.fiber_sp = initial_frame( &stack, start.cast(), entry:: as *const () as usize, ); Coroutine { slots, stack: Some(stack), _body: PhantomData, } } /// Run the fiber until it suspends or returns. pub(crate) fn resume(&mut self, input: I) -> CoroutineResult { let c = &raw mut self.slots.channel; // SAFETY: the fiber is suspended (or not started) at // `fiber_sp`; it switches back to `caller_sp`. unsafe { assert!(!(*c).finished, "louise: resumed a finished fiber"); (*c).input = Some(input); (*c).caller_tsan = tsan::current(); tsan::switch_to((*c).fiber_tsan); tl_fiber_switch(&raw mut (*c).caller_sp, (*c).fiber_sp); if (*c).finished { CoroutineResult::Return(self.slots.result.take().expect("louise: fiber result")) } else { CoroutineResult::Yield((*c).output.take().expect("louise: fiber value")) } } } /// The stack of a finished fiber, for reuse. Finishing is necessary /// but not sufficient before mapping reuse: the caller must also /// rule out every outstanding snapshot that could restore this /// coroutine's old stack addresses (multi-shot handlers do so only /// at their final `finish`). pub(crate) fn into_stack(mut self) -> Stack { assert!( self.slots.channel.finished, "louise: the fiber is still running" ); self.stack.take().expect("stack") } /// A copy of this suspended fiber's stack. pub(crate) fn snapshot(&self) -> Snapshot { assert!( !self.slots.channel.finished, "louise: snapshot of a finished fiber" ); let sp = self.slots.channel.fiber_sp; let top = self.stack.as_ref().expect("stack").top() & !15; let n = (top - sp) / 8; let mut words = Vec::with_capacity(n); // SAFETY: `sp..top` is the part in use of this fiber's stack, // which is suspended; `words` has room for `n` words. unsafe { super::copy_words(sp as *const usize, words.as_mut_ptr(), n); words.set_len(n); } Snapshot { sp, words, tsan_depth: self.slots.channel.tsan_depth, } } /// Save this suspended fiber's stack, then give its memory back /// ([`Stack::release`]): [`Coroutine::restore`] with the snapshot /// before resuming it. An idle actor's stack holds 688 bytes /// (`tests/bench/idle.lse`), against a 4 KiB page and a 4 KiB page /// table resident. pub(crate) fn hibernate(&mut self) -> Snapshot { let snap = self.snapshot(); self.stack.as_ref().expect("stack").release(); snap } /// Make this fiber the suspended one `snap` was taken of. What its /// stack held is overwritten: the fiber must be finished, or its /// suspension saved or released. pub(crate) fn restore(&mut self, snap: &Snapshot) { // SAFETY: the snapshot was taken of this fiber's stack, so it // fits at the same addresses; the fiber is not running. unsafe { super::copy_words(snap.words.as_ptr(), snap.sp as *mut usize, snap.words.len()); } let c = &mut self.slots.channel; c.fiber_sp = snap.sp; // TSan's shadow call stack for the fiber must match the frames // now on it again, or their returns would underflow it. // SAFETY: the fiber is not running. unsafe { tsan::set_depth(c.fiber_tsan, snap.tsan_depth) }; c.tsan_depth = snap.tsan_depth; c.finished = false; c.input = None; c.output = None; self.slots.result = None; } } impl Drop for Coroutine { fn drop(&mut self) { // SAFETY: the fiber is not running (it is being dropped). unsafe { tsan::destroy(self.slots.channel.fiber_tsan) }; if !self.slots.channel.finished && let Some(stack) = self.stack.take() { // A suspended fiber's frames hold references they never // drop: leak its stack rather than reuse live memory. std::mem::forget(stack); } } } /// The fiber's first Rust frame: run the body, publish its result, /// switch back for good. extern "C" fn entry(start: *mut u8) -> ! where F: FnOnce(&Yielder, I) -> R, { // SAFETY: `start` is the box made by `with_stack`, used once. unsafe { // Moved out (and the box freed) in this statement: this frame // never returns, so nothing owned may outlive the final switch. let Start { body, channel, result, } = *Box::from_raw(start.cast::>()); let yielder = Yielder { channel }; let input = (*channel) .input .take() .expect("louise: started without input"); *result = Some(body(&yielder, input)); (*channel).finished = true; tsan::switch_to((*channel).caller_tsan); let mut dead_sp = 0; tl_fiber_switch(&raw mut dead_sp, (*channel).caller_sp); unreachable!("louise: a finished fiber was resumed"); } } /// The architecture's half: the switch, and the first frame it pops. #[cfg(target_arch = "x86_64")] mod arch { use super::Stack; /// Lay out the frame `tl_fiber_switch` pops on the first resume: /// the control words, six callee-saved registers (rbx = `start`, /// r12 = `entry`), then the return address `tl_fiber_trampoline`, /// which calls `entry(start)` with the stack aligned as after a /// call. pub(super) fn initial_frame(stack: &Stack, start: *mut u8, entry: usize) -> usize { let top = stack.top() & !15; let words: [usize; 10] = [ 0x037F_0000_1F80, // MXCSR (low half) and the x87 control word 0, // r15 0, // r14 0, // r13 entry, // r12 start as usize, // rbx 0, // rbp tl_fiber_trampoline as *const () as usize, 0, // the trampoline's "return address": ends backtraces 0, // padding (keeps `top` 16-aligned) ]; let sp = top - words.len() * 8; // SAFETY: the words fit in the stack's top 80 bytes. unsafe { std::ptr::copy_nonoverlapping(words.as_ptr(), sp as *mut usize, words.len()); } sp } unsafe extern "C" { /// Save the current context, storing its stack pointer in /// `save`, and continue the one suspended at `to`. pub(super) fn tl_fiber_switch(save: *mut usize, to: usize); fn tl_fiber_trampoline(); } // System V x86_64: rbx, rbp, r12–r15, MXCSR's control bits and the // x87 control word are callee-saved; everything else may be // clobbered by a call, which is what the switch looks like to its // callers. std::arch::global_asm!( ".text", ".globl tl_fiber_switch", ".type tl_fiber_switch,@function", ".p2align 4", "tl_fiber_switch:", " .cfi_startproc", " push rbp", " push rbx", " push r12", " push r13", " push r14", " push r15", " sub rsp, 8", " stmxcsr [rsp]", " fnstcw [rsp + 4]", " mov [rdi], rsp", " mov rsp, rsi", " ldmxcsr [rsp]", " fldcw [rsp + 4]", " add rsp, 8", " pop r15", " pop r14", " pop r13", " pop r12", " pop rbx", " pop rbp", " ret", " .cfi_endproc", ".size tl_fiber_switch, .-tl_fiber_switch", "", ".globl tl_fiber_trampoline", ".type tl_fiber_trampoline,@function", ".p2align 4", "tl_fiber_trampoline:", " .cfi_startproc", " .cfi_undefined rip", " mov rdi, rbx", " call r12", " ud2", " .cfi_endproc", ".size tl_fiber_trampoline, .-tl_fiber_trampoline", ); } /// Tested under qemu (`scripts/aarch64.sh`), not yet on hardware /// (ADR 0011, 2026-10-12 note). Pointer authentication and branch /// target identification are not handled. #[cfg(target_arch = "aarch64")] mod arch { use super::Stack; /// The frame `tl_fiber_switch` saves (22 words, 176 bytes; a /// multiple of 16, so `sp` stays aligned). Indices in words. const FRAME: usize = 22; const X19: usize = 0; // x19–x28 at 0..10, then fp (x29) and lr (x30) const X20: usize = 1; const LR: usize = 11; // d8–d15 at 12..20, FPCR at 20, padding at 21 /// Lay out the frame `tl_fiber_switch` pops on the first resume: /// x19 = `start`, x20 = `entry`, fp = 0 (ends frame-pointer /// backtraces), lr = `tl_fiber_trampoline`, which calls /// `entry(start)`; d8–d15 zero, FPCR 0 (Linux's default: round to /// nearest, no traps). pub(super) fn initial_frame(stack: &Stack, start: *mut u8, entry: usize) -> usize { let top = stack.top() & !15; let mut words = [0usize; FRAME]; words[X19] = start as usize; words[X20] = entry; words[LR] = tl_fiber_trampoline as *const () as usize; let sp = top - FRAME * 8; // SAFETY: the words fit in the stack's top 176 bytes. unsafe { std::ptr::copy_nonoverlapping(words.as_ptr(), sp as *mut usize, FRAME); } sp } unsafe extern "C" { /// Save the current context, storing its stack pointer in /// `save`, and continue the one suspended at `to`. pub(super) fn tl_fiber_switch(save: *mut usize, to: usize); fn tl_fiber_trampoline(); } // AAPCS64: x19–x28, x29 (fp), x30 (lr), the low halves of v8–v15 // (d8–d15) and FPCR are callee-saved; everything else may be // clobbered by a call, which is what the switch looks like to its // callers. FPSR holds status flags only, and is not preserved. // `ret` returns to the restored lr: into the other context's call // of `tl_fiber_switch`, or, the first time, to the trampoline. std::arch::global_asm!( ".text", ".globl tl_fiber_switch", ".type tl_fiber_switch,%function", ".p2align 4", "tl_fiber_switch:", " .cfi_startproc", " sub sp, sp, #176", " stp x19, x20, [sp, #0]", " stp x21, x22, [sp, #16]", " stp x23, x24, [sp, #32]", " stp x25, x26, [sp, #48]", " stp x27, x28, [sp, #64]", " stp x29, x30, [sp, #80]", " stp d8, d9, [sp, #96]", " stp d10, d11, [sp, #112]", " stp d12, d13, [sp, #128]", " stp d14, d15, [sp, #144]", " mrs x9, fpcr", " str x9, [sp, #160]", " mov x9, sp", " str x9, [x0]", " mov sp, x1", " ldr x9, [sp, #160]", " msr fpcr, x9", " ldp d14, d15, [sp, #144]", " ldp d12, d13, [sp, #128]", " ldp d10, d11, [sp, #112]", " ldp d8, d9, [sp, #96]", " ldp x29, x30, [sp, #80]", " ldp x27, x28, [sp, #64]", " ldp x25, x26, [sp, #48]", " ldp x23, x24, [sp, #32]", " ldp x21, x22, [sp, #16]", " ldp x19, x20, [sp, #0]", " add sp, sp, #176", " ret", " .cfi_endproc", ".size tl_fiber_switch, .-tl_fiber_switch", "", ".globl tl_fiber_trampoline", ".type tl_fiber_trampoline,%function", ".p2align 4", "tl_fiber_trampoline:", " .cfi_startproc", " .cfi_undefined x30", " mov x0, x19", " blr x20", " brk #0", " .cfi_endproc", ".size tl_fiber_trampoline, .-tl_fiber_trampoline", ); } } #[cfg(test)] mod tests { use super::*; #[test] fn values_flow_both_ways() { let mut co = Coroutine::with_stack( Stack::new(64 << 10).unwrap(), |y: &Yielder, first| { let mut total = first; for i in 0..3 { total += y.suspend(i); } total * 10 }, ); assert!(matches!(co.resume(1), CoroutineResult::Yield(0))); assert!(matches!(co.resume(2), CoroutineResult::Yield(1))); assert!(matches!(co.resume(3), CoroutineResult::Yield(2))); assert!(matches!(co.resume(4), CoroutineResult::Return(100))); // Reinitialise coroutine B on coroutine A's exact mapping, not // merely extract an unused stack. let stack = co.into_stack(); let mut reused = Coroutine::with_stack(stack, |y: &Yielder, first| { first + y.suspend(first + 1) }); assert!(matches!(reused.resume(40), CoroutineResult::Yield(41))); assert!(matches!(reused.resume(1), CoroutineResult::Return(41))); } #[test] fn nested_fibers_and_float_state() { let mut outer = Coroutine::with_stack( Stack::new(256 << 10).unwrap(), |y: &Yielder<(), f64>, ()| { let mut inner = Coroutine::with_stack( Stack::new(64 << 10).unwrap(), |y2: &Yielder<(), f64>, ()| { y2.suspend(1.5); 2.25 }, ); let CoroutineResult::Yield(a) = inner.resume(()) else { panic!() }; y.suspend(a); let CoroutineResult::Return(b) = inner.resume(()) else { panic!() }; a * b }, ); assert!(matches!(outer.resume(()), CoroutineResult::Yield(x) if x == 1.5)); assert!(matches!(outer.resume(()), CoroutineResult::Return(x) if x == 3.375)); } #[test] fn a_suspended_fiber_resumes_on_another_thread() { struct SendCo(Coroutine); // SAFETY: the body holds no thread-local state across `suspend`. unsafe impl Send for SendCo {} let mut co = SendCo(Coroutine::with_stack( Stack::new(64 << 10).unwrap(), |y: &Yielder, a| { let b = y.suspend(a + 1); a + b }, )); assert!(matches!(co.0.resume(10), CoroutineResult::Yield(11))); let handle = std::thread::spawn(move || { let mut co = co; matches!(co.0.resume(5), CoroutineResult::Return(15)) }); assert!(handle.join().unwrap()); } #[test] fn a_snapshot_resumes_again_where_it_was_taken() { let mut co = Coroutine::with_stack( Stack::new(64 << 10).unwrap(), |y: &Yielder, base| { let local = [base; 4]; // on the fiber's stack let x = y.suspend(local[3]); std::hint::black_box(local)[0] * 100 + x }, ); assert!(matches!(co.resume(7), CoroutineResult::Yield(7))); let snap = co.snapshot(); assert!(matches!(co.resume(1), CoroutineResult::Return(701))); co.restore(&snap); assert!(matches!(co.resume(2), CoroutineResult::Return(702))); co.restore(&snap); assert!(matches!(co.resume(3), CoroutineResult::Return(703))); } #[test] fn stack_tops_are_aligned_and_leave_the_size_asked_for() { for size in [64 << 10, 256 << 10, 64 << 20] { let s = Stack::new(size).unwrap(); assert_eq!(s.region_top % REGION, 0); assert!(s.top() <= s.region_top); assert!(s.top() - (s.base as usize + page()) >= size); assert!(s.region_top <= s.base as usize + s.len); } let handler = Stack::new(16 << 20).unwrap(); let (base, len) = handler.map_extent(); assert_eq!(base, handler.base); assert_eq!(len, page() + (16 << 20) + COLORS * color_step() + REGION); if page() == 4096 { assert_eq!(len, 19_011_584, "18.131 MiB including all overhead"); } } #[test] fn a_hibernated_fiber_resumes_where_it_was() { let mut co = Coroutine::with_stack( Stack::new(64 << 20).unwrap(), |y: &Yielder, base| { let local = [base, base + 1, base + 2, base + 3]; // on the stack let x = y.suspend(local[1]); let x = x + y.suspend(std::hint::black_box(&local)[2]); std::hint::black_box(local).iter().sum::() + x }, ); assert!(matches!(co.resume(10), CoroutineResult::Yield(11))); let snap = co.hibernate(); // The stack reads as zeros now: only the snapshot holds the frames. assert!( snap.words.contains(&11), "the suspended frame holds `local`" ); // SAFETY: `sp` is inside the mapping, above its guard page. assert_eq!(unsafe { (snap.sp as *const usize).read_volatile() }, 0); co.restore(&snap); assert!(matches!(co.resume(1), CoroutineResult::Yield(12))); let snap = co.hibernate(); co.restore(&snap); assert!(matches!(co.resume(2), CoroutineResult::Return(49))); } #[test] fn deep_recursion_runs_on_the_fiber_stack() { fn depth(n: u32) -> u32 { let pad = [n; 32]; if n == 0 { 0 } else { 1 + depth(std::hint::black_box(pad)[0] - 1) } } let mut co = Coroutine::with_stack(Stack::new(64 << 20).unwrap(), |_: &Yielder<(), ()>, ()| { depth(10_000) }); assert!(matches!(co.resume(()), CoroutineResult::Return(10_000))); } }