| @@ -0,0 +1,440 @@ |
| 1 | +//! Handlers with `ctl` operations: one-shot continuations by stack |
| 2 | +//! switching (ADR 0003, Revision 1; ADR 0010 for routing). |
| 3 | +//! |
| 4 | +//! - `tl_handle_ctl` runs the handler's body on a fiber of its own. The |
| 5 | +//! calling stack drives it, as the interpreter's `drive` does. |
| 6 | +//! - `tl_perform_ctl` suspends the current fiber with a request naming |
| 7 | +//! the handler, by its marker. A handler that is not the target forwards |
| 8 | +//! the request to its own parent and passes the answer back down. |
| 9 | +//! - The target calls the clause with the arguments and a `resume` |
| 10 | +//! closure. Calling `resume` continues the fiber until it finishes |
| 11 | +//! (giving the handler's result, after the return clause) or performs |
| 12 | +//! the next operation (whose clause's result it is). |
| 13 | +//! - **One-shot.** Each suspension accepts exactly one `resume`; a second |
| 14 | +//! one panics. |
| 15 | +//! - **Cancellation.** When the outermost `tl_handle_ctl` finishes while |
| 16 | +//! the fiber still waits for a `resume` that never came, the fiber is |
| 17 | +//! resumed in *cancel* mode: its perform returns with `yielding = |
| 18 | +//! CANCEL`, generated code unwinds it, and every reference it held is |
| 19 | +//! dropped (exact Perceus). A `resume` called after that panics. |
| 20 | +//! - **Preemption** inside a fiber is forwarded up to the actor (the |
| 21 | +//! actor's own fiber yields to the scheduler), then back down. |
| 22 | +//! |
| 23 | +//! **Lifetimes.** A handler's frame lives in a heap block (`TAG_FRAME`) |
| 24 | +//! counted like any value. `tl_handle_ctl` holds one count, and each |
| 25 | +//! `resume` closure holds one. A frame's fiber has always finished, or |
| 26 | +//! been cancelled, before the frame is freed. |
| 27 | + |
| 28 | +use corosensei::stack::DefaultStack; |
| 29 | +use corosensei::{Coroutine, CoroutineResult, Yielder}; |
| 30 | + |
| 31 | +use crate::abi::{ |
| 32 | + Block, Ctx, TAG_FRAME, UNIT, Value, YIELD_CANCEL, YIELD_FINAL, YIELD_NONE, int, int_get, is_ptr, |
| 33 | +}; |
| 34 | +use crate::heap::{drop_value, tl_alloc}; |
| 35 | +use crate::prims::{call_closure, dup}; |
| 36 | + |
| 37 | +/// Virtual size of a handler fiber's stack (committed lazily). |
| 38 | +const FIBER_STACK: usize = 16 << 20; |
| 39 | + |
| 40 | +pub(crate) enum Resume { |
| 41 | + Value(Value), |
| 42 | + Cancel, |
| 43 | +} |
| 44 | + |
| 45 | +pub(crate) enum Request { |
| 46 | + /// An operation for the handler with this marker; the payload is the |
| 47 | + /// operation's index, then its arguments. |
| 48 | + Op { marker: u64, payload: Value }, |
| 49 | + /// The actor's reduction budget is spent: yield to the scheduler. |
| 50 | + Preempt, |
| 51 | +} |
| 52 | + |
| 53 | +pub(crate) type HandlerYielder = Yielder<Resume, Request>; |
| 54 | +type HandlerFiber = Coroutine<Resume, Request, Value, DefaultStack>; |
| 55 | + |
| 56 | +struct Frame { |
| 57 | + marker: u64, |
| 58 | + fiber: Option<HandlerFiber>, |
| 59 | + /// Owned: the capability block (clause closures, then the marker). |
| 60 | + cap: Value, |
| 61 | + /// Owned: the return clause, or unit. |
| 62 | + ret: Value, |
| 63 | + /// Suspensions so far; a `resume` closure belongs to one. |
| 64 | + suspensions: i64, |
| 65 | + /// Whether the fiber is suspended waiting for a `resume`. |
| 66 | + waiting: bool, |
| 67 | + /// Whether the handler finished while the fiber still waited. |
| 68 | + cancelled: bool, |
| 69 | +} |
| 70 | + |
| 71 | +const WORD: usize = size_of::<Value>(); |
| 72 | + |
| 73 | +/// # Safety |
| 74 | +/// `block` must be a live frame block. |
| 75 | +unsafe fn frame<'a>(block: Value) -> &'a mut Frame { |
| 76 | + // SAFETY: caller guarantees a frame block; its raw area holds the box. |
| 77 | + unsafe { |
| 78 | + &mut *Block::fields_ptr(block as *mut Block) |
| 79 | + .cast::<*mut Frame>() |
| 80 | + .read() |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +/// Called when a frame block is freed: release what the frame owns. |
| 85 | +/// |
| 86 | +/// # Safety |
| 87 | +/// `b` must be a frame block being freed. |
| 88 | +pub(crate) unsafe fn free_frame(b: *mut Block, pending: &mut Vec<*mut Block>) { |
| 89 | + // SAFETY: caller guarantees a frame block made by `tl_handle_ctl`; the |
| 90 | + // box is freed exactly once, here. |
| 91 | + unsafe { |
| 92 | + let f = Box::from_raw(Block::fields_ptr(b).cast::<*mut Frame>().read()); |
| 93 | + let Frame { |
| 94 | + fiber, cap, ret, .. |
| 95 | + } = *f; |
| 96 | + if let Some(fiber) = fiber { |
| 97 | + // Never happens (fibers finish or are cancelled first). A |
| 98 | + // suspended corosensei fiber must not be dropped (it would |
| 99 | + // force-unwind C frames): leak it instead. |
| 100 | + std::mem::forget(fiber); |
| 101 | + } |
| 102 | + crate::heap::release_into(cap, pending); |
| 103 | + crate::heap::release_into(ret, pending); |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +/// # Safety |
| 108 | +/// `ctx` must be the running actor's context. |
| 109 | +unsafe fn current<'a>(ctx: *mut Ctx) -> &'a mut *const HandlerYielder { |
| 110 | + // SAFETY: forwarded caller guarantee. |
| 111 | + unsafe { crate::sched::current_handler(ctx) } |
| 112 | +} |
| 113 | + |
| 114 | +/// Run `body` (consumed) under a handler with `ctl` operations, whose |
| 115 | +/// capability `cap` (consumed) holds the clauses and the marker, and whose |
| 116 | +/// return clause is `ret` (consumed; unit if none). |
| 117 | +/// |
| 118 | +/// # Safety |
| 119 | +/// `ctx` must be the running actor's context; the values must be owned and |
| 120 | +/// follow the generated-code conventions. |
| 121 | +#[unsafe(no_mangle)] |
| 122 | +pub unsafe extern "C" fn tl_handle_ctl( |
| 123 | + ctx: *mut Ctx, |
| 124 | + body: Value, |
| 125 | + cap: Value, |
| 126 | + ret: Value, |
| 127 | + marker: u64, |
| 128 | +) -> Value { |
| 129 | + let block = tl_alloc(ctx, TAG_FRAME, 0, WORD) as Value; |
| 130 | + let body_cap = dup(cap); |
| 131 | + let ctx_addr = ctx as usize; |
| 132 | + let stack = DefaultStack::new(FIBER_STACK).expect("tilrt: cannot allocate a handler fiber"); |
| 133 | + let fiber = HandlerFiber::with_stack(stack, move |yielder: &HandlerYielder, _: Resume| { |
| 134 | + let ctx = ctx_addr as *mut Ctx; |
| 135 | + // SAFETY: the fiber runs on the actor that created it. |
| 136 | + unsafe { |
| 137 | + *current(ctx) = yielder; |
| 138 | + call_closure(ctx, body, &[body_cap]) |
| 139 | + } |
| 140 | + }); |
| 141 | + let f = Box::into_raw(Box::new(Frame { |
| 142 | + marker, |
| 143 | + fiber: Some(fiber), |
| 144 | + cap, |
| 145 | + ret, |
| 146 | + suspensions: 0, |
| 147 | + waiting: false, |
| 148 | + cancelled: false, |
| 149 | + })); |
| 150 | + // SAFETY: the raw area holds the frame pointer. |
| 151 | + unsafe { |
| 152 | + Block::fields_ptr(block as *mut Block) |
| 153 | + .cast::<*mut Frame>() |
| 154 | + .write(f); |
| 155 | + let result = drive(ctx, block, Resume::Value(UNIT)); |
| 156 | + cancel(ctx, block); |
| 157 | + drop_value(ctx, block); |
| 158 | + result |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +/// Perform a `ctl` operation of the handler whose capability is `cap` |
| 163 | +/// (borrowed); `payload` (consumed) is the operation's index and |
| 164 | +/// arguments. Returns the value it is resumed with; when cancelled, |
| 165 | +/// returns unit with `yielding = CANCEL` (generated code unwinds). |
| 166 | +/// |
| 167 | +/// # Safety |
| 168 | +/// `ctx` must be the running actor's context; `cap` a handler capability. |
| 169 | +#[unsafe(no_mangle)] |
| 170 | +pub unsafe extern "C" fn tl_perform_ctl(ctx: *mut Ctx, cap: Value, payload: Value) -> Value { |
| 171 | + // SAFETY: caller guarantees a capability block: clauses, then marker. |
| 172 | + unsafe { |
| 173 | + let b = cap as *mut Block; |
| 174 | + let n = (*b).header.scan_fsize as usize; |
| 175 | + let marker = int_get(*Block::fields_ptr(b).add(n - 1)) as u64; |
| 176 | + suspend(ctx, Request::Op { marker, payload }) |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +/// Suspend the current fiber with `request`; the answer, or unit and |
| 181 | +/// `yielding = CANCEL`. |
| 182 | +/// |
| 183 | +/// # Safety |
| 184 | +/// `ctx` must be the running actor's context. |
| 185 | +unsafe fn suspend(ctx: *mut Ctx, request: Request) -> Value { |
| 186 | + // SAFETY: forwarded caller guarantee; `current` is the yielder of the |
| 187 | + // fiber executing this code. |
| 188 | + unsafe { |
| 189 | + let y = *current(ctx); |
| 190 | + if y.is_null() { |
| 191 | + if let Request::Op { payload, .. } = request { |
| 192 | + drop_value(ctx, payload); |
| 193 | + } |
| 194 | + return crate::effects::tl_panic_str( |
| 195 | + ctx, |
| 196 | + c"an operation reached the actor's root without a handler".as_ptr(), |
| 197 | + ); |
| 198 | + } |
| 199 | + let answer = (*y).suspend(request); |
| 200 | + *current(ctx) = y; |
| 201 | + match answer { |
| 202 | + Resume::Value(v) => v, |
| 203 | + Resume::Cancel => { |
| 204 | + (*ctx).yielding = YIELD_CANCEL; |
| 205 | + UNIT |
| 206 | + } |
| 207 | + } |
| 208 | + } |
| 209 | +} |
| 210 | + |
| 211 | +/// Preempt from inside a handler fiber: forward to the parent, up to the |
| 212 | +/// actor's own fiber. Returns false at the actor's root stack. |
| 213 | +/// |
| 214 | +/// # Safety |
| 215 | +/// `ctx` must be the running actor's context. |
| 216 | +pub(crate) unsafe fn preempt_in_fiber(ctx: *mut Ctx) -> bool { |
| 217 | + // SAFETY: forwarded caller guarantee. |
| 218 | + unsafe { |
| 219 | + if (*current(ctx)).is_null() { |
| 220 | + return false; |
| 221 | + } |
| 222 | + let v = suspend(ctx, Request::Preempt); |
| 223 | + drop_value(ctx, v); |
| 224 | + true |
| 225 | + } |
| 226 | +} |
| 227 | + |
| 228 | +/// Run the frame's fiber with `input` until it finishes or performs an |
| 229 | +/// operation of this handler; returns the handler's result. |
| 230 | +/// |
| 231 | +/// # Safety |
| 232 | +/// `ctx` must be the running actor's context; `block` a live frame. |
| 233 | +unsafe fn drive(ctx: *mut Ctx, block: Value, mut input: Resume) -> Value { |
| 234 | + // SAFETY: caller guarantees a live frame; the fiber runs on this actor. |
| 235 | + unsafe { |
| 236 | + loop { |
| 237 | + let f = frame(block); |
| 238 | + let Some(mut fiber) = f.fiber.take() else { |
| 239 | + return crate::effects::tl_panic_str( |
| 240 | + ctx, |
| 241 | + c"`resume` called after its handler finished".as_ptr(), |
| 242 | + ); |
| 243 | + }; |
| 244 | + let saved = *current(ctx); |
| 245 | + let step = fiber.resume(input); |
| 246 | + *current(ctx) = saved; |
| 247 | + let f = frame(block); |
| 248 | + match step { |
| 249 | + CoroutineResult::Return(value) => { |
| 250 | + drop(fiber); |
| 251 | + let c = &mut *ctx; |
| 252 | + if c.yielding == YIELD_FINAL && c.yield_marker == f.marker { |
| 253 | + let payload = std::mem::replace(&mut c.yield_value, UNIT); |
| 254 | + c.yielding = YIELD_NONE; |
| 255 | + return call_clause(ctx, f.cap, payload, None); |
| 256 | + } |
| 257 | + if c.yielding != YIELD_NONE { |
| 258 | + return UNIT; // unwinding continues in the caller |
| 259 | + } |
| 260 | + if is_ptr(f.ret) { |
| 261 | + return call_closure(ctx, dup(f.ret), &[value]); |
| 262 | + } |
| 263 | + return value; |
| 264 | + } |
| 265 | + CoroutineResult::Yield(request) => { |
| 266 | + f.fiber = Some(fiber); |
| 267 | + match request { |
| 268 | + Request::Preempt => { |
| 269 | + if !preempt_in_fiber(ctx) { |
| 270 | + crate::sched::preempt_root(ctx); |
| 271 | + } |
| 272 | + input = Resume::Value(UNIT); |
| 273 | + } |
| 274 | + Request::Op { marker, payload } if marker == f.marker => { |
| 275 | + f.suspensions += 1; |
| 276 | + f.waiting = true; |
| 277 | + let resume = resume_closure(ctx, block, f.suspensions); |
| 278 | + return call_clause(ctx, f.cap, payload, Some(resume)); |
| 279 | + } |
| 280 | + Request::Op { marker, payload } => { |
| 281 | + // Not ours: ask the handlers around this one. |
| 282 | + let answer = suspend(ctx, Request::Op { marker, payload }); |
| 283 | + input = if (*ctx).yielding == YIELD_CANCEL { |
| 284 | + Resume::Cancel |
| 285 | + } else { |
| 286 | + Resume::Value(answer) |
| 287 | + }; |
| 288 | + if let Resume::Cancel = input { |
| 289 | + // The fiber around us is being cancelled: |
| 290 | + // cancel ours, then keep unwinding. |
| 291 | + (*ctx).yielding = YIELD_NONE; |
| 292 | + cancel(ctx, block); |
| 293 | + (*ctx).yielding = YIELD_CANCEL; |
| 294 | + return UNIT; |
| 295 | + } |
| 296 | + } |
| 297 | + } |
| 298 | + } |
| 299 | + } |
| 300 | + } |
| 301 | + } |
| 302 | +} |
| 303 | + |
| 304 | +/// If the frame's fiber is suspended, resume it in cancel mode so it |
| 305 | +/// unwinds (dropping what it holds) and finishes. The unwinding state of |
| 306 | +/// the caller is preserved. |
| 307 | +/// |
| 308 | +/// # Safety |
| 309 | +/// `ctx` must be the running actor's context; `block` a live frame. |
| 310 | +unsafe fn cancel(ctx: *mut Ctx, block: Value) { |
| 311 | + // SAFETY: caller guarantees a live frame on this actor. |
| 312 | + unsafe { |
| 313 | + let f = frame(block); |
| 314 | + let Some(mut fiber) = f.fiber.take() else { |
| 315 | + return; |
| 316 | + }; |
| 317 | + f.waiting = false; |
| 318 | + f.cancelled = true; |
| 319 | + let c = &mut *ctx; |
| 320 | + let saved = ( |
| 321 | + c.yielding, |
| 322 | + c.yield_marker, |
| 323 | + std::mem::replace(&mut c.yield_value, UNIT), |
| 324 | + ); |
| 325 | + c.yielding = YIELD_NONE; |
| 326 | + let outer = *current(ctx); |
| 327 | + let mut input = Resume::Cancel; |
| 328 | + loop { |
| 329 | + match fiber.resume(input) { |
| 330 | + CoroutineResult::Return(value) => { |
| 331 | + drop_value(ctx, value); |
| 332 | + break; |
| 333 | + } |
| 334 | + // Cancelled code can still preempt (or, in a clause run |
| 335 | + // while unwinding, perform): keep it going. |
| 336 | + CoroutineResult::Yield(Request::Preempt) => { |
| 337 | + *current(ctx) = outer; |
| 338 | + if !preempt_in_fiber(ctx) { |
| 339 | + crate::sched::preempt_root(ctx); |
| 340 | + } |
| 341 | + input = Resume::Value(UNIT); |
| 342 | + } |
| 343 | + CoroutineResult::Yield(Request::Op { payload, .. }) => { |
| 344 | + drop_value(ctx, payload); |
| 345 | + input = Resume::Cancel; |
| 346 | + } |
| 347 | + } |
| 348 | + } |
| 349 | + *current(ctx) = outer; |
| 350 | + let c = &mut *ctx; |
| 351 | + drop_value(ctx, std::mem::replace(&mut c.yield_value, saved.2)); |
| 352 | + c.yielding = saved.0; |
| 353 | + c.yield_marker = saved.1; |
| 354 | + } |
| 355 | +} |
| 356 | + |
| 357 | +/// Call the clause of `cap` for the operation in `payload` (consumed): |
| 358 | +/// its arguments, then `resume` if given. |
| 359 | +/// |
| 360 | +/// # Safety |
| 361 | +/// `ctx` must be the running actor's context; `cap` a live capability. |
| 362 | +unsafe fn call_clause(ctx: *mut Ctx, cap: Value, payload: Value, resume: Option<Value>) -> Value { |
| 363 | + // SAFETY: caller guarantees a capability and a payload block. |
| 364 | + unsafe { |
| 365 | + let p = payload as *mut Block; |
| 366 | + let n = (*p).header.scan_fsize as usize; |
| 367 | + let fields = Block::fields_ptr(p); |
| 368 | + let op = int_get(*fields) as usize; |
| 369 | + let clause = dup(*Block::fields_ptr(cap as *mut Block).add(op)); |
| 370 | + let mut args: Vec<Value> = (1..n).map(|i| dup(*fields.add(i))).collect(); |
| 371 | + drop_value(ctx, payload); |
| 372 | + args.extend(resume); |
| 373 | + call_closure(ctx, clause, &args) |
| 374 | + } |
| 375 | +} |
| 376 | + |
| 377 | +/// A `resume` closure for suspension `seq` of the frame in `block`. |
| 378 | +/// |
| 379 | +/// # Safety |
| 380 | +/// `ctx` must be the running actor's context; `block` a live frame. |
| 381 | +unsafe fn resume_closure(ctx: *mut Ctx, block: Value, seq: i64) -> Value { |
| 382 | + let c = crate::values::tl_closure_alloc(ctx, resume_code_erased(), 2); |
| 383 | + // SAFETY: a fresh closure with two environment fields. |
| 384 | + unsafe { |
| 385 | + let env = Block::fields_ptr(c as *mut Block); |
| 386 | + env.write(dup(block)); |
| 387 | + env.add(1).write(int(seq)); |
| 388 | + } |
| 389 | + c |
| 390 | +} |
| 391 | + |
| 392 | +fn resume_code_erased() -> crate::values::ClosureFn { |
| 393 | + // SAFETY: closure code is stored type-erased and called with the |
| 394 | + // generated-code signature, which `resume_code` has. |
| 395 | + unsafe { |
| 396 | + std::mem::transmute::< |
| 397 | + unsafe extern "C" fn(*mut Ctx, Value, Value, Value, Value, Value, Value) -> Value, |
| 398 | + crate::values::ClosureFn, |
| 399 | + >(resume_code) |
| 400 | + } |
| 401 | +} |
| 402 | + |
| 403 | +/// `resume(x)`: continue the suspended fiber with `x`. |
| 404 | +unsafe extern "C" fn resume_code( |
| 405 | + ctx: *mut Ctx, |
| 406 | + this: Value, |
| 407 | + x: Value, |
| 408 | + _: Value, |
| 409 | + _: Value, |
| 410 | + _: Value, |
| 411 | + _: Value, |
| 412 | +) -> Value { |
| 413 | + // SAFETY: `this` is a resume closure made by `resume_closure`, owned by |
| 414 | + // this call. |
| 415 | + unsafe { |
| 416 | + let env = Block::fields_ptr(this as *mut Block); |
| 417 | + let block = dup(*env); |
| 418 | + let seq = int_get(*env.add(1)); |
| 419 | + drop_value(ctx, this); |
| 420 | + let f = frame(block); |
| 421 | + let result = if f.cancelled { |
| 422 | + drop_value(ctx, x); |
| 423 | + crate::effects::tl_panic_str( |
| 424 | + ctx, |
| 425 | + c"`resume` called after its handler finished".as_ptr(), |
| 426 | + ) |
| 427 | + } else if !f.waiting || f.suspensions != seq { |
| 428 | + drop_value(ctx, x); |
| 429 | + crate::effects::tl_panic_str( |
| 430 | + ctx, |
| 431 | + c"`resume` called twice (continuations are one-shot)".as_ptr(), |
| 432 | + ) |
| 433 | + } else { |
| 434 | + f.waiting = false; |
| 435 | + drive(ctx, block, Resume::Value(x)) |
| 436 | + }; |
| 437 | + drop_value(ctx, block); |
| 438 | + result |
| 439 | + } |
| 440 | +} |