
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#1201 · main · 9 min 57 s
1Étoiles
0Forks
0Issues
| 1 | //! Fibers: stacks and the context switch (ADR 0011). |
| 2 | //! |
| 3 | //! Actors (`sched`) and `ctl` handler bodies (`handlers`) run on fibers: |
| 4 | //! asymmetric coroutines that `resume` until they `suspend` or return. |
| 5 | //! The runtime supports Linux on x86_64 and aarch64, and nothing else |
| 6 | //! (ADR 0011, 2026-10-12 note). |
| 7 | //! |
| 8 | //! - **Stacks** are the runtime's own: an anonymous mapping with a guard |
| 9 | //! page at its low end, committed lazily by the kernel. Their tops are |
| 10 | //! aligned on [`REGION`], so that a stack's memory, page tables |
| 11 | //! included, can be given back while its fiber is suspended |
| 12 | //! ([`Coroutine::hibernate`], ADR 0028). |
| 13 | //! - **The switch** is the runtime's own: it saves the callee-saved |
| 14 | //! registers (and the floating-point control words) on the current |
| 15 | //! stack, stores the stack pointer, and loads the other one. A suspended |
| 16 | //! fiber is just its saved stack pointer, so it may resume on any |
| 17 | //! thread, and its stack can be copied and written back |
| 18 | //! ([`Coroutine::snapshot`]). `scripts/aarch64.sh` runs the tests on |
| 19 | //! aarch64 under qemu. |
| 20 | //! |
| 21 | //! Rules: |
| 22 | //! - a fiber is never dropped while suspended: its frames would never run |
| 23 | //! their drops; |
| 24 | //! - code on a fiber must not hold thread-local state across a suspension, |
| 25 | //! since it may resume on another thread (see `sched::Fiber`). |
| 26 | |
| 27 | /// A fiber stack: at least `size` usable bytes above one guard page. |
| 28 | pub(crate) struct Stack { |
| 29 | /// The mapping, guard page first. |
| 30 | base: *mut u8, |
| 31 | len: usize, |
| 32 | /// The usable size requested from [`Stack::new`], before guard, |
| 33 | /// colouring and alignment overhead. Keeps the size-specific pools |
| 34 | /// honest without exposing the mapping's geometry. |
| 35 | size: usize, |
| 36 | /// Aligned on [`REGION`]: what [`Stack::release`] gives back ends here. |
| 37 | /// The mapping's last bytes, above it, are never used. |
| 38 | region_top: usize, |
| 39 | /// Where the stack starts (it grows down): `region_top` less this |
| 40 | /// stack's color. |
| 41 | top: usize, |
| 42 | } |
| 43 | |
| 44 | /// Stacks start a varying distance below their aligned top, in steps of a |
| 45 | /// page and a cache line. Aligned alike, the top frames of every stack fell |
| 46 | /// in the same cache sets: a 1,000-actor ring (`tests/bench/messages.lse`) |
| 47 | /// ran 5% slower, most of it in `tl_fiber_switch`. The pages above a |
| 48 | /// stack's start are never touched, so a color costs no memory. |
| 49 | const COLORS: usize = 32; |
| 50 | static NEXT_COLOR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); |
| 51 | |
| 52 | // SAFETY: a stack is plain memory, owned by one fiber at a time. |
| 53 | unsafe impl Send for Stack {} |
| 54 | |
| 55 | /// The kernel's page size: 4 KiB on x86_64, and 4, 16 or 64 KiB on |
| 56 | /// aarch64, depending on the kernel. The guard page and `madvise` must |
| 57 | /// use it. |
| 58 | fn page() -> usize { |
| 59 | static PAGE: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 60 | // SAFETY: `sysconf` has no preconditions. |
| 61 | *PAGE.get_or_init(|| match unsafe { libc::sysconf(libc::_SC_PAGESIZE) } { |
| 62 | n if n > 0 => n as usize, |
| 63 | _ => 4096, |
| 64 | }) |
| 65 | } |
| 66 | |
| 67 | /// How far apart two stack colors start: a page and a cache line. |
| 68 | fn color_step() -> usize { |
| 69 | page() + 64 |
| 70 | } |
| 71 | |
| 72 | /// What one page table maps with 4 KiB pages (x86_64, and aarch64's |
| 73 | /// default). A stack's top is aligned on it, so the regions at its top |
| 74 | /// belong to it alone: when [`Stack::release`] gives them back, the |
| 75 | /// kernel frees their page tables too (Linux's `CONFIG_PT_RECLAIM` |
| 76 | /// reclaims a page table only when the whole range it maps is released). |
| 77 | /// Without that, an idle actor kept a 4 KiB page table for its one |
| 78 | /// touched stack page (ADR 0028). With larger pages the alignment is only |
| 79 | /// less useful. |
| 80 | pub(crate) const REGION: usize = 2 << 20; |
| 81 | |
| 82 | impl Stack { |
| 83 | pub(crate) fn new(size: usize) -> std::io::Result<Stack> { |
| 84 | // The guard page, the stack, and room to align its top: virtual |
| 85 | // memory only, never touched. |
| 86 | let page = page(); |
| 87 | let len = page + size.div_ceil(page) * page + COLORS * color_step() + REGION; |
| 88 | // SAFETY: a fresh private anonymous mapping; nothing aliases it. |
| 89 | unsafe { |
| 90 | let base = libc::mmap( |
| 91 | std::ptr::null_mut(), |
| 92 | len, |
| 93 | libc::PROT_READ | libc::PROT_WRITE, |
| 94 | libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE, |
| 95 | -1, |
| 96 | 0, |
| 97 | ); |
| 98 | if base == libc::MAP_FAILED { |
| 99 | return Err(std::io::Error::last_os_error()); |
| 100 | } |
| 101 | // The lowest page catches overflows (stacks grow down). |
| 102 | if libc::mprotect(base, page, libc::PROT_NONE) != 0 { |
| 103 | let e = std::io::Error::last_os_error(); |
| 104 | libc::munmap(base, len); |
| 105 | return Err(e); |
| 106 | } |
| 107 | // At least `page + size` above `base` once colored, since the |
| 108 | // mapping is `REGION` and every color longer than that. |
| 109 | let region_top = (base as usize + len) & !(REGION - 1); |
| 110 | let color = NEXT_COLOR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % COLORS; |
| 111 | Ok(Stack { |
| 112 | base: base.cast(), |
| 113 | len, |
| 114 | size, |
| 115 | region_top, |
| 116 | top: region_top - color * color_step(), |
| 117 | }) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | /// The highest address (exclusive): stacks grow down from here. |
| 122 | pub(crate) fn top(&self) -> usize { |
| 123 | self.top |
| 124 | } |
| 125 | |
| 126 | /// The usable size requested from [`Stack::new`]. |
| 127 | pub(crate) fn size(&self) -> usize { |
| 128 | self.size |
| 129 | } |
| 130 | |
| 131 | /// Exact map extent for checking ordinary, non-process teardown. Linux's |
| 132 | /// `MAP_FIXED_NOREPLACE` lets the test verify that this extent is free |
| 133 | /// without reading a dropped stack or reserving a replacement on failure. |
| 134 | #[cfg(test)] |
| 135 | pub(crate) fn map_extent(&self) -> (*mut u8, usize) { |
| 136 | (self.base, self.len) |
| 137 | } |
| 138 | |
| 139 | /// Give the stack's memory back to the kernel: its pages read as zeros |
| 140 | /// afterwards, and the page tables of the whole regions at its top are |
| 141 | /// freed. Nothing on it may be live: a finished fiber's stack, or a |
| 142 | /// suspended one already saved ([`Coroutine::hibernate`]). |
| 143 | pub(crate) fn release(&self) { |
| 144 | let low = self.base as usize + page(); |
| 145 | // SAFETY: `low..region_top` is inside the mapping, above the guard |
| 146 | // page; the caller guarantees nothing on it is live. |
| 147 | let r = unsafe { |
| 148 | libc::madvise( |
| 149 | low as *mut libc::c_void, |
| 150 | self.region_top - low, |
| 151 | libc::MADV_DONTNEED, |
| 152 | ) |
| 153 | }; |
| 154 | debug_assert_eq!(r, 0, "louise: madvise: {}", std::io::Error::last_os_error()); |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | impl Drop for Stack { |
| 159 | fn drop(&mut self) { |
| 160 | // SAFETY: the mapping made in `new`, unmapped once. |
| 161 | unsafe { libc::munmap(self.base.cast(), self.len) }; |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | /// The part in use of a suspended fiber's stack, and its stack pointer: a |
| 166 | /// copy that can be written back in place to resume the fiber there again |
| 167 | /// (multi-shot continuations, ADR 0017). Restoring at the same address |
| 168 | /// keeps every pointer into the stack valid; the references the frames |
| 169 | /// hold are the caller's business. |
| 170 | pub(crate) struct Snapshot { |
| 171 | sp: usize, |
| 172 | words: Vec<usize>, |
| 173 | /// ThreadSanitizer's call depth on the fiber then (`tsan::set_depth`). |
| 174 | tsan_depth: usize, |
| 175 | } |
| 176 | |
| 177 | /// Copy `n` words. Volatile, one word at a time: never a `memcpy`, which |
| 178 | /// AddressSanitizer would check against the redzones of the frames being |
| 179 | /// copied. |
| 180 | /// |
| 181 | /// # Safety |
| 182 | /// Both ranges must be valid and not overlap. |
| 183 | unsafe fn copy_words(src: *const usize, dst: *mut usize, n: usize) { |
| 184 | for i in 0..n { |
| 185 | // SAFETY: caller guarantees both ranges. |
| 186 | unsafe { dst.add(i).write_volatile(src.add(i).read_volatile()) }; |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /// What `resume` returns: the fiber suspended with a value, or finished. |
| 191 | pub(crate) enum CoroutineResult<Y, R> { |
| 192 | Yield(Y), |
| 193 | Return(R), |
| 194 | } |
| 195 | |
| 196 | pub(crate) use imp::{Coroutine, Yielder}; |
| 197 | |
| 198 | /// ThreadSanitizer's view of fibers. With `--cfg louise_rt_tsan` (a runtime |
| 199 | /// built with `-Zsanitizer=thread`, see `scripts/tsan.sh`), each fiber is |
| 200 | /// registered with TSan and every switch is announced just before it |
| 201 | /// happens, as TSan requires. Otherwise TSan believes each thread stays on |
| 202 | /// one stack: its shadow call stack goes out of balance and it crashes at |
| 203 | /// exit. Elsewhere these are no-ops. |
| 204 | /// |
| 205 | /// Switches synchronise (flag 0): the code before a switch happens before |
| 206 | /// the code after it, which is true of a switch on one thread. Moving a |
| 207 | /// fiber to another thread goes through a run queue, which TSan sees. |
| 208 | mod tsan { |
| 209 | #[derive(Clone, Copy)] |
| 210 | pub(super) struct Fiber( |
| 211 | #[cfg_attr(not(louise_rt_tsan), allow(dead_code))] *mut std::ffi::c_void, |
| 212 | ); |
| 213 | |
| 214 | impl Fiber { |
| 215 | pub(super) const NONE: Fiber = Fiber(std::ptr::null_mut()); |
| 216 | } |
| 217 | |
| 218 | #[cfg(louise_rt_tsan)] |
| 219 | unsafe extern "C" { |
| 220 | fn __tsan_get_current_fiber() -> *mut std::ffi::c_void; |
| 221 | fn __tsan_create_fiber(flags: u32) -> *mut std::ffi::c_void; |
| 222 | fn __tsan_destroy_fiber(fiber: *mut std::ffi::c_void); |
| 223 | fn __tsan_switch_to_fiber(fiber: *mut std::ffi::c_void, flags: u32); |
| 224 | fn __tsan_testonly_shadow_stack_current_size() -> usize; |
| 225 | fn __tsan_func_entry(pc: *const std::ffi::c_void); |
| 226 | fn __tsan_func_exit(); |
| 227 | } |
| 228 | |
| 229 | /// `__tsan_switch_to_fiber` without synchronising the two fibers. |
| 230 | #[cfg(louise_rt_tsan)] |
| 231 | const NO_SYNC: u32 = 1; |
| 232 | |
| 233 | /// TSan's call depth on the running fiber: the number of instrumented |
| 234 | /// frames it believes are on the stack. Only TSan builds record it: |
| 235 | /// even storing a constant on every suspension made the `ctl` |
| 236 | /// generator of `tests/bench/effects` 25% slower. |
| 237 | #[cfg(louise_rt_tsan)] |
| 238 | pub(super) fn depth() -> usize { |
| 239 | // SAFETY: a query of the TSan runtime. |
| 240 | unsafe { __tsan_testonly_shadow_stack_current_size() } |
| 241 | } |
| 242 | |
| 243 | /// Set TSan's call depth on suspended `fiber` to `depth`, after its |
| 244 | /// stack was overwritten with a snapshot (multi-shot resumptions): pop |
| 245 | /// frames, or push placeholders (their return addresses are unknown, |
| 246 | /// so reports show them as 0). |
| 247 | /// |
| 248 | /// # Safety |
| 249 | /// `fiber` came from [`create`], and is not running. |
| 250 | pub(super) unsafe fn set_depth(fiber: Fiber, depth: usize) { |
| 251 | #[cfg(louise_rt_tsan)] |
| 252 | // SAFETY: `fiber` is suspended; nothing instrumented runs while |
| 253 | // it is TSan's current fiber here (only TSan's own entry points), |
| 254 | // and the caller's fiber is current again on return. |
| 255 | unsafe { |
| 256 | let me = __tsan_get_current_fiber(); |
| 257 | __tsan_switch_to_fiber(fiber.0, NO_SYNC); |
| 258 | let mut d = __tsan_testonly_shadow_stack_current_size(); |
| 259 | while d > depth { |
| 260 | __tsan_func_exit(); |
| 261 | d -= 1; |
| 262 | } |
| 263 | while d < depth { |
| 264 | __tsan_func_entry(std::ptr::null()); |
| 265 | d += 1; |
| 266 | } |
| 267 | __tsan_switch_to_fiber(me, NO_SYNC); |
| 268 | } |
| 269 | #[cfg(not(louise_rt_tsan))] |
| 270 | let _ = (fiber, depth); |
| 271 | } |
| 272 | |
| 273 | pub(super) fn current() -> Fiber { |
| 274 | #[cfg(louise_rt_tsan)] |
| 275 | // SAFETY: a query of the TSan runtime. |
| 276 | return Fiber(unsafe { __tsan_get_current_fiber() }); |
| 277 | #[cfg(not(louise_rt_tsan))] |
| 278 | Fiber::NONE |
| 279 | } |
| 280 | |
| 281 | pub(super) fn create() -> Fiber { |
| 282 | #[cfg(louise_rt_tsan)] |
| 283 | // SAFETY: registers a new fiber; destroyed with its coroutine. |
| 284 | return Fiber(unsafe { __tsan_create_fiber(0) }); |
| 285 | #[cfg(not(louise_rt_tsan))] |
| 286 | Fiber::NONE |
| 287 | } |
| 288 | |
| 289 | /// # Safety |
| 290 | /// `fiber` came from [`create`], and is not running. |
| 291 | pub(super) unsafe fn destroy(fiber: Fiber) { |
| 292 | #[cfg(louise_rt_tsan)] |
| 293 | // SAFETY: forwarded caller guarantee. |
| 294 | unsafe { |
| 295 | __tsan_destroy_fiber(fiber.0) |
| 296 | }; |
| 297 | #[cfg(not(louise_rt_tsan))] |
| 298 | let _ = fiber; |
| 299 | } |
| 300 | |
| 301 | /// Announce the switch about to happen to `fiber`. |
| 302 | /// |
| 303 | /// Inlined: an instrumented function of its own would enter on one |
| 304 | /// fiber and leave on the other, and so unbalance both their shadow |
| 305 | /// call stacks (TSan crashes when one underflows). |
| 306 | #[inline(always)] |
| 307 | pub(super) fn switch_to(fiber: Fiber) { |
| 308 | #[cfg(louise_rt_tsan)] |
| 309 | // SAFETY: `fiber` is live: the caller switches to it next. |
| 310 | unsafe { |
| 311 | __tsan_switch_to_fiber(fiber.0, 0) |
| 312 | }; |
| 313 | #[cfg(not(louise_rt_tsan))] |
| 314 | let _ = fiber; |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | #[cfg(not(all( |
| 319 | target_os = "linux", |
| 320 | any(target_arch = "x86_64", target_arch = "aarch64") |
| 321 | )))] |
| 322 | compile_error!("louise_rt runs on Linux, on x86_64 or aarch64 (ADR 0011)"); |
| 323 | |
| 324 | /// The context switch: what is common to both architectures. |
| 325 | mod imp { |
| 326 | use std::marker::PhantomData; |
| 327 | |
| 328 | use self::arch::{initial_frame, tl_fiber_switch}; |
| 329 | use super::{CoroutineResult, Snapshot, Stack, tsan}; |
| 330 | |
| 331 | /// Where a fiber and the code resuming it exchange values. Boxed, so |
| 332 | /// its address is stable while the fiber is suspended. |
| 333 | struct Channel<I, Y> { |
| 334 | /// The resumer's saved stack pointer (while the fiber runs). |
| 335 | caller_sp: usize, |
| 336 | /// The fiber's saved stack pointer (while it is suspended). |
| 337 | fiber_sp: usize, |
| 338 | /// ThreadSanitizer's handles for the resumer and the fiber. |
| 339 | caller_tsan: tsan::Fiber, |
| 340 | fiber_tsan: tsan::Fiber, |
| 341 | /// TSan's call depth on the fiber when it last suspended. |
| 342 | tsan_depth: usize, |
| 343 | input: Option<I>, |
| 344 | output: Option<Y>, |
| 345 | finished: bool, |
| 346 | } |
| 347 | |
| 348 | /// Handed to the fiber's body; `suspend` returns to the resumer. |
| 349 | pub(crate) struct Yielder<I, Y> { |
| 350 | channel: *mut Channel<I, Y>, |
| 351 | } |
| 352 | |
| 353 | impl<I, Y> Yielder<I, Y> { |
| 354 | /// Suspend the fiber with `value`; returns the next resume's input. |
| 355 | pub(crate) fn suspend(&self, value: Y) -> I { |
| 356 | // SAFETY: the channel outlives the fiber; only the running |
| 357 | // fiber calls this, on its own stack. |
| 358 | unsafe { |
| 359 | let c = self.channel; |
| 360 | (*c).output = Some(value); |
| 361 | #[cfg(louise_rt_tsan)] |
| 362 | { |
| 363 | (*c).tsan_depth = tsan::depth(); |
| 364 | } |
| 365 | tsan::switch_to((*c).caller_tsan); |
| 366 | tl_fiber_switch(&raw mut (*c).fiber_sp, (*c).caller_sp); |
| 367 | (*c).input.take().expect("louise: resumed without input") |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | pub(crate) struct Coroutine<I, Y, R> { |
| 373 | slots: Box<Slots<I, Y, R>>, |
| 374 | stack: Option<Stack>, |
| 375 | _body: PhantomData<fn(I) -> R>, |
| 376 | } |
| 377 | |
| 378 | /// What the fiber and its resumer share, at a stable address while the |
| 379 | /// fiber lives: one allocation, as idle actors are many (ADR 0028). |
| 380 | struct Slots<I, Y, R> { |
| 381 | channel: Channel<I, Y>, |
| 382 | result: Option<R>, |
| 383 | } |
| 384 | |
| 385 | /// What the new fiber's first frame needs: its body and where to put |
| 386 | /// the result. |
| 387 | struct Start<I, Y, R, F> { |
| 388 | body: F, |
| 389 | channel: *mut Channel<I, Y>, |
| 390 | result: *mut Option<R>, |
| 391 | } |
| 392 | |
| 393 | impl<I, Y, R> Coroutine<I, Y, R> { |
| 394 | pub(crate) fn with_stack<F>(stack: Stack, body: F) -> Self |
| 395 | where |
| 396 | F: FnOnce(&Yielder<I, Y>, I) -> R, |
| 397 | { |
| 398 | let mut slots = Box::new(Slots { |
| 399 | channel: Channel { |
| 400 | caller_sp: 0, |
| 401 | fiber_sp: 0, |
| 402 | caller_tsan: tsan::Fiber::NONE, |
| 403 | fiber_tsan: tsan::create(), |
| 404 | tsan_depth: 0, |
| 405 | input: None, |
| 406 | output: None, |
| 407 | finished: false, |
| 408 | }, |
| 409 | result: None, |
| 410 | }); |
| 411 | let start = Box::into_raw(Box::new(Start { |
| 412 | body, |
| 413 | channel: &raw mut slots.channel, |
| 414 | result: &raw mut slots.result, |
| 415 | })); |
| 416 | slots.channel.fiber_sp = initial_frame( |
| 417 | &stack, |
| 418 | start.cast(), |
| 419 | entry::<I, Y, R, F> as *const () as usize, |
| 420 | ); |
| 421 | Coroutine { |
| 422 | slots, |
| 423 | stack: Some(stack), |
| 424 | _body: PhantomData, |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | /// Run the fiber until it suspends or returns. |
| 429 | pub(crate) fn resume(&mut self, input: I) -> CoroutineResult<Y, R> { |
| 430 | let c = &raw mut self.slots.channel; |
| 431 | // SAFETY: the fiber is suspended (or not started) at |
| 432 | // `fiber_sp`; it switches back to `caller_sp`. |
| 433 | unsafe { |
| 434 | assert!(!(*c).finished, "louise: resumed a finished fiber"); |
| 435 | (*c).input = Some(input); |
| 436 | (*c).caller_tsan = tsan::current(); |
| 437 | tsan::switch_to((*c).fiber_tsan); |
| 438 | tl_fiber_switch(&raw mut (*c).caller_sp, (*c).fiber_sp); |
| 439 | if (*c).finished { |
| 440 | CoroutineResult::Return(self.slots.result.take().expect("louise: fiber result")) |
| 441 | } else { |
| 442 | CoroutineResult::Yield((*c).output.take().expect("louise: fiber value")) |
| 443 | } |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | /// The stack of a finished fiber, for reuse. Finishing is necessary |
| 448 | /// but not sufficient before mapping reuse: the caller must also |
| 449 | /// rule out every outstanding snapshot that could restore this |
| 450 | /// coroutine's old stack addresses (multi-shot handlers do so only |
| 451 | /// at their final `finish`). |
| 452 | pub(crate) fn into_stack(mut self) -> Stack { |
| 453 | assert!( |
| 454 | self.slots.channel.finished, |
| 455 | "louise: the fiber is still running" |
| 456 | ); |
| 457 | self.stack.take().expect("stack") |
| 458 | } |
| 459 | |
| 460 | /// A copy of this suspended fiber's stack. |
| 461 | pub(crate) fn snapshot(&self) -> Snapshot { |
| 462 | assert!( |
| 463 | !self.slots.channel.finished, |
| 464 | "louise: snapshot of a finished fiber" |
| 465 | ); |
| 466 | let sp = self.slots.channel.fiber_sp; |
| 467 | let top = self.stack.as_ref().expect("stack").top() & !15; |
| 468 | let n = (top - sp) / 8; |
| 469 | let mut words = Vec::with_capacity(n); |
| 470 | // SAFETY: `sp..top` is the part in use of this fiber's stack, |
| 471 | // which is suspended; `words` has room for `n` words. |
| 472 | unsafe { |
| 473 | super::copy_words(sp as *const usize, words.as_mut_ptr(), n); |
| 474 | words.set_len(n); |
| 475 | } |
| 476 | Snapshot { |
| 477 | sp, |
| 478 | words, |
| 479 | tsan_depth: self.slots.channel.tsan_depth, |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | /// Save this suspended fiber's stack, then give its memory back |
| 484 | /// ([`Stack::release`]): [`Coroutine::restore`] with the snapshot |
| 485 | /// before resuming it. An idle actor's stack holds 688 bytes |
| 486 | /// (`tests/bench/idle.lse`), against a 4 KiB page and a 4 KiB page |
| 487 | /// table resident. |
| 488 | pub(crate) fn hibernate(&mut self) -> Snapshot { |
| 489 | let snap = self.snapshot(); |
| 490 | self.stack.as_ref().expect("stack").release(); |
| 491 | snap |
| 492 | } |
| 493 | |
| 494 | /// Make this fiber the suspended one `snap` was taken of. What its |
| 495 | /// stack held is overwritten: the fiber must be finished, or its |
| 496 | /// suspension saved or released. |
| 497 | pub(crate) fn restore(&mut self, snap: &Snapshot) { |
| 498 | // SAFETY: the snapshot was taken of this fiber's stack, so it |
| 499 | // fits at the same addresses; the fiber is not running. |
| 500 | unsafe { |
| 501 | super::copy_words(snap.words.as_ptr(), snap.sp as *mut usize, snap.words.len()); |
| 502 | } |
| 503 | let c = &mut self.slots.channel; |
| 504 | c.fiber_sp = snap.sp; |
| 505 | // TSan's shadow call stack for the fiber must match the frames |
| 506 | // now on it again, or their returns would underflow it. |
| 507 | // SAFETY: the fiber is not running. |
| 508 | unsafe { tsan::set_depth(c.fiber_tsan, snap.tsan_depth) }; |
| 509 | c.tsan_depth = snap.tsan_depth; |
| 510 | c.finished = false; |
| 511 | c.input = None; |
| 512 | c.output = None; |
| 513 | self.slots.result = None; |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | impl<I, Y, R> Drop for Coroutine<I, Y, R> { |
| 518 | fn drop(&mut self) { |
| 519 | // SAFETY: the fiber is not running (it is being dropped). |
| 520 | unsafe { tsan::destroy(self.slots.channel.fiber_tsan) }; |
| 521 | if !self.slots.channel.finished |
| 522 | && let Some(stack) = self.stack.take() |
| 523 | { |
| 524 | // A suspended fiber's frames hold references they never |
| 525 | // drop: leak its stack rather than reuse live memory. |
| 526 | std::mem::forget(stack); |
| 527 | } |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | /// The fiber's first Rust frame: run the body, publish its result, |
| 532 | /// switch back for good. |
| 533 | extern "C" fn entry<I, Y, R, F>(start: *mut u8) -> ! |
| 534 | where |
| 535 | F: FnOnce(&Yielder<I, Y>, I) -> R, |
| 536 | { |
| 537 | // SAFETY: `start` is the box made by `with_stack`, used once. |
| 538 | unsafe { |
| 539 | // Moved out (and the box freed) in this statement: this frame |
| 540 | // never returns, so nothing owned may outlive the final switch. |
| 541 | let Start { |
| 542 | body, |
| 543 | channel, |
| 544 | result, |
| 545 | } = *Box::from_raw(start.cast::<Start<I, Y, R, F>>()); |
| 546 | let yielder = Yielder { channel }; |
| 547 | let input = (*channel) |
| 548 | .input |
| 549 | .take() |
| 550 | .expect("louise: started without input"); |
| 551 | *result = Some(body(&yielder, input)); |
| 552 | (*channel).finished = true; |
| 553 | tsan::switch_to((*channel).caller_tsan); |
| 554 | let mut dead_sp = 0; |
| 555 | tl_fiber_switch(&raw mut dead_sp, (*channel).caller_sp); |
| 556 | unreachable!("louise: a finished fiber was resumed"); |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | /// The architecture's half: the switch, and the first frame it pops. |
| 561 | #[cfg(target_arch = "x86_64")] |
| 562 | mod arch { |
| 563 | use super::Stack; |
| 564 | |
| 565 | /// Lay out the frame `tl_fiber_switch` pops on the first resume: |
| 566 | /// the control words, six callee-saved registers (rbx = `start`, |
| 567 | /// r12 = `entry`), then the return address `tl_fiber_trampoline`, |
| 568 | /// which calls `entry(start)` with the stack aligned as after a |
| 569 | /// call. |
| 570 | pub(super) fn initial_frame(stack: &Stack, start: *mut u8, entry: usize) -> usize { |
| 571 | let top = stack.top() & !15; |
| 572 | let words: [usize; 10] = [ |
| 573 | 0x037F_0000_1F80, // MXCSR (low half) and the x87 control word |
| 574 | 0, // r15 |
| 575 | 0, // r14 |
| 576 | 0, // r13 |
| 577 | entry, // r12 |
| 578 | start as usize, // rbx |
| 579 | 0, // rbp |
| 580 | tl_fiber_trampoline as *const () as usize, |
| 581 | 0, // the trampoline's "return address": ends backtraces |
| 582 | 0, // padding (keeps `top` 16-aligned) |
| 583 | ]; |
| 584 | let sp = top - words.len() * 8; |
| 585 | // SAFETY: the words fit in the stack's top 80 bytes. |
| 586 | unsafe { |
| 587 | std::ptr::copy_nonoverlapping(words.as_ptr(), sp as *mut usize, words.len()); |
| 588 | } |
| 589 | sp |
| 590 | } |
| 591 | |
| 592 | unsafe extern "C" { |
| 593 | /// Save the current context, storing its stack pointer in |
| 594 | /// `save`, and continue the one suspended at `to`. |
| 595 | pub(super) fn tl_fiber_switch(save: *mut usize, to: usize); |
| 596 | fn tl_fiber_trampoline(); |
| 597 | } |
| 598 | |
| 599 | // System V x86_64: rbx, rbp, r12–r15, MXCSR's control bits and the |
| 600 | // x87 control word are callee-saved; everything else may be |
| 601 | // clobbered by a call, which is what the switch looks like to its |
| 602 | // callers. |
| 603 | std::arch::global_asm!( |
| 604 | ".text", |
| 605 | ".globl tl_fiber_switch", |
| 606 | ".type tl_fiber_switch,@function", |
| 607 | ".p2align 4", |
| 608 | "tl_fiber_switch:", |
| 609 | " .cfi_startproc", |
| 610 | " push rbp", |
| 611 | " push rbx", |
| 612 | " push r12", |
| 613 | " push r13", |
| 614 | " push r14", |
| 615 | " push r15", |
| 616 | " sub rsp, 8", |
| 617 | " stmxcsr [rsp]", |
| 618 | " fnstcw [rsp + 4]", |
| 619 | " mov [rdi], rsp", |
| 620 | " mov rsp, rsi", |
| 621 | " ldmxcsr [rsp]", |
| 622 | " fldcw [rsp + 4]", |
| 623 | " add rsp, 8", |
| 624 | " pop r15", |
| 625 | " pop r14", |
| 626 | " pop r13", |
| 627 | " pop r12", |
| 628 | " pop rbx", |
| 629 | " pop rbp", |
| 630 | " ret", |
| 631 | " .cfi_endproc", |
| 632 | ".size tl_fiber_switch, .-tl_fiber_switch", |
| 633 | "", |
| 634 | ".globl tl_fiber_trampoline", |
| 635 | ".type tl_fiber_trampoline,@function", |
| 636 | ".p2align 4", |
| 637 | "tl_fiber_trampoline:", |
| 638 | " .cfi_startproc", |
| 639 | " .cfi_undefined rip", |
| 640 | " mov rdi, rbx", |
| 641 | " call r12", |
| 642 | " ud2", |
| 643 | " .cfi_endproc", |
| 644 | ".size tl_fiber_trampoline, .-tl_fiber_trampoline", |
| 645 | ); |
| 646 | } |
| 647 | |
| 648 | /// Tested under qemu (`scripts/aarch64.sh`), not yet on hardware |
| 649 | /// (ADR 0011, 2026-10-12 note). Pointer authentication and branch |
| 650 | /// target identification are not handled. |
| 651 | #[cfg(target_arch = "aarch64")] |
| 652 | mod arch { |
| 653 | use super::Stack; |
| 654 | |
| 655 | /// The frame `tl_fiber_switch` saves (22 words, 176 bytes; a |
| 656 | /// multiple of 16, so `sp` stays aligned). Indices in words. |
| 657 | const FRAME: usize = 22; |
| 658 | const X19: usize = 0; // x19–x28 at 0..10, then fp (x29) and lr (x30) |
| 659 | const X20: usize = 1; |
| 660 | const LR: usize = 11; // d8–d15 at 12..20, FPCR at 20, padding at 21 |
| 661 | |
| 662 | /// Lay out the frame `tl_fiber_switch` pops on the first resume: |
| 663 | /// x19 = `start`, x20 = `entry`, fp = 0 (ends frame-pointer |
| 664 | /// backtraces), lr = `tl_fiber_trampoline`, which calls |
| 665 | /// `entry(start)`; d8–d15 zero, FPCR 0 (Linux's default: round to |
| 666 | /// nearest, no traps). |
| 667 | pub(super) fn initial_frame(stack: &Stack, start: *mut u8, entry: usize) -> usize { |
| 668 | let top = stack.top() & !15; |
| 669 | let mut words = [0usize; FRAME]; |
| 670 | words[X19] = start as usize; |
| 671 | words[X20] = entry; |
| 672 | words[LR] = tl_fiber_trampoline as *const () as usize; |
| 673 | let sp = top - FRAME * 8; |
| 674 | // SAFETY: the words fit in the stack's top 176 bytes. |
| 675 | unsafe { |
| 676 | std::ptr::copy_nonoverlapping(words.as_ptr(), sp as *mut usize, FRAME); |
| 677 | } |
| 678 | sp |
| 679 | } |
| 680 | |
| 681 | unsafe extern "C" { |
| 682 | /// Save the current context, storing its stack pointer in |
| 683 | /// `save`, and continue the one suspended at `to`. |
| 684 | pub(super) fn tl_fiber_switch(save: *mut usize, to: usize); |
| 685 | fn tl_fiber_trampoline(); |
| 686 | } |
| 687 | |
| 688 | // AAPCS64: x19–x28, x29 (fp), x30 (lr), the low halves of v8–v15 |
| 689 | // (d8–d15) and FPCR are callee-saved; everything else may be |
| 690 | // clobbered by a call, which is what the switch looks like to its |
| 691 | // callers. FPSR holds status flags only, and is not preserved. |
| 692 | // `ret` returns to the restored lr: into the other context's call |
| 693 | // of `tl_fiber_switch`, or, the first time, to the trampoline. |
| 694 | std::arch::global_asm!( |
| 695 | ".text", |
| 696 | ".globl tl_fiber_switch", |
| 697 | ".type tl_fiber_switch,%function", |
| 698 | ".p2align 4", |
| 699 | "tl_fiber_switch:", |
| 700 | " .cfi_startproc", |
| 701 | " sub sp, sp, #176", |
| 702 | " stp x19, x20, [sp, #0]", |
| 703 | " stp x21, x22, [sp, #16]", |
| 704 | " stp x23, x24, [sp, #32]", |
| 705 | " stp x25, x26, [sp, #48]", |
| 706 | " stp x27, x28, [sp, #64]", |
| 707 | " stp x29, x30, [sp, #80]", |
| 708 | " stp d8, d9, [sp, #96]", |
| 709 | " stp d10, d11, [sp, #112]", |
| 710 | " stp d12, d13, [sp, #128]", |
| 711 | " stp d14, d15, [sp, #144]", |
| 712 | " mrs x9, fpcr", |
| 713 | " str x9, [sp, #160]", |
| 714 | " mov x9, sp", |
| 715 | " str x9, [x0]", |
| 716 | " mov sp, x1", |
| 717 | " ldr x9, [sp, #160]", |
| 718 | " msr fpcr, x9", |
| 719 | " ldp d14, d15, [sp, #144]", |
| 720 | " ldp d12, d13, [sp, #128]", |
| 721 | " ldp d10, d11, [sp, #112]", |
| 722 | " ldp d8, d9, [sp, #96]", |
| 723 | " ldp x29, x30, [sp, #80]", |
| 724 | " ldp x27, x28, [sp, #64]", |
| 725 | " ldp x25, x26, [sp, #48]", |
| 726 | " ldp x23, x24, [sp, #32]", |
| 727 | " ldp x21, x22, [sp, #16]", |
| 728 | " ldp x19, x20, [sp, #0]", |
| 729 | " add sp, sp, #176", |
| 730 | " ret", |
| 731 | " .cfi_endproc", |
| 732 | ".size tl_fiber_switch, .-tl_fiber_switch", |
| 733 | "", |
| 734 | ".globl tl_fiber_trampoline", |
| 735 | ".type tl_fiber_trampoline,%function", |
| 736 | ".p2align 4", |
| 737 | "tl_fiber_trampoline:", |
| 738 | " .cfi_startproc", |
| 739 | " .cfi_undefined x30", |
| 740 | " mov x0, x19", |
| 741 | " blr x20", |
| 742 | " brk #0", |
| 743 | " .cfi_endproc", |
| 744 | ".size tl_fiber_trampoline, .-tl_fiber_trampoline", |
| 745 | ); |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | #[cfg(test)] |
| 750 | mod tests { |
| 751 | use super::*; |
| 752 | |
| 753 | #[test] |
| 754 | fn values_flow_both_ways() { |
| 755 | let mut co = Coroutine::with_stack( |
| 756 | Stack::new(64 << 10).unwrap(), |
| 757 | |y: &Yielder<i32, i32>, first| { |
| 758 | let mut total = first; |
| 759 | for i in 0..3 { |
| 760 | total += y.suspend(i); |
| 761 | } |
| 762 | total * 10 |
| 763 | }, |
| 764 | ); |
| 765 | assert!(matches!(co.resume(1), CoroutineResult::Yield(0))); |
| 766 | assert!(matches!(co.resume(2), CoroutineResult::Yield(1))); |
| 767 | assert!(matches!(co.resume(3), CoroutineResult::Yield(2))); |
| 768 | assert!(matches!(co.resume(4), CoroutineResult::Return(100))); |
| 769 | |
| 770 | // Reinitialise coroutine B on coroutine A's exact mapping, not |
| 771 | // merely extract an unused stack. |
| 772 | let stack = co.into_stack(); |
| 773 | let mut reused = Coroutine::with_stack(stack, |y: &Yielder<i32, i32>, first| { |
| 774 | first + y.suspend(first + 1) |
| 775 | }); |
| 776 | assert!(matches!(reused.resume(40), CoroutineResult::Yield(41))); |
| 777 | assert!(matches!(reused.resume(1), CoroutineResult::Return(41))); |
| 778 | } |
| 779 | |
| 780 | #[test] |
| 781 | fn nested_fibers_and_float_state() { |
| 782 | let mut outer = Coroutine::with_stack( |
| 783 | Stack::new(256 << 10).unwrap(), |
| 784 | |y: &Yielder<(), f64>, ()| { |
| 785 | let mut inner = Coroutine::with_stack( |
| 786 | Stack::new(64 << 10).unwrap(), |
| 787 | |y2: &Yielder<(), f64>, ()| { |
| 788 | y2.suspend(1.5); |
| 789 | 2.25 |
| 790 | }, |
| 791 | ); |
| 792 | let CoroutineResult::Yield(a) = inner.resume(()) else { |
| 793 | panic!() |
| 794 | }; |
| 795 | y.suspend(a); |
| 796 | let CoroutineResult::Return(b) = inner.resume(()) else { |
| 797 | panic!() |
| 798 | }; |
| 799 | a * b |
| 800 | }, |
| 801 | ); |
| 802 | assert!(matches!(outer.resume(()), CoroutineResult::Yield(x) if x == 1.5)); |
| 803 | assert!(matches!(outer.resume(()), CoroutineResult::Return(x) if x == 3.375)); |
| 804 | } |
| 805 | |
| 806 | #[test] |
| 807 | fn a_suspended_fiber_resumes_on_another_thread() { |
| 808 | struct SendCo(Coroutine<u64, u64, u64>); |
| 809 | // SAFETY: the body holds no thread-local state across `suspend`. |
| 810 | unsafe impl Send for SendCo {} |
| 811 | let mut co = SendCo(Coroutine::with_stack( |
| 812 | Stack::new(64 << 10).unwrap(), |
| 813 | |y: &Yielder<u64, u64>, a| { |
| 814 | let b = y.suspend(a + 1); |
| 815 | a + b |
| 816 | }, |
| 817 | )); |
| 818 | assert!(matches!(co.0.resume(10), CoroutineResult::Yield(11))); |
| 819 | let handle = std::thread::spawn(move || { |
| 820 | let mut co = co; |
| 821 | matches!(co.0.resume(5), CoroutineResult::Return(15)) |
| 822 | }); |
| 823 | assert!(handle.join().unwrap()); |
| 824 | } |
| 825 | |
| 826 | #[test] |
| 827 | fn a_snapshot_resumes_again_where_it_was_taken() { |
| 828 | let mut co = Coroutine::with_stack( |
| 829 | Stack::new(64 << 10).unwrap(), |
| 830 | |y: &Yielder<u64, u64>, base| { |
| 831 | let local = [base; 4]; // on the fiber's stack |
| 832 | let x = y.suspend(local[3]); |
| 833 | std::hint::black_box(local)[0] * 100 + x |
| 834 | }, |
| 835 | ); |
| 836 | assert!(matches!(co.resume(7), CoroutineResult::Yield(7))); |
| 837 | let snap = co.snapshot(); |
| 838 | assert!(matches!(co.resume(1), CoroutineResult::Return(701))); |
| 839 | co.restore(&snap); |
| 840 | assert!(matches!(co.resume(2), CoroutineResult::Return(702))); |
| 841 | co.restore(&snap); |
| 842 | assert!(matches!(co.resume(3), CoroutineResult::Return(703))); |
| 843 | } |
| 844 | |
| 845 | #[test] |
| 846 | fn stack_tops_are_aligned_and_leave_the_size_asked_for() { |
| 847 | for size in [64 << 10, 256 << 10, 64 << 20] { |
| 848 | let s = Stack::new(size).unwrap(); |
| 849 | assert_eq!(s.region_top % REGION, 0); |
| 850 | assert!(s.top() <= s.region_top); |
| 851 | assert!(s.top() - (s.base as usize + page()) >= size); |
| 852 | assert!(s.region_top <= s.base as usize + s.len); |
| 853 | } |
| 854 | let handler = Stack::new(16 << 20).unwrap(); |
| 855 | let (base, len) = handler.map_extent(); |
| 856 | assert_eq!(base, handler.base); |
| 857 | assert_eq!(len, page() + (16 << 20) + COLORS * color_step() + REGION); |
| 858 | if page() == 4096 { |
| 859 | assert_eq!(len, 19_011_584, "18.131 MiB including all overhead"); |
| 860 | } |
| 861 | } |
| 862 | |
| 863 | #[test] |
| 864 | fn a_hibernated_fiber_resumes_where_it_was() { |
| 865 | let mut co = Coroutine::with_stack( |
| 866 | Stack::new(64 << 20).unwrap(), |
| 867 | |y: &Yielder<u64, u64>, base| { |
| 868 | let local = [base, base + 1, base + 2, base + 3]; // on the stack |
| 869 | let x = y.suspend(local[1]); |
| 870 | let x = x + y.suspend(std::hint::black_box(&local)[2]); |
| 871 | std::hint::black_box(local).iter().sum::<u64>() + x |
| 872 | }, |
| 873 | ); |
| 874 | assert!(matches!(co.resume(10), CoroutineResult::Yield(11))); |
| 875 | let snap = co.hibernate(); |
| 876 | // The stack reads as zeros now: only the snapshot holds the frames. |
| 877 | assert!( |
| 878 | snap.words.contains(&11), |
| 879 | "the suspended frame holds `local`" |
| 880 | ); |
| 881 | // SAFETY: `sp` is inside the mapping, above its guard page. |
| 882 | assert_eq!(unsafe { (snap.sp as *const usize).read_volatile() }, 0); |
| 883 | co.restore(&snap); |
| 884 | assert!(matches!(co.resume(1), CoroutineResult::Yield(12))); |
| 885 | let snap = co.hibernate(); |
| 886 | co.restore(&snap); |
| 887 | assert!(matches!(co.resume(2), CoroutineResult::Return(49))); |
| 888 | } |
| 889 | |
| 890 | #[test] |
| 891 | fn deep_recursion_runs_on_the_fiber_stack() { |
| 892 | fn depth(n: u32) -> u32 { |
| 893 | let pad = [n; 32]; |
| 894 | if n == 0 { |
| 895 | 0 |
| 896 | } else { |
| 897 | 1 + depth(std::hint::black_box(pad)[0] - 1) |
| 898 | } |
| 899 | } |
| 900 | let mut co = |
| 901 | Coroutine::with_stack(Stack::new(64 << 20).unwrap(), |_: &Yielder<(), ()>, ()| { |
| 902 | depth(10_000) |
| 903 | }); |
| 904 | assert!(matches!(co.resume(()), CoroutineResult::Return(10_000))); |
| 905 | } |
| 906 | } |