tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

909 lignes · 34707 octetsBrut · Historique
1//! Handlers with `ctl` operations: continuations by stack switching (ADR
2//! 0003, Revision 1; ADR 0010 for routing; ADR 0017 for `multi ctl`).
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 (running its `defer` cleanups),
19//! and every reference it held is dropped (exact Perceus). A `resume`
20//! called after that panics. If a cleanup panics (or the actor is
21//! killed meanwhile), that unwinding continues past the handler.
22//! - **Preemption** inside a fiber is forwarded up to the actor (the
23//! actor's own fiber yields to the scheduler), then back down.
24//!
25//! **Multi-shot** (`tl_handle_multi`, ADR 0017). Each suspension is a
26//! *capture*. The fiber's stack holds at most one capture at a time (its
27//! *occupant*); the others are saved as [`Snapshot`]s and written back at
28//! the same address when resumed, so pointers into the stack stay valid.
29//! - A `resume` whose closure is unique (its last use) runs the capture
30//! itself. Otherwise it runs a copy: a *copying pass* resumes the fiber
31//! with `yielding = CLONE`, so every frame's unwinding code takes one
32//! more reference to what it holds (instead of dropping it) and returns;
33//! then the snapshot is written back, and runs owning those references.
34//! Only generated code, `tl_defer` and `tl_region_exit` may sit on the
35//! fiber between the body and the operation: a `ctl` handler installed
36//! in between (a fiber of its own) makes the capture impossible to copy.
37//! - When the handler finishes, every capture left is released in order:
38//! one never resumed is cancelled (its cleanups run), one resumed before
39//! is discarded (`yielding = DISCARD`: references dropped, cleanups not
40//! run, since its copies ran them).
41//!
42//! **Lifetimes.** A handler's frame lives in a heap block (`TAG_FRAME`)
43//! counted like any value. `tl_handle_ctl` holds one count, and each
44//! `resume` closure holds one. A frame's fiber has always finished, or
45//! been cancelled, before the frame is freed.
46
47use crate::fiber::{Coroutine, CoroutineResult, Snapshot, Stack, Yielder};
48
49use crate::abi::{
50 Block, Ctx, TAG_FRAME, UNIT, Value, YIELD_CANCEL, YIELD_CLONE, YIELD_DISCARD, YIELD_FINAL,
51 YIELD_NONE, int, int_get, is_ptr,
52};
53use crate::heap::{drop_value, dup_value, tl_alloc};
54use crate::prims::call_closure;
55use crate::sched::HANDLER_STACK_SIZE;
56
57pub(crate) enum Resume {
58 Value(Value),
59 Cancel,
60 /// A copying pass (ADR 0017).
61 Clone,
62 /// Release without running cleanups (ADR 0017).
63 Discard,
64}
65
66pub(crate) enum Request {
67 /// An operation for the handler with this marker; the payload is the
68 /// operation's index, then its arguments.
69 Op { marker: u64, payload: Value },
70 /// The actor's reduction budget is spent: yield to the scheduler.
71 Preempt,
72}
73
74pub(crate) type HandlerYielder = Yielder<Resume, Request>;
75type HandlerFiber = Coroutine<Resume, Request, Value>;
76
77/// A handler fiber's yielder and frame. It lives at the bottom of the
78/// fiber's own stack; each actor points at the one of the fiber running
79/// now (null on the actor's own stack). One pointer, so that saving it in
80/// `drive` costs one word.
81pub(crate) struct Running {
82 yielder: *const HandlerYielder,
83 frame: *mut Frame,
84}
85
86struct Frame {
87 marker: u64,
88 fiber: Option<HandlerFiber>,
89 /// Owned: the capability block (clause closures, then the marker).
90 cap: Value,
91 /// Owned: the return clause, or unit.
92 ret: Value,
93 /// Suspensions so far; a `resume` closure belongs to one.
94 suspensions: i64,
95 /// Whether the fiber is suspended waiting for a `resume`.
96 waiting: bool,
97 /// Whether the handler finished while the fiber still waited.
98 cancelled: bool,
99 /// `ctl` handlers installed while this frame's fiber runs, and not
100 /// finished: a capture taken now holds their fibers.
101 nested: u32,
102 /// For an effect with `multi ctl` operations.
103 multi: Option<Multi>,
104}
105
106/// The captures of a multi-shot handler.
107struct Multi {
108 /// Bit `i`: operation `i` is `multi ctl` (the others are `ctl`).
109 ops: u64,
110 captures: Vec<Capture>,
111 /// The capture the fiber's stack holds, suspended at its operation.
112 occupant: Option<usize>,
113 /// The body runs, or waits for another handler (the stack is in use).
114 in_use: bool,
115}
116
117struct Capture {
118 held: Held,
119 /// By a `multi ctl` operation (a `ctl` one is resumed once).
120 multi: bool,
121 resumed: u32,
122 /// Other `ctl` handlers' fibers were active on the stack.
123 holds_fiber: bool,
124}
125
126enum Held {
127 /// In the fiber's stack (the occupant).
128 Live,
129 Saved(Snapshot),
130 /// Resumed for the last time, or released.
131 Gone,
132}
133
134const WORD: usize = size_of::<Value>();
135
136/// # Safety
137/// `block` must be a live frame block.
138unsafe fn frame<'a>(block: Value) -> &'a mut Frame {
139 // SAFETY: caller guarantees a frame block; its raw area holds the box.
140 unsafe {
141 &mut *Block::fields_ptr(block as *mut Block)
142 .cast::<*mut Frame>()
143 .read()
144 }
145}
146
147/// Called when a frame block is freed: release what the frame owns.
148///
149/// # Safety
150/// `b` must be a frame block being freed.
151pub(crate) unsafe fn free_frame(b: *mut Block, pending: &mut Vec<*mut Block>) {
152 // SAFETY: caller guarantees a frame block made by `tl_handle_ctl`; the
153 // box is freed exactly once, here.
154 unsafe {
155 let f = Box::from_raw(Block::fields_ptr(b).cast::<*mut Frame>().read());
156 let Frame {
157 fiber, cap, ret, ..
158 } = *f;
159 if let Some(fiber) = fiber {
160 // Never happens (fibers finish or are cancelled first). A
161 // suspended fiber must not be dropped (its frames never ran
162 // their drops): leak it instead.
163 std::mem::forget(fiber);
164 }
165 crate::heap::release_into(cap, pending);
166 crate::heap::release_into(ret, pending);
167 }
168}
169
170/// # Safety
171/// `ctx` must be the running actor's context.
172unsafe fn current<'a>(ctx: *mut Ctx) -> &'a mut *const Running {
173 // SAFETY: forwarded caller guarantee.
174 unsafe { crate::sched::current_handler(ctx) }
175}
176
177/// Acquire a mapping of the handler size, reusing only that separate pool's
178/// stacks. The existing `Stack::new` sets up the guard page on a pool miss.
179///
180/// # Safety
181/// `ctx` must be the running actor's context.
182unsafe fn acquire_handler_stack(ctx: *mut Ctx) -> Stack {
183 // SAFETY: forwarded caller guarantee.
184 let (_, sched) = unsafe { crate::sched::this(ctx) };
185 sched.take_handler_stack().unwrap_or_else(|| {
186 Stack::new(HANDLER_STACK_SIZE).expect("louise: cannot allocate a handler fiber")
187 })
188}
189
190/// Recycle a returned handler coroutine's mapping into the 16 MiB pool.
191///
192/// # Safety
193/// `ctx` must be the running actor's context. `fiber` must have returned,
194/// and no snapshot may be capable of restoring its old addresses. In
195/// particular, this is called for multi-shot handlers only at final
196/// [`finish`], after all captures have become `Held::Gone`.
197unsafe fn recycle_handler(ctx: *mut Ctx, fiber: HandlerFiber) {
198 let stack = fiber.into_stack();
199 // SAFETY: forwarded caller guarantee; `into_stack` conversion is done
200 // before taking the scheduler lock, and `fiber` cannot be dropped again.
201 let (_, sched) = unsafe { crate::sched::this(ctx) };
202 sched.pool_handler_stack(stack);
203}
204
205/// Run `body` (consumed) under a handler with `ctl` operations, whose
206/// capability `cap` (consumed) holds the clauses and the marker, and whose
207/// return clause is `ret` (consumed; unit if none).
208///
209/// # Safety
210/// `ctx` must be the running actor's context; the values must be owned and
211/// follow the generated-code conventions.
212#[unsafe(no_mangle)]
213pub unsafe extern "C" fn tl_handle_ctl(
214 ctx: *mut Ctx,
215 body: Value,
216 cap: Value,
217 ret: Value,
218 marker: u64,
219) -> Value {
220 // SAFETY: forwarded caller guarantee.
221 unsafe { handle(ctx, body, cap, ret, marker, None) }
222}
223
224/// [`tl_handle_ctl`] for an effect with `multi ctl` operations: bit `i`
225/// of `multi_ops` is set if operation `i` is one.
226///
227/// # Safety
228/// As for [`tl_handle_ctl`].
229#[unsafe(no_mangle)]
230pub unsafe extern "C" fn tl_handle_multi(
231 ctx: *mut Ctx,
232 body: Value,
233 cap: Value,
234 ret: Value,
235 marker: u64,
236 multi_ops: u64,
237) -> Value {
238 // SAFETY: forwarded caller guarantee.
239 unsafe { handle(ctx, body, cap, ret, marker, Some(multi_ops)) }
240}
241
242/// # Safety
243/// As for [`tl_handle_ctl`].
244unsafe fn handle(
245 ctx: *mut Ctx,
246 body: Value,
247 cap: Value,
248 ret: Value,
249 marker: u64,
250 multi_ops: Option<u64>,
251) -> Value {
252 let block = tl_alloc(ctx, TAG_FRAME, 0, WORD) as Value;
253 // SAFETY: caller guarantees a live capability.
254 let body_cap = unsafe { dup_value(cap) };
255 let f = Box::into_raw(Box::new(Frame {
256 marker,
257 fiber: None,
258 cap,
259 ret,
260 suspensions: 0,
261 waiting: false,
262 cancelled: false,
263 nested: 0,
264 multi: multi_ops.map(|ops| Multi {
265 ops,
266 captures: Vec::new(),
267 occupant: None,
268 in_use: true,
269 }),
270 }));
271 let (ctx_addr, frame_addr) = (ctx as usize, f as usize);
272 // SAFETY: `handle`'s caller guarantees the running actor's context.
273 // Acquisition reads that actor's scheduler and cannot suspend; entering
274 // through an outer handler changes its current handler, not its owner.
275 let stack = unsafe { acquire_handler_stack(ctx) };
276 let fiber = HandlerFiber::with_stack(stack, move |yielder: &HandlerYielder, _: Resume| {
277 let ctx = ctx_addr as *mut Ctx;
278 // SAFETY: the fiber runs on the actor that created it.
279 unsafe {
280 let running = Running {
281 yielder,
282 frame: frame_addr as *mut Frame,
283 };
284 *current(ctx) = &running;
285 call_closure(ctx, body, &[body_cap, UNIT])
286 }
287 });
288 // SAFETY: `f` is the fresh frame; the raw area holds its pointer. The
289 // frame whose fiber runs this code (if any) outlives this call.
290 unsafe {
291 (*f).fiber = Some(fiber);
292 Block::fields_ptr(block as *mut Block)
293 .cast::<*mut Frame>()
294 .write(f);
295 let running = *current(ctx);
296 let parent = if running.is_null() {
297 std::ptr::null_mut()
298 } else {
299 (*running).frame
300 };
301 if !parent.is_null() {
302 (*parent).nested += 1;
303 }
304 let mut result = drive(ctx, block, Resume::Value(UNIT));
305 if finish(ctx, block) {
306 drop_value(ctx, result);
307 result = UNIT;
308 }
309 if !parent.is_null() {
310 (*parent).nested -= 1;
311 }
312 drop_value(ctx, block);
313 result
314 }
315}
316
317/// Perform a `ctl` operation of the handler whose capability is `cap`
318/// (borrowed); `payload` (consumed) is the operation's index and
319/// arguments. Returns the value it is resumed with; when cancelled,
320/// returns unit with `yielding = CANCEL` (generated code unwinds).
321///
322/// # Safety
323/// `ctx` must be the running actor's context; `cap` a handler capability.
324#[unsafe(no_mangle)]
325pub unsafe extern "C" fn tl_perform_ctl(ctx: *mut Ctx, cap: Value, payload: Value) -> Value {
326 // SAFETY: caller guarantees a capability block: clauses, then marker.
327 unsafe {
328 let b = cap as *mut Block;
329 let n = (*b).header.scan_fsize as usize;
330 let marker = int_get(*Block::fields_ptr(b).add(n - 1)) as u64;
331 suspend(ctx, Request::Op { marker, payload })
332 }
333}
334
335/// Suspend the current fiber with `request`; the answer, or unit and
336/// `yielding` set (cancelled, or a pass over a multi-shot capture).
337///
338/// # Safety
339/// `ctx` must be the running actor's context.
340unsafe fn suspend(ctx: *mut Ctx, request: Request) -> Value {
341 // SAFETY: forwarded caller guarantee; `current` is the yielder of the
342 // fiber executing this code.
343 unsafe {
344 let y = *current(ctx);
345 if y.is_null() {
346 if let Request::Op { payload, .. } = request {
347 drop_value(ctx, payload);
348 }
349 return crate::effects::tl_panic_str(
350 ctx,
351 c"an operation reached the actor's root without a handler".as_ptr(),
352 );
353 }
354 let answer = (*(*y).yielder).suspend(request);
355 *current(ctx) = y;
356 let mode = match answer {
357 Resume::Value(v) => return v,
358 Resume::Cancel => YIELD_CANCEL,
359 Resume::Clone => YIELD_CLONE,
360 Resume::Discard => YIELD_DISCARD,
361 };
362 (*ctx).yielding = mode;
363 UNIT
364 }
365}
366
367/// Preempt from inside a handler fiber: forward to the parent, up to the
368/// actor's own fiber. Returns false at the actor's root stack.
369///
370/// # Safety
371/// `ctx` must be the running actor's context.
372pub(crate) unsafe fn preempt_in_fiber(ctx: *mut Ctx) -> bool {
373 // SAFETY: forwarded caller guarantee.
374 unsafe {
375 if current(ctx).is_null() {
376 return false;
377 }
378 let v = suspend(ctx, Request::Preempt);
379 drop_value(ctx, v);
380 true
381 }
382}
383
384/// Run the frame's fiber with `input` until it finishes or performs an
385/// operation of this handler; returns the handler's result.
386///
387/// A clause that calls `resume` and then does more work (`x + resume(())`)
388/// nests `resume_code`, `drive` and `call_clause` once per operation, so
389/// `drive`'s frame is paid once per pending `resume`: 100,000 of them in
390/// `tests/bench/effects.lse`. Running the fiber needs a large frame, so it
391/// is out of line ([`run`]), and what nests here is only the call of the
392/// clause. Inlined, with the runtime built as one LTO unit (ADR 0031), it
393/// took 352 bytes of stack per operation instead of 192: twice the page
394/// faults, and `effects` 17% slower.
395///
396/// # Safety
397/// `ctx` must be the running actor's context; `block` a live frame.
398unsafe fn drive(ctx: *mut Ctx, block: Value, input: Resume) -> Value {
399 // SAFETY: forwarded caller guarantee; the frame outlives the call.
400 unsafe {
401 match run(ctx, block, input) {
402 Stop::Done(value) => value,
403 Stop::Clause(payload, resume) => call_clause(ctx, frame(block).cap, payload, resume),
404 }
405 }
406}
407
408/// Where [`run`] left a handler.
409enum Stop {
410 /// Its result.
411 Done(Value),
412 /// The operation in the payload is to be handled by its clause, with
413 /// this `resume` (none for a `final ctl`).
414 Clause(Value, Option<Value>),
415}
416
417/// [`drive`]'s loop: resume the fiber until the handler has a result or
418/// a clause to run.
419///
420/// # Safety
421/// As [`drive`].
422#[inline(never)]
423unsafe fn run(ctx: *mut Ctx, block: Value, mut input: Resume) -> Stop {
424 // SAFETY: caller guarantees a live frame; the fiber runs on this actor.
425 unsafe {
426 loop {
427 let f = frame(block);
428 let Some(mut fiber) = f.fiber.take() else {
429 return Stop::Done(crate::effects::tl_panic_str(
430 ctx,
431 c"`resume` called after its handler finished".as_ptr(),
432 ));
433 };
434 let saved = *current(ctx);
435 let step = fiber.resume(input);
436 *current(ctx) = saved;
437 let f = frame(block);
438 match step {
439 CoroutineResult::Return(value) => {
440 match &mut f.multi {
441 // Kept: saved captures are written back into it.
442 Some(m) => {
443 m.occupant = None;
444 m.in_use = false;
445 f.fiber = Some(fiber);
446 }
447 // One-shot frames own no snapshots, so `Return`
448 // ends both coroutine and stack-address lifetimes.
449 None => recycle_handler(ctx, fiber),
450 }
451 let c = &mut *ctx;
452 if c.yielding == YIELD_FINAL && c.yield_marker == f.marker {
453 let payload = std::mem::replace(&mut c.yield_value, UNIT);
454 c.yielding = YIELD_NONE;
455 return Stop::Clause(payload, None);
456 }
457 if c.yielding != YIELD_NONE {
458 return Stop::Done(UNIT); // unwinding continues in the caller
459 }
460 if is_ptr(f.ret) {
461 return Stop::Done(call_closure(ctx, dup_value(f.ret), &[value]));
462 }
463 return Stop::Done(value);
464 }
465 CoroutineResult::Yield(request) => {
466 f.fiber = Some(fiber);
467 match request {
468 Request::Preempt => {
469 if !preempt_in_fiber(ctx) {
470 crate::sched::preempt_root(ctx);
471 }
472 input = Resume::Value(UNIT);
473 }
474 Request::Op { marker, payload } if marker == f.marker => {
475 let resume = if f.multi.is_some() {
476 capture(ctx, block, payload)
477 } else {
478 f.suspensions += 1;
479 f.waiting = true;
480 resume_closure(ctx, block, f.suspensions, resume_code)
481 };
482 return Stop::Clause(payload, Some(resume));
483 }
484 Request::Op { marker, payload } => {
485 // Not ours: ask the handlers around this one.
486 let answer = suspend(ctx, Request::Op { marker, payload });
487 input = if (*ctx).yielding == YIELD_CANCEL {
488 Resume::Cancel
489 } else {
490 Resume::Value(answer)
491 };
492 if let Resume::Cancel = input {
493 // The fiber around us is being cancelled:
494 // cancel ours, then keep unwinding (or
495 // unwind as a cleanup of ours did).
496 (*ctx).yielding = YIELD_NONE;
497 if !finish(ctx, block) {
498 (*ctx).yielding = YIELD_CANCEL;
499 }
500 return Stop::Done(UNIT);
501 }
502 }
503 }
504 }
505 }
506 }
507 }
508}
509
510/// A multi-shot handler's fiber suspended at one of its operations (in
511/// `payload`, borrowed): record the capture; returns its `resume`
512/// closure. Out of line, so that `drive`
513/// keeps the stack frame it had for one-shot handlers (nested `resume`s
514/// recurse through it).
515///
516/// # Safety
517/// `ctx` must be the running actor's context; `block` a live multi frame.
518#[inline(never)]
519unsafe fn capture(ctx: *mut Ctx, block: Value, payload: Value) -> Value {
520 // SAFETY: forwarded caller guarantee; the payload starts with the
521 // operation's index.
522 unsafe {
523 let f = frame(block);
524 let holds_fiber = f.nested > 0;
525 let m = f.multi.as_mut().expect("multi");
526 let op = int_get(*Block::fields_ptr(payload as *mut Block)) as u32;
527 let multi = op < 64 && m.ops & (1 << op) != 0;
528 m.captures.push(Capture {
529 held: Held::Live,
530 multi,
531 resumed: 0,
532 holds_fiber,
533 });
534 let index = m.captures.len() - 1;
535 m.occupant = Some(index);
536 m.in_use = false;
537 resume_closure(ctx, block, index as i64, multi_resume_code)
538 }
539}
540
541/// The handler is done: cancel the suspended body (one-shot), or release
542/// every capture left (multi-shot; see the module documentation). Returns
543/// whether the released code started an unwinding of its own, which then
544/// replaces the caller's.
545///
546/// # Safety
547/// `ctx` must be the running actor's context; `block` a live frame.
548#[inline(never)]
549unsafe fn finish(ctx: *mut Ctx, block: Value) -> bool {
550 // SAFETY: caller guarantees a live frame on this actor.
551 unsafe {
552 let f = frame(block);
553 let Some(m) = &mut f.multi else {
554 f.waiting = false;
555 if f.fiber.is_some() {
556 f.cancelled = true;
557 }
558 return run_out(ctx, block, Resume::Cancel);
559 };
560 let mut started = false;
561 // A computation suspended in another handler's operation (the code
562 // around this handler is being cancelled) unwinds first.
563 if m.in_use && f.fiber.is_some() {
564 m.in_use = false;
565 started |= run_out(ctx, block, Resume::Cancel);
566 }
567 let mut index = 0;
568 loop {
569 let f = frame(block);
570 let m = f.multi.as_mut().expect("multi");
571 let Some(capture) = m.captures.get(index) else {
572 break;
573 };
574 if !matches!(capture.held, Held::Gone) {
575 let mode = if capture.resumed == 0 {
576 Resume::Cancel
577 } else {
578 Resume::Discard
579 };
580 materialize(f, index);
581 let m = f.multi.as_mut().expect("multi");
582 m.captures[index].held = Held::Gone;
583 m.occupant = None;
584 started |= run_out(ctx, block, mode);
585 }
586 index += 1;
587 }
588 let f = frame(block);
589 // Late resume closures now stop before `run`. All non-`Gone`
590 // captures were materialised and driven to `Return` above, so no
591 // snapshot can subsequently restore this mapping's addresses.
592 f.cancelled = true;
593 let m = f.multi.as_ref().expect("multi");
594 debug_assert!(m.occupant.is_none(), "louise: live multi capture at finish");
595 debug_assert!(
596 m.captures.iter().all(|c| matches!(c.held, Held::Gone)),
597 "louise: saved multi capture at finish"
598 );
599 if let Some(fiber) = f.fiber.take() {
600 recycle_handler(ctx, fiber);
601 }
602 started
603 }
604}
605
606/// If the frame's fiber is suspended, resume it with `mode` (cancel or
607/// discard) so it unwinds (dropping what it holds; when cancelled, running
608/// its cleanups) and finishes. The unwinding state of the caller is
609/// preserved, unless the code started an unwinding of its own (a cleanup
610/// panicked, or the actor was killed): that one replaces it, and this
611/// returns true.
612///
613/// # Safety
614/// `ctx` must be the running actor's context; `block` a live frame.
615#[inline(never)]
616unsafe fn run_out(ctx: *mut Ctx, block: Value, mode: Resume) -> bool {
617 // SAFETY: caller guarantees a live frame on this actor.
618 unsafe {
619 let f = frame(block);
620 let Some(mut fiber) = f.fiber.take() else {
621 return false;
622 };
623 let keep = f.multi.is_some();
624 let flag = match mode {
625 Resume::Discard => YIELD_DISCARD,
626 _ => YIELD_CANCEL,
627 };
628 let c = &mut *ctx;
629 let saved = (
630 c.yielding,
631 c.yield_marker,
632 std::mem::replace(&mut c.yield_value, UNIT),
633 );
634 c.yielding = YIELD_NONE;
635 let outer = *current(ctx);
636 let mut input = mode;
637 loop {
638 match fiber.resume(input) {
639 CoroutineResult::Return(value) => {
640 drop_value(ctx, value);
641 break;
642 }
643 // Cancelled code can still preempt (or, in a clause run
644 // while unwinding, perform): keep it going.
645 CoroutineResult::Yield(Request::Preempt) => {
646 *current(ctx) = outer;
647 if !preempt_in_fiber(ctx) {
648 crate::sched::preempt_root(ctx);
649 }
650 input = Resume::Value(UNIT);
651 }
652 CoroutineResult::Yield(Request::Op { payload, .. }) => {
653 drop_value(ctx, payload);
654 input = Resume::Cancel;
655 }
656 }
657 }
658 *current(ctx) = outer;
659 if keep {
660 frame(block).fiber = Some(fiber);
661 } else {
662 // A suspended one-shot body is not finished merely because its
663 // handle ended. Reclaim only now, after this cancellation
664 // drive reached `Return`; both ordinary and already-unwinding
665 // exits below therefore retain the same reclamation path.
666 recycle_handler(ctx, fiber);
667 }
668 let c = &mut *ctx;
669 if c.yielding != YIELD_NONE && c.yielding != flag {
670 drop_value(ctx, saved.2);
671 return true;
672 }
673 drop_value(ctx, std::mem::replace(&mut c.yield_value, saved.2));
674 c.yielding = saved.0;
675 c.yield_marker = saved.1;
676 false
677 }
678}
679
680/// Make capture `index` the one the fiber's stack holds, saving the
681/// occupant first. Returns a copy of what the stack now holds, if it had to
682/// be written back (the saved capture).
683#[inline(never)]
684fn materialize(f: &mut Frame, index: usize) -> Option<Snapshot> {
685 let fiber = f
686 .fiber
687 .as_mut()
688 .expect("louise: a multi-shot handler keeps its fiber");
689 let m = f.multi.as_mut().expect("multi");
690 if m.occupant == Some(index) {
691 return None;
692 }
693 if let Some(occupant) = m.occupant.take() {
694 m.captures[occupant].held = Held::Saved(fiber.snapshot());
695 }
696 let Held::Saved(snap) = std::mem::replace(&mut m.captures[index].held, Held::Live) else {
697 unreachable!("louise: a capture that is neither held nor saved");
698 };
699 fiber.restore(&snap);
700 m.occupant = Some(index);
701 Some(snap)
702}
703
704/// Call the clause of `cap` for the operation in `payload` (consumed):
705/// its arguments, then `resume` if given.
706///
707/// # Safety
708/// `ctx` must be the running actor's context; `cap` a live capability.
709unsafe fn call_clause(ctx: *mut Ctx, cap: Value, payload: Value, resume: Option<Value>) -> Value {
710 // SAFETY: caller guarantees a capability and a payload block.
711 unsafe {
712 let p = payload as *mut Block;
713 let n = (*p).header.scan_fsize as usize;
714 let fields = Block::fields_ptr(p);
715 let op = int_get(*fields) as usize;
716 let clause = dup_value(*Block::fields_ptr(cap as *mut Block).add(op));
717 // The generated-code convention, without a vector: the call is the
718 // last thing done, so it can reuse this frame (a clause calling
719 // `resume` nests this code once per operation).
720 let mut regs = [UNIT; 5];
721 let args = (1..n).map(|i| dup_value(*fields.add(i))).chain(resume);
722 for (i, a) in args.enumerate() {
723 if i < 5 {
724 regs[i] = a;
725 } else {
726 *(*ctx).xargs.add(i - 5) = a;
727 }
728 }
729 drop_value(ctx, payload);
730 let code: ResumeCode = std::mem::transmute(crate::values::closure_code(clause));
731 code(ctx, clause, regs[0], regs[1], regs[2], regs[3], regs[4])
732 }
733}
734
735type ResumeCode = unsafe extern "C" fn(*mut Ctx, Value, Value, Value, Value, Value, Value) -> Value;
736
737/// A `resume` closure running `code`, for suspension `seq` of the frame in
738/// `block`.
739///
740/// # Safety
741/// `ctx` must be the running actor's context; `block` a live frame.
742unsafe fn resume_closure(ctx: *mut Ctx, block: Value, seq: i64, code: ResumeCode) -> Value {
743 // SAFETY: closure code is stored type-erased and called with the
744 // generated-code signature, which `code` has. The borrowed entry
745 // (ADR 0068) is the one-argument adapter: `resume(x)` takes one.
746 let erased = unsafe { std::mem::transmute::<ResumeCode, crate::values::ClosureFn>(code) };
747 // SAFETY: same erasure; `tl_borrowed1` has the generated-code
748 // signature.
749 let erased_borrowed = unsafe {
750 std::mem::transmute::<ResumeCode, crate::values::ClosureFn>(crate::values::tl_borrowed1)
751 };
752 let c = crate::values::tl_closure_alloc(ctx, erased, erased_borrowed, 2);
753 // SAFETY: a fresh closure with two environment fields.
754 unsafe {
755 let env = Block::fields_ptr(c as *mut Block);
756 env.write(dup_value(block));
757 env.add(1).write(int(seq));
758 }
759 c
760}
761
762/// `resume(x)` of a one-shot handler: continue the suspended fiber with
763/// `x`.
764unsafe extern "C" fn resume_code(
765 ctx: *mut Ctx,
766 this: Value,
767 x: Value,
768 _: Value,
769 _: Value,
770 _: Value,
771 _: Value,
772) -> Value {
773 // SAFETY: `this` is a resume closure made by `resume_closure`, owned by
774 // this call.
775 unsafe {
776 let env = Block::fields_ptr(this as *mut Block);
777 let block = *env;
778 let seq = int_get(*env.add(1));
779 let f = frame(block);
780 let message = if f.cancelled {
781 c"`resume` called after its handler finished"
782 } else if !f.waiting || f.suspensions != seq {
783 c"`resume` called twice (continuations are one-shot)"
784 } else {
785 // The fiber waits, so the handler has not finished: its
786 // `tl_handle_ctl` keeps the frame alive while `drive` runs, and
787 // this closure can go first, leaving `drive` the last call.
788 f.waiting = false;
789 drop_value(ctx, this);
790 return drive(ctx, block, Resume::Value(x));
791 };
792 drop_value(ctx, this);
793 drop_value(ctx, x);
794 crate::effects::tl_panic_str(ctx, message.as_ptr())
795 }
796}
797
798/// `resume(x)` of a multi-shot handler's capture: run it (its last use),
799/// or a copy of it, with `x`.
800unsafe extern "C" fn multi_resume_code(
801 ctx: *mut Ctx,
802 this: Value,
803 x: Value,
804 _: Value,
805 _: Value,
806 _: Value,
807 _: Value,
808) -> Value {
809 // SAFETY: `this` is a resume closure made by `resume_closure`, owned by
810 // this call; its frame is live while it holds it.
811 unsafe {
812 let env = Block::fields_ptr(this as *mut Block);
813 let block = *env;
814 let index = int_get(*env.add(1)) as usize;
815 let last_use = crate::heap::rc(this as *mut Block) == 1;
816 let prepared = prepare(ctx, block, index, last_use);
817 // As in `resume_code`: once prepared, the handler is running, and
818 // its `tl_handle_multi` keeps the frame alive.
819 drop_value(ctx, this);
820 match prepared {
821 Ok(()) => drive(ctx, block, Resume::Value(x)),
822 Err(message) => {
823 drop_value(ctx, x);
824 crate::effects::tl_panic_str(ctx, message.as_ptr())
825 }
826 }
827 }
828}
829
830/// Check that capture `index` can be resumed (in the interpreter's order
831/// of checks), and leave in the fiber's stack what is to run: the capture
832/// itself on its last use, otherwise a copy owning references of its own.
833///
834/// # Safety
835/// `ctx` must be the running actor's context; `block` a live multi frame.
836#[inline(never)]
837unsafe fn prepare(
838 ctx: *mut Ctx,
839 block: Value,
840 index: usize,
841 last_use: bool,
842) -> Result<(), &'static std::ffi::CStr> {
843 // SAFETY: forwarded caller guarantee.
844 unsafe {
845 let f = frame(block);
846 if f.cancelled {
847 return Err(c"`resume` called after its handler finished");
848 }
849 let m = f.multi.as_mut().expect("multi");
850 if m.in_use {
851 return Err(c"`resume` called while its handler's body is running");
852 }
853 let capture = &m.captures[index];
854 let copy = capture.multi && !last_use;
855 if capture.multi && capture.holds_fiber {
856 return Err(c"a `multi ctl` continuation holding a `ctl` handler cannot be resumed");
857 }
858 if matches!(capture.held, Held::Gone) {
859 return Err(c"`resume` called twice (continuations are one-shot)");
860 }
861 let kept = materialize(f, index);
862 let m = f.multi.as_mut().expect("multi");
863 if copy {
864 let fiber = f.fiber.as_mut().expect("fiber");
865 let snap = kept.unwrap_or_else(|| fiber.snapshot());
866 copying_pass(ctx, fiber);
867 fiber.restore(&snap);
868 m.captures[index].held = Held::Saved(snap);
869 } else {
870 m.captures[index].held = Held::Gone;
871 }
872 m.occupant = None;
873 m.captures[index].resumed += 1;
874 m.in_use = true;
875 Ok(())
876 }
877}
878
879/// Resume the suspended `fiber` with `yielding = CLONE`: its frames take one
880/// more reference to everything they hold and return, so it finishes. The
881/// caller's unwinding state is preserved.
882///
883/// # Safety
884/// `ctx` must be the running actor's context; `fiber` suspended at a
885/// multi-shot capture without other handler fibers in it.
886#[inline(never)]
887unsafe fn copying_pass(ctx: *mut Ctx, fiber: &mut HandlerFiber) {
888 // SAFETY: forwarded caller guarantee.
889 unsafe {
890 let c = &mut *ctx;
891 let saved = (
892 c.yielding,
893 c.yield_marker,
894 std::mem::replace(&mut c.yield_value, UNIT),
895 );
896 c.yielding = YIELD_NONE;
897 let outer = *current(ctx);
898 match fiber.resume(Resume::Clone) {
899 CoroutineResult::Return(value) => drop_value(ctx, value),
900 CoroutineResult::Yield(_) => panic!("louise: a copying pass suspended"),
901 }
902 *current(ctx) = outer;
903 let c = &mut *ctx;
904 debug_assert_eq!(c.yielding, YIELD_CLONE, "louise: a copying pass unwound");
905 c.yielding = saved.0;
906 c.yield_marker = saved.1;
907 c.yield_value = saved.2;
908 }
909}