| @@ -0,0 +1,441 @@ |
| 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 API mirrors the subset of corosensei the runtime used. |
| 6 | +//! |
| 7 | +//! - **Stacks** are the runtime's own: an anonymous mapping with a guard |
| 8 | +//! page at its low end, committed lazily by the kernel. |
| 9 | +//! - **The switch** is the runtime's own on x86_64 Linux: it saves the |
| 10 | +//! callee-saved registers (and the SSE/x87 control words) on the current |
| 11 | +//! stack, stores the stack pointer, and loads the other one. A suspended |
| 12 | +//! fiber is just its saved stack pointer, so it may resume on any |
| 13 | +//! thread. Other targets use corosensei on the same stacks. |
| 14 | +//! |
| 15 | +//! Rules (as before): |
| 16 | +//! - a fiber is never dropped while suspended: its frames would never run |
| 17 | +//! their drops (corosensei would force-unwind them through C instead); |
| 18 | +//! - code on a fiber must not hold thread-local state across a suspension, |
| 19 | +//! since it may resume on another thread (see `sched::Fiber`). |
| 20 | + |
| 21 | +/// A fiber stack: `size` usable bytes above one guard page. |
| 22 | +pub(crate) struct Stack { |
| 23 | + base: *mut u8, |
| 24 | + len: usize, |
| 25 | +} |
| 26 | + |
| 27 | +// SAFETY: a stack is plain memory, owned by one fiber at a time. |
| 28 | +unsafe impl Send for Stack {} |
| 29 | + |
| 30 | +const PAGE: usize = 4096; |
| 31 | + |
| 32 | +impl Stack { |
| 33 | + pub(crate) fn new(size: usize) -> std::io::Result<Stack> { |
| 34 | + let len = size.div_ceil(PAGE) * PAGE + PAGE; |
| 35 | + // SAFETY: a fresh private anonymous mapping; nothing aliases it. |
| 36 | + unsafe { |
| 37 | + let base = libc::mmap( |
| 38 | + std::ptr::null_mut(), |
| 39 | + len, |
| 40 | + libc::PROT_READ | libc::PROT_WRITE, |
| 41 | + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE, |
| 42 | + -1, |
| 43 | + 0, |
| 44 | + ); |
| 45 | + if base == libc::MAP_FAILED { |
| 46 | + return Err(std::io::Error::last_os_error()); |
| 47 | + } |
| 48 | + // The lowest page catches overflows (stacks grow down). |
| 49 | + if libc::mprotect(base, PAGE, libc::PROT_NONE) != 0 { |
| 50 | + let e = std::io::Error::last_os_error(); |
| 51 | + libc::munmap(base, len); |
| 52 | + return Err(e); |
| 53 | + } |
| 54 | + Ok(Stack { |
| 55 | + base: base.cast(), |
| 56 | + len, |
| 57 | + }) |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + /// The highest address (exclusive): stacks grow down from here. |
| 62 | + fn top(&self) -> usize { |
| 63 | + self.base as usize + self.len |
| 64 | + } |
| 65 | + |
| 66 | + /// The lowest usable address (just above the guard page). |
| 67 | + #[cfg_attr(all(target_arch = "x86_64", target_os = "linux"), allow(dead_code))] |
| 68 | + fn limit(&self) -> usize { |
| 69 | + self.base as usize + PAGE |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +impl Drop for Stack { |
| 74 | + fn drop(&mut self) { |
| 75 | + // SAFETY: the mapping made in `new`, unmapped once. |
| 76 | + unsafe { libc::munmap(self.base.cast(), self.len) }; |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +/// What `resume` returns: the fiber suspended with a value, or finished. |
| 81 | +pub(crate) enum CoroutineResult<Y, R> { |
| 82 | + Yield(Y), |
| 83 | + Return(R), |
| 84 | +} |
| 85 | + |
| 86 | +pub(crate) use imp::{Coroutine, Yielder}; |
| 87 | + |
| 88 | +#[cfg(all(target_arch = "x86_64", target_os = "linux"))] |
| 89 | +mod imp { |
| 90 | + use std::marker::PhantomData; |
| 91 | + |
| 92 | + use super::{CoroutineResult, Stack}; |
| 93 | + |
| 94 | + /// Where a fiber and the code resuming it exchange values. Boxed, so |
| 95 | + /// its address is stable while the fiber is suspended. |
| 96 | + struct Channel<I, Y> { |
| 97 | + /// The resumer's saved stack pointer (while the fiber runs). |
| 98 | + caller_sp: usize, |
| 99 | + /// The fiber's saved stack pointer (while it is suspended). |
| 100 | + fiber_sp: usize, |
| 101 | + input: Option<I>, |
| 102 | + output: Option<Y>, |
| 103 | + finished: bool, |
| 104 | + } |
| 105 | + |
| 106 | + /// Handed to the fiber's body; `suspend` returns to the resumer. |
| 107 | + pub(crate) struct Yielder<I, Y> { |
| 108 | + channel: *mut Channel<I, Y>, |
| 109 | + } |
| 110 | + |
| 111 | + impl<I, Y> Yielder<I, Y> { |
| 112 | + /// Suspend the fiber with `value`; returns the next resume's input. |
| 113 | + pub(crate) fn suspend(&self, value: Y) -> I { |
| 114 | + // SAFETY: the channel outlives the fiber; only the running |
| 115 | + // fiber calls this, on its own stack. |
| 116 | + unsafe { |
| 117 | + let c = self.channel; |
| 118 | + (*c).output = Some(value); |
| 119 | + tl_fiber_switch(&raw mut (*c).fiber_sp, (*c).caller_sp); |
| 120 | + (*c).input.take().expect("tilrt: resumed without input") |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + |
| 125 | + pub(crate) struct Coroutine<I, Y, R> { |
| 126 | + channel: Box<Channel<I, Y>>, |
| 127 | + result: Box<Option<R>>, |
| 128 | + stack: Option<Stack>, |
| 129 | + _body: PhantomData<fn(I) -> R>, |
| 130 | + } |
| 131 | + |
| 132 | + /// What the new fiber's first frame needs: its body and where to put |
| 133 | + /// the result. |
| 134 | + struct Start<I, Y, R, F> { |
| 135 | + body: F, |
| 136 | + channel: *mut Channel<I, Y>, |
| 137 | + result: *mut Option<R>, |
| 138 | + } |
| 139 | + |
| 140 | + impl<I, Y, R> Coroutine<I, Y, R> { |
| 141 | + pub(crate) fn with_stack<F>(stack: Stack, body: F) -> Self |
| 142 | + where |
| 143 | + F: FnOnce(&Yielder<I, Y>, I) -> R, |
| 144 | + { |
| 145 | + let mut channel = Box::new(Channel { |
| 146 | + caller_sp: 0, |
| 147 | + fiber_sp: 0, |
| 148 | + input: None, |
| 149 | + output: None, |
| 150 | + finished: false, |
| 151 | + }); |
| 152 | + let mut result = Box::new(None); |
| 153 | + let start = Box::into_raw(Box::new(Start { |
| 154 | + body, |
| 155 | + channel: &raw mut *channel, |
| 156 | + result: &raw mut *result, |
| 157 | + })); |
| 158 | + channel.fiber_sp = initial_frame( |
| 159 | + &stack, |
| 160 | + start.cast(), |
| 161 | + entry::<I, Y, R, F> as *const () as usize, |
| 162 | + ); |
| 163 | + Coroutine { |
| 164 | + channel, |
| 165 | + result, |
| 166 | + stack: Some(stack), |
| 167 | + _body: PhantomData, |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + /// Run the fiber until it suspends or returns. |
| 172 | + pub(crate) fn resume(&mut self, input: I) -> CoroutineResult<Y, R> { |
| 173 | + let c = &raw mut *self.channel; |
| 174 | + // SAFETY: the fiber is suspended (or not started) at |
| 175 | + // `fiber_sp`; it switches back to `caller_sp`. |
| 176 | + unsafe { |
| 177 | + assert!(!(*c).finished, "tilrt: resumed a finished fiber"); |
| 178 | + (*c).input = Some(input); |
| 179 | + tl_fiber_switch(&raw mut (*c).caller_sp, (*c).fiber_sp); |
| 180 | + if (*c).finished { |
| 181 | + CoroutineResult::Return(self.result.take().expect("tilrt: fiber result")) |
| 182 | + } else { |
| 183 | + CoroutineResult::Yield((*c).output.take().expect("tilrt: fiber value")) |
| 184 | + } |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + /// The stack of a finished fiber, for reuse. |
| 189 | + pub(crate) fn into_stack(mut self) -> Stack { |
| 190 | + assert!(self.channel.finished, "tilrt: the fiber is still running"); |
| 191 | + self.stack.take().expect("stack") |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + impl<I, Y, R> Drop for Coroutine<I, Y, R> { |
| 196 | + fn drop(&mut self) { |
| 197 | + if !self.channel.finished |
| 198 | + && let Some(stack) = self.stack.take() |
| 199 | + { |
| 200 | + // A suspended fiber's frames hold references they never |
| 201 | + // drop: leak its stack rather than reuse live memory. |
| 202 | + std::mem::forget(stack); |
| 203 | + } |
| 204 | + } |
| 205 | + } |
| 206 | + |
| 207 | + /// The fiber's first Rust frame: run the body, publish its result, |
| 208 | + /// switch back for good. |
| 209 | + extern "C" fn entry<I, Y, R, F>(start: *mut u8) -> ! |
| 210 | + where |
| 211 | + F: FnOnce(&Yielder<I, Y>, I) -> R, |
| 212 | + { |
| 213 | + // SAFETY: `start` is the box made by `with_stack`, used once. |
| 214 | + unsafe { |
| 215 | + // Moved out (and the box freed) in this statement: this frame |
| 216 | + // never returns, so nothing owned may outlive the final switch. |
| 217 | + let Start { |
| 218 | + body, |
| 219 | + channel, |
| 220 | + result, |
| 221 | + } = *Box::from_raw(start.cast::<Start<I, Y, R, F>>()); |
| 222 | + let yielder = Yielder { channel }; |
| 223 | + let input = (*channel) |
| 224 | + .input |
| 225 | + .take() |
| 226 | + .expect("tilrt: started without input"); |
| 227 | + *result = Some(body(&yielder, input)); |
| 228 | + (*channel).finished = true; |
| 229 | + let mut dead_sp = 0; |
| 230 | + tl_fiber_switch(&raw mut dead_sp, (*channel).caller_sp); |
| 231 | + unreachable!("tilrt: a finished fiber was resumed"); |
| 232 | + } |
| 233 | + } |
| 234 | + |
| 235 | + /// Lay out the frame `tl_fiber_switch` pops on the first resume: the |
| 236 | + /// control words, six callee-saved registers (rbx = `start`, r12 = |
| 237 | + /// `entry`), then the return address `tl_fiber_trampoline`, which |
| 238 | + /// calls `entry(start)` with the stack aligned as after a call. |
| 239 | + fn initial_frame(stack: &Stack, start: *mut u8, entry: usize) -> usize { |
| 240 | + let top = stack.top() & !15; |
| 241 | + let words: [usize; 10] = [ |
| 242 | + 0x037F_0000_1F80, // MXCSR (low half) and the x87 control word |
| 243 | + 0, // r15 |
| 244 | + 0, // r14 |
| 245 | + 0, // r13 |
| 246 | + entry, // r12 |
| 247 | + start as usize, // rbx |
| 248 | + 0, // rbp |
| 249 | + tl_fiber_trampoline as *const () as usize, |
| 250 | + 0, // the trampoline's "return address": ends backtraces |
| 251 | + 0, // padding (keeps `top` 16-aligned) |
| 252 | + ]; |
| 253 | + let sp = top - words.len() * 8; |
| 254 | + // SAFETY: the words fit in the stack's top 80 bytes. |
| 255 | + unsafe { |
| 256 | + std::ptr::copy_nonoverlapping(words.as_ptr(), sp as *mut usize, words.len()); |
| 257 | + } |
| 258 | + sp |
| 259 | + } |
| 260 | + |
| 261 | + unsafe extern "C" { |
| 262 | + /// Save the current context, storing its stack pointer in `save`, |
| 263 | + /// and continue the one suspended at `to`. |
| 264 | + fn tl_fiber_switch(save: *mut usize, to: usize); |
| 265 | + fn tl_fiber_trampoline(); |
| 266 | + } |
| 267 | + |
| 268 | + // System V x86_64: rbx, rbp, r12–r15, MXCSR's control bits and the x87 |
| 269 | + // control word are callee-saved; everything else may be clobbered by a |
| 270 | + // call, which is what the switch looks like to its callers. |
| 271 | + std::arch::global_asm!( |
| 272 | + ".text", |
| 273 | + ".globl tl_fiber_switch", |
| 274 | + ".type tl_fiber_switch,@function", |
| 275 | + ".p2align 4", |
| 276 | + "tl_fiber_switch:", |
| 277 | + " .cfi_startproc", |
| 278 | + " push rbp", |
| 279 | + " push rbx", |
| 280 | + " push r12", |
| 281 | + " push r13", |
| 282 | + " push r14", |
| 283 | + " push r15", |
| 284 | + " sub rsp, 8", |
| 285 | + " stmxcsr [rsp]", |
| 286 | + " fnstcw [rsp + 4]", |
| 287 | + " mov [rdi], rsp", |
| 288 | + " mov rsp, rsi", |
| 289 | + " ldmxcsr [rsp]", |
| 290 | + " fldcw [rsp + 4]", |
| 291 | + " add rsp, 8", |
| 292 | + " pop r15", |
| 293 | + " pop r14", |
| 294 | + " pop r13", |
| 295 | + " pop r12", |
| 296 | + " pop rbx", |
| 297 | + " pop rbp", |
| 298 | + " ret", |
| 299 | + " .cfi_endproc", |
| 300 | + ".size tl_fiber_switch, .-tl_fiber_switch", |
| 301 | + "", |
| 302 | + ".globl tl_fiber_trampoline", |
| 303 | + ".type tl_fiber_trampoline,@function", |
| 304 | + ".p2align 4", |
| 305 | + "tl_fiber_trampoline:", |
| 306 | + " .cfi_startproc", |
| 307 | + " .cfi_undefined rip", |
| 308 | + " mov rdi, rbx", |
| 309 | + " call r12", |
| 310 | + " ud2", |
| 311 | + " .cfi_endproc", |
| 312 | + ".size tl_fiber_trampoline, .-tl_fiber_trampoline", |
| 313 | + ); |
| 314 | +} |
| 315 | + |
| 316 | +#[cfg(not(all(target_arch = "x86_64", target_os = "linux")))] |
| 317 | +mod imp { |
| 318 | + //! corosensei on the runtime's stacks. |
| 319 | + use super::{CoroutineResult, Stack}; |
| 320 | + |
| 321 | + // SAFETY: `base`/`limit` describe the mapping above its guard page. |
| 322 | + unsafe impl corosensei::stack::Stack for Stack { |
| 323 | + fn base(&self) -> corosensei::stack::StackPointer { |
| 324 | + corosensei::stack::StackPointer::new(self.top() & !15).expect("stack top") |
| 325 | + } |
| 326 | + fn limit(&self) -> corosensei::stack::StackPointer { |
| 327 | + corosensei::stack::StackPointer::new(self.limit()).expect("stack limit") |
| 328 | + } |
| 329 | + } |
| 330 | + |
| 331 | + pub(crate) type Yielder<I, Y> = corosensei::Yielder<I, Y>; |
| 332 | + |
| 333 | + pub(crate) struct Coroutine<I, Y, R>(corosensei::Coroutine<I, Y, R, Stack>); |
| 334 | + |
| 335 | + impl<I: 'static, Y: 'static, R: 'static> Coroutine<I, Y, R> { |
| 336 | + pub(crate) fn with_stack<F>(stack: Stack, body: F) -> Self |
| 337 | + where |
| 338 | + F: FnOnce(&Yielder<I, Y>, I) -> R + 'static, |
| 339 | + { |
| 340 | + Coroutine(corosensei::Coroutine::with_stack(stack, body)) |
| 341 | + } |
| 342 | + |
| 343 | + pub(crate) fn resume(&mut self, input: I) -> CoroutineResult<Y, R> { |
| 344 | + match self.0.resume(input) { |
| 345 | + corosensei::CoroutineResult::Yield(y) => CoroutineResult::Yield(y), |
| 346 | + corosensei::CoroutineResult::Return(r) => CoroutineResult::Return(r), |
| 347 | + } |
| 348 | + } |
| 349 | + |
| 350 | + pub(crate) fn into_stack(self) -> Stack { |
| 351 | + self.0.into_stack() |
| 352 | + } |
| 353 | + } |
| 354 | +} |
| 355 | + |
| 356 | +#[cfg(test)] |
| 357 | +mod tests { |
| 358 | + use super::*; |
| 359 | + |
| 360 | + #[test] |
| 361 | + fn values_flow_both_ways() { |
| 362 | + let mut co = Coroutine::with_stack( |
| 363 | + Stack::new(64 << 10).unwrap(), |
| 364 | + |y: &Yielder<i32, i32>, first| { |
| 365 | + let mut total = first; |
| 366 | + for i in 0..3 { |
| 367 | + total += y.suspend(i); |
| 368 | + } |
| 369 | + total * 10 |
| 370 | + }, |
| 371 | + ); |
| 372 | + assert!(matches!(co.resume(1), CoroutineResult::Yield(0))); |
| 373 | + assert!(matches!(co.resume(2), CoroutineResult::Yield(1))); |
| 374 | + assert!(matches!(co.resume(3), CoroutineResult::Yield(2))); |
| 375 | + assert!(matches!(co.resume(4), CoroutineResult::Return(100))); |
| 376 | + let _reused = co.into_stack(); |
| 377 | + } |
| 378 | + |
| 379 | + #[test] |
| 380 | + fn nested_fibers_and_float_state() { |
| 381 | + let mut outer = Coroutine::with_stack( |
| 382 | + Stack::new(256 << 10).unwrap(), |
| 383 | + |y: &Yielder<(), f64>, ()| { |
| 384 | + let mut inner = Coroutine::with_stack( |
| 385 | + Stack::new(64 << 10).unwrap(), |
| 386 | + |y2: &Yielder<(), f64>, ()| { |
| 387 | + y2.suspend(1.5); |
| 388 | + 2.25 |
| 389 | + }, |
| 390 | + ); |
| 391 | + let CoroutineResult::Yield(a) = inner.resume(()) else { |
| 392 | + panic!() |
| 393 | + }; |
| 394 | + y.suspend(a); |
| 395 | + let CoroutineResult::Return(b) = inner.resume(()) else { |
| 396 | + panic!() |
| 397 | + }; |
| 398 | + a * b |
| 399 | + }, |
| 400 | + ); |
| 401 | + assert!(matches!(outer.resume(()), CoroutineResult::Yield(x) if x == 1.5)); |
| 402 | + assert!(matches!(outer.resume(()), CoroutineResult::Return(x) if x == 3.375)); |
| 403 | + } |
| 404 | + |
| 405 | + #[test] |
| 406 | + fn a_suspended_fiber_resumes_on_another_thread() { |
| 407 | + struct SendCo(Coroutine<u64, u64, u64>); |
| 408 | + // SAFETY: the body holds no thread-local state across `suspend`. |
| 409 | + unsafe impl Send for SendCo {} |
| 410 | + let mut co = SendCo(Coroutine::with_stack( |
| 411 | + Stack::new(64 << 10).unwrap(), |
| 412 | + |y: &Yielder<u64, u64>, a| { |
| 413 | + let b = y.suspend(a + 1); |
| 414 | + a + b |
| 415 | + }, |
| 416 | + )); |
| 417 | + assert!(matches!(co.0.resume(10), CoroutineResult::Yield(11))); |
| 418 | + let handle = std::thread::spawn(move || { |
| 419 | + let mut co = co; |
| 420 | + matches!(co.0.resume(5), CoroutineResult::Return(15)) |
| 421 | + }); |
| 422 | + assert!(handle.join().unwrap()); |
| 423 | + } |
| 424 | + |
| 425 | + #[test] |
| 426 | + fn deep_recursion_runs_on_the_fiber_stack() { |
| 427 | + fn depth(n: u32) -> u32 { |
| 428 | + let pad = [n; 32]; |
| 429 | + if n == 0 { |
| 430 | + 0 |
| 431 | + } else { |
| 432 | + 1 + depth(std::hint::black_box(pad)[0] - 1) |
| 433 | + } |
| 434 | + } |
| 435 | + let mut co = |
| 436 | + Coroutine::with_stack(Stack::new(64 << 20).unwrap(), |_: &Yielder<(), ()>, ()| { |
| 437 | + depth(10_000) |
| 438 | + }); |
| 439 | + assert!(matches!(co.resume(()), CoroutineResult::Return(10_000))); |
| 440 | + } |
| 441 | +} |