| @@ -1,17 +1,30 @@ |
| 1 | | −//! Actors and the scheduler (ABI v0 spike scope). |
| 1 | +//! Actors and the scheduler (ADR 0004; M6 native part 1). |
| 2 | 2 | //! |
| 3 | | −//! M0 scope: one scheduler thread, round-robin run queue, reduction-based |
| 4 | | −//! preemption, and kill-by-unwinding. Mailboxes, links, monitors, timers and |
| 5 | | −//! multiple scheduler threads arrive in M6 (docs/adr/0004-actor-model.md). |
| 3 | +//! The semantics are the interpreter's (`tilc_core::sched`), so compiled |
| 4 | +//! programs print exactly what interpreted ones do: |
| 5 | +//! - one scheduler thread, round-robin run queue; |
| 6 | +//! - an actor is preempted after [`REDUCTIONS`] function entries, and gets |
| 7 | +//! a fresh budget whenever it is scheduled or performs a `proc` |
| 8 | +//! operation (each of which is a scheduling point in the interpreter); |
| 9 | +//! - spawned actors run after their parent's current slice; |
| 10 | +//! - time is virtual: when no actor can run, the clock jumps to the next |
| 11 | +//! deadline, and due actors wake in pid order; |
| 12 | +//! - exits follow Erlang. An abnormal exit stops linked actors, or sends |
| 13 | +//! them an `ExitSignal` if they trap exits; monitors receive `Down`; |
| 14 | +//! - when `main` stops, the other actors are stopped. |
| 6 | 15 | //! |
| 7 | | −//! Invariants: |
| 8 | | −//! - Each actor runs on its own fiber and owns its `Ctx`; generated code |
| 9 | | −//! reaches runtime state only through `ctx.rt`. |
| 10 | | −//! - The scheduler state is borrowed only while no actor is running, so |
| 11 | | −//! runtime calls made by an actor (spawn, kill) can borrow it themselves. |
| 12 | | −//! - A fiber is never dropped while suspended: corosensei would force-unwind |
| 13 | | −//! it through C frames. Actors always run to completion, killed ones by |
| 14 | | −//! yield-unwinding, which also releases everything they own. |
| 16 | +//! **Logical exit and unwinding are separate.** An actor exits (monitors |
| 17 | +//! and links are notified) the moment it is killed, as in the interpreter. |
| 18 | +//! Its fiber then runs once more to unwind, dropping everything it holds. |
| 19 | +//! A fiber is never dropped while suspended, because corosensei would |
| 20 | +//! force-unwind C frames. |
| 21 | +//! |
| 22 | +//! **Single thread.** Messages are moved, not copied, because all actors |
| 23 | +//! share one heap and one thread. The multi-threaded scheduler (ADR 0004, |
| 24 | +//! Revision 1) adds move/share/copy sending. |
| 25 | +//! |
| 26 | +//! Invariant: the scheduler state is borrowed only while no actor code |
| 27 | +//! runs, or within one runtime call made by an actor. |
| 15 | 28 | |
| 16 | 29 | use std::cell::RefCell; |
| 17 | 30 | use std::collections::{HashMap, VecDeque}; |
| @@ -26,21 +39,21 @@ use crate::abi::{ |
| 26 | 39 | use crate::heap::{DropStack, drop_value}; |
| 27 | 40 | use crate::values::{closure_code, string_bytes}; |
| 28 | 41 | |
| 29 | | −/// Reductions an actor may spend before yielding (same budget as the BEAM). |
| 30 | | −const REDUCTIONS: i32 = 4000; |
| 42 | +/// Function entries an actor may make before it yields (the interpreter |
| 43 | +/// counts calls the same way). |
| 44 | +pub(crate) const REDUCTIONS: i32 = 2000; |
| 31 | 45 | /// Virtual size of an actor stack (plus a guard page from corosensei). |
| 32 | 46 | const STACK_SIZE: usize = 256 * 1024; |
| 33 | | −/// The root actor (`main`) gets a large stack, committed lazily: native |
| 34 | | −/// programs recurse as deeply as interpreted ones (non-tail recursion over |
| 35 | | −/// long lists). |
| 47 | +/// Compiled actors get larger stacks (committed lazily), so native |
| 48 | +/// recursion depth matches the interpreter's. |
| 49 | +const PROGRAM_STACK_SIZE: usize = 64 << 20; |
| 50 | +/// The root actor (`main`). |
| 36 | 51 | const ROOT_STACK_SIZE: usize = 1 << 30; |
| 37 | 52 | |
| 38 | 53 | static LIVE_ACTORS: AtomicI64 = AtomicI64::new(0); |
| 39 | | −/// Set by `tl_main_program`: the root actor's crash is reported by it, as |
| 40 | | −/// `tilc run` reports a panic. |
| 54 | +/// Set by `tl_main_program`: the root's crash is reported by it, as |
| 55 | +/// `tilc run` reports a panic; other crashes as the interpreter does. |
| 41 | 56 | static PROGRAM_MODE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); |
| 42 | | −/// The first actor spawned is the root. |
| 43 | | −const ROOT_PID: i64 = 1; |
| 44 | 57 | |
| 45 | 58 | type EntryFn = unsafe extern "C" fn(*mut Ctx) -> Value; |
| 46 | 59 | type ActorClosureFn = unsafe extern "C" fn(*mut Ctx, Value) -> Value; |
| @@ -48,23 +61,34 @@ type Fiber = Coroutine<(), (), (), DefaultStack>; |
| 48 | 61 | |
| 49 | 62 | enum Body { |
| 50 | 63 | Entry(EntryFn), |
| 51 | | − /// Owned closure called as `code(ctx, self)`. |
| 64 | + /// Owned closure called as `code(ctx, self)` (the M0 spike's actors). |
| 52 | 65 | Closure(Value), |
| 66 | + /// Owned closure of a compiled program, called with the actor's root |
| 67 | + /// capability (`fn() -> () / <proc, io>`). |
| 68 | + Program(Value), |
| 53 | 69 | } |
| 54 | 70 | |
| 55 | | −#[derive(Debug, PartialEq)] |
| 56 | | −enum Exit { |
| 71 | +/// Why an actor stopped. |
| 72 | +#[derive(Clone, Debug, PartialEq)] |
| 73 | +pub(crate) enum Exit { |
| 57 | 74 | Running, |
| 58 | 75 | Normal, |
| 59 | 76 | Killed, |
| 60 | 77 | Crashed(String), |
| 61 | 78 | } |
| 62 | 79 | |
| 80 | +#[derive(Clone, Copy, PartialEq)] |
| 81 | +pub(crate) enum Wait { |
| 82 | + Ready, |
| 83 | + Receive { tag: i64, deadline: Option<u64> }, |
| 84 | + Sleep { deadline: u64 }, |
| 85 | +} |
| 86 | + |
| 63 | 87 | pub struct Actor { |
| 64 | 88 | ctx: Ctx, |
| 65 | | − pid: i64, |
| 89 | + pub(crate) pid: i64, |
| 66 | 90 | next_marker: u64, |
| 67 | | − kill_requested: bool, |
| 91 | + pub(crate) kill_requested: bool, |
| 68 | 92 | exit: Exit, |
| 69 | 93 | drops: DropStack, |
| 70 | 94 | yielder: *const Yielder<(), ()>, |
| @@ -72,15 +96,16 @@ pub struct Actor { |
| 72 | 96 | /// stack (see `handlers`). |
| 73 | 97 | handler: *const crate::handlers::HandlerYielder, |
| 74 | 98 | sched: *const RefCell<Sched>, |
| 75 | | −} |
| 76 | | − |
| 77 | | −/// # Safety |
| 78 | | −/// `ctx` must be the running actor's context. |
| 79 | | −pub(crate) unsafe fn current_handler<'a>( |
| 80 | | − ctx: *mut Ctx, |
| 81 | | −) -> &'a mut *const crate::handlers::HandlerYielder { |
| 82 | | − // SAFETY: forwarded caller guarantee. |
| 83 | | − unsafe { &mut (*actor(ctx)).handler } |
| 99 | + // OTP state (see `process`). |
| 100 | + pub(crate) mailbox: VecDeque<(i64, Value)>, |
| 101 | + pub(crate) wait: Wait, |
| 102 | + /// What a parked operation returns when woken. |
| 103 | + pub(crate) wake: Value, |
| 104 | + pub(crate) links: Vec<i64>, |
| 105 | + pub(crate) trap: bool, |
| 106 | + pub(crate) exits_tag: Option<i64>, |
| 107 | + /// Exited (logically); its fiber may still have to unwind. |
| 108 | + pub(crate) dead: bool, |
| 84 | 109 | } |
| 85 | 110 | |
| 86 | 111 | struct Slot { |
| @@ -90,10 +115,16 @@ struct Slot { |
| 90 | 115 | } |
| 91 | 116 | |
| 92 | 117 | #[derive(Default)] |
| 93 | | −struct Sched { |
| 118 | +pub(crate) struct Sched { |
| 94 | 119 | actors: HashMap<i64, Slot>, |
| 95 | 120 | run_queue: VecDeque<i64>, |
| 96 | 121 | next_pid: i64, |
| 122 | + pub(crate) next_tag: i64, |
| 123 | + pub(crate) clock: u64, |
| 124 | + /// (watched, watcher, tag) |
| 125 | + pub(crate) monitors: Vec<(i64, i64, i64)>, |
| 126 | + root: i64, |
| 127 | + outcome: Option<Exit>, |
| 97 | 128 | } |
| 98 | 129 | |
| 99 | 130 | /// # Safety |
| @@ -104,6 +135,15 @@ unsafe fn actor(ctx: *mut Ctx) -> *mut Actor { |
| 104 | 135 | } |
| 105 | 136 | |
| 106 | 137 | /// # Safety |
| 138 | +/// `ctx` must be the running actor's context. |
| 139 | +pub(crate) unsafe fn current_handler<'a>( |
| 140 | + ctx: *mut Ctx, |
| 141 | +) -> &'a mut *const crate::handlers::HandlerYielder { |
| 142 | + // SAFETY: forwarded caller guarantee. |
| 143 | + unsafe { &mut (*actor(ctx)).handler } |
| 144 | +} |
| 145 | + |
| 146 | +/// # Safety |
| 107 | 147 | /// `ctx` must be the running actor's context. The returned borrow must not |
| 108 | 148 | /// outlive the current runtime call. |
| 109 | 149 | pub(crate) unsafe fn drop_stack<'a>(ctx: *mut Ctx) -> &'a mut DropStack { |
| @@ -122,10 +162,51 @@ pub(crate) unsafe fn next_marker(ctx: *mut Ctx) -> u64 { |
| 122 | 162 | } |
| 123 | 163 | } |
| 124 | 164 | |
| 165 | +/// The running actor and the scheduler. |
| 166 | +/// |
| 167 | +/// # Safety |
| 168 | +/// `ctx` must be the running actor's context; the references must not |
| 169 | +/// outlive the current runtime call. |
| 170 | +pub(crate) unsafe fn this<'a>(ctx: *mut Ctx) -> (&'a mut Actor, &'a RefCell<Sched>) { |
| 171 | + // SAFETY: forwarded caller guarantee. |
| 172 | + unsafe { |
| 173 | + let a = actor(ctx); |
| 174 | + (&mut *a, &*(*a).sched) |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +/// Actor `pid`, if its fiber has not finished. |
| 179 | +pub(crate) fn actor_of<'a>(s: &Sched, pid: i64) -> Option<&'a mut Actor> { |
| 180 | + // SAFETY: slots only hold live actors; callers do not keep the |
| 181 | + // reference across scheduling points. |
| 182 | + s.actors.get(&pid).map(|slot| unsafe { &mut *slot.actor }) |
| 183 | +} |
| 184 | + |
| 185 | +impl Sched { |
| 186 | + pub(crate) fn tag(&mut self) -> i64 { |
| 187 | + self.next_tag += 1; |
| 188 | + self.next_tag |
| 189 | + } |
| 190 | + |
| 191 | + /// Make a parked actor runnable; its operation returns `wake`. |
| 192 | + pub(crate) fn wake(&mut self, pid: i64, wake: Value) { |
| 193 | + if let Some(a) = actor_of(self, pid) { |
| 194 | + a.wait = Wait::Ready; |
| 195 | + a.wake = wake; |
| 196 | + self.run_queue.push_back(pid); |
| 197 | + } |
| 198 | + } |
| 199 | + |
| 200 | + /// Whether `pid` is alive (not exited). |
| 201 | + pub(crate) fn exists(&self, pid: i64) -> bool { |
| 202 | + actor_of(self, pid).is_some_and(|a| !a.dead) |
| 203 | + } |
| 204 | +} |
| 205 | + |
| 125 | 206 | fn spawn_actor(sched: &RefCell<Sched>, body: Body, stack_size: usize) -> i64 { |
| 126 | 207 | let mut s = sched.borrow_mut(); |
| 127 | | − s.next_pid += 1; |
| 128 | 208 | let pid = s.next_pid; |
| 209 | + s.next_pid += 1; |
| 129 | 210 | let a = Box::into_raw(Box::new(Actor { |
| 130 | 211 | ctx: Ctx { |
| 131 | 212 | yielding: YIELD_NONE, |
| @@ -144,6 +225,13 @@ fn spawn_actor(sched: &RefCell<Sched>, body: Body, stack_size: usize) -> i64 { |
| 144 | 225 | yielder: std::ptr::null(), |
| 145 | 226 | handler: std::ptr::null(), |
| 146 | 227 | sched, |
| 228 | + mailbox: VecDeque::new(), |
| 229 | + wait: Wait::Ready, |
| 230 | + wake: UNIT, |
| 231 | + links: Vec::new(), |
| 232 | + trap: false, |
| 233 | + exits_tag: None, |
| 234 | + dead: false, |
| 147 | 235 | })); |
| 148 | 236 | // SAFETY: `a` is a fresh allocation; `rt` points back at it. |
| 149 | 237 | unsafe { (*a).ctx.rt = a.cast() }; |
| @@ -167,6 +255,16 @@ fn spawn_actor(sched: &RefCell<Sched>, body: Body, stack_size: usize) -> i64 { |
| 167 | 255 | pid |
| 168 | 256 | } |
| 169 | 257 | |
| 258 | +/// Spawn a compiled program's actor running `body` (consumed). |
| 259 | +/// |
| 260 | +/// # Safety |
| 261 | +/// `ctx` must be the running actor's context. |
| 262 | +pub(crate) unsafe fn spawn_program(ctx: *mut Ctx, body: Value) -> i64 { |
| 263 | + // SAFETY: forwarded caller guarantee. |
| 264 | + let (_, sched) = unsafe { this(ctx) }; |
| 265 | + spawn_actor(sched, Body::Program(body), PROGRAM_STACK_SIZE) |
| 266 | +} |
| 267 | + |
| 170 | 268 | /// Run an actor's body to completion and record why it exited. |
| 171 | 269 | /// |
| 172 | 270 | /// # Safety |
| @@ -176,10 +274,12 @@ unsafe fn run_body(a: *mut Actor, body: Body) { |
| 176 | 274 | unsafe { |
| 177 | 275 | let ctx = &raw mut (*a).ctx; |
| 178 | 276 | let result = match body { |
| 277 | + Body::Closure(clo) | Body::Program(clo) if (*a).kill_requested => { |
| 278 | + drop_value(ctx, clo); |
| 279 | + (*ctx).yielding = YIELD_KILL; |
| 280 | + UNIT |
| 281 | + } |
| 179 | 282 | _ if (*a).kill_requested => { |
| 180 | | − if let Body::Closure(clo) = body { |
| 181 | | − drop_value(ctx, clo); |
| 182 | | − } |
| 183 | 283 | (*ctx).yielding = YIELD_KILL; |
| 184 | 284 | UNIT |
| 185 | 285 | } |
| @@ -188,10 +288,14 @@ unsafe fn run_body(a: *mut Actor, body: Body) { |
| 188 | 288 | let code: ActorClosureFn = std::mem::transmute(closure_code(clo)); |
| 189 | 289 | code(ctx, clo) |
| 190 | 290 | } |
| 291 | + Body::Program(clo) => { |
| 292 | + let cap = crate::process::root_cap(ctx); |
| 293 | + crate::prims::call_closure(ctx, clo, &[cap]) |
| 294 | + } |
| 191 | 295 | }; |
| 192 | 296 | // While unwinding, generated code returns unit, so this is a no-op then. |
| 193 | 297 | drop_value(ctx, result); |
| 194 | | − (*a).exit = match (*ctx).yielding { |
| 298 | + let reason = match (*ctx).yielding { |
| 195 | 299 | YIELD_NONE => Exit::Normal, |
| 196 | 300 | YIELD_KILL => Exit::Killed, |
| 197 | 301 | YIELD_PANIC => Exit::Crashed( |
| @@ -202,40 +306,122 @@ unsafe fn run_body(a: *mut Actor, body: Body) { |
| 202 | 306 | }; |
| 203 | 307 | drop_value(ctx, std::mem::replace(&mut (*ctx).yield_value, UNIT)); |
| 204 | 308 | (*ctx).yielding = YIELD_NONE; |
| 205 | | − if let Exit::Crashed(reason) = &(*a).exit |
| 206 | | − && !((*a).pid == ROOT_PID && PROGRAM_MODE.load(Ordering::Relaxed)) |
| 207 | | − { |
| 208 | | − eprintln!("tilrt: actor {} crashed: {reason}", (*a).pid); |
| 309 | + let sched = &*(*a).sched; |
| 310 | + exit_actor(sched, (*a).pid, reason); |
| 311 | + // Release what the actor still owns. |
| 312 | + for (_, message) in std::mem::take(&mut (*a).mailbox) { |
| 313 | + drop_value(ctx, message); |
| 209 | 314 | } |
| 315 | + drop_value(ctx, std::mem::replace(&mut (*a).wake, UNIT)); |
| 210 | 316 | } |
| 211 | 317 | } |
| 212 | 318 | |
| 213 | | −/// Run until no actor is left. When `root` exits, every other actor is |
| 214 | | −/// killed (and unwound). Returns the root actor's exit. |
| 319 | +/// Stop `pid` (logically): record its exit, notify monitors, propagate |
| 320 | +/// through links, and make sure its fiber unwinds. |
| 321 | +pub(crate) fn exit_actor(sched: &RefCell<Sched>, pid: i64, reason: Exit) { |
| 322 | + let links = { |
| 323 | + let mut s = sched.borrow_mut(); |
| 324 | + let Some(a) = actor_of(&s, pid) else { |
| 325 | + return; |
| 326 | + }; |
| 327 | + if a.dead { |
| 328 | + return; |
| 329 | + } |
| 330 | + a.dead = true; |
| 331 | + a.exit = reason.clone(); |
| 332 | + if pid == s.root && s.outcome.is_none() { |
| 333 | + s.outcome = Some(reason.clone()); |
| 334 | + } |
| 335 | + if let Exit::Crashed(m) = &reason { |
| 336 | + let program = PROGRAM_MODE.load(Ordering::Relaxed); |
| 337 | + if !(program && pid == s.root) { |
| 338 | + let prefix = if program { "" } else { "tilrt: " }; |
| 339 | + eprintln!("{prefix}actor {pid} crashed: {m}"); |
| 340 | + } |
| 341 | + } |
| 342 | + // Its fiber unwinds the next time it runs. |
| 343 | + a.kill_requested = true; |
| 344 | + if a.wait != Wait::Ready { |
| 345 | + s.wake(pid, UNIT); |
| 346 | + } |
| 347 | + std::mem::take(&mut a.links) |
| 348 | + }; |
| 349 | + let fired: Vec<(i64, i64, i64)> = { |
| 350 | + let mut s = sched.borrow_mut(); |
| 351 | + let (fired, kept) = s.monitors.drain(..).partition(|(w, _, _)| *w == pid); |
| 352 | + s.monitors = kept; |
| 353 | + fired |
| 354 | + }; |
| 355 | + for (_, watcher, tag) in fired { |
| 356 | + crate::process::deliver_down(sched, watcher, tag, pid, &reason); |
| 357 | + } |
| 358 | + for linked in links { |
| 359 | + let trap = { |
| 360 | + let s = sched.borrow(); |
| 361 | + let Some(other) = actor_of(&s, linked).filter(|a| !a.dead) else { |
| 362 | + continue; |
| 363 | + }; |
| 364 | + other.links.retain(|l| *l != pid); |
| 365 | + other.trap |
| 366 | + }; |
| 367 | + // As in Erlang: actors that trap exits are told about every exit, |
| 368 | + // normal ones included; others only die of abnormal ones. |
| 369 | + if trap { |
| 370 | + crate::process::deliver_exit_signal(sched, linked, pid, &reason); |
| 371 | + } else if reason != Exit::Normal { |
| 372 | + exit_actor(sched, linked, reason.clone()); |
| 373 | + } |
| 374 | + } |
| 375 | +} |
| 376 | + |
| 377 | +/// Run until no actor is left. When the root exits, every other actor is |
| 378 | +/// stopped (and unwound). Returns the root's exit. |
| 215 | 379 | fn run(sched: &RefCell<Sched>, root: i64) -> Exit { |
| 216 | | − let mut root_exit = Exit::Running; |
| 380 | + sched.borrow_mut().root = root; |
| 217 | 381 | loop { |
| 218 | | − let (pid, mut fiber) = { |
| 219 | | − let mut s = sched.borrow_mut(); |
| 220 | | − let Some(pid) = s.run_queue.pop_front() else { |
| 382 | + let next = sched.borrow_mut().run_queue.pop_front(); |
| 383 | + let Some(pid) = next else { |
| 384 | + if sched.borrow().actors.is_empty() { |
| 221 | 385 | break; |
| 386 | + } |
| 387 | + if !advance_clock(sched) { |
| 388 | + // Nothing can ever run again. |
| 389 | + exit_actor( |
| 390 | + sched, |
| 391 | + root, |
| 392 | + Exit::Crashed("deadlock: every actor is waiting for a message".into()), |
| 393 | + ); |
| 394 | + let alive: Vec<i64> = sched.borrow().actors.keys().copied().collect(); |
| 395 | + for pid in alive { |
| 396 | + exit_actor(sched, pid, Exit::Killed); |
| 397 | + let mut s = sched.borrow_mut(); |
| 398 | + if actor_of(&s, pid).is_some_and(|a| a.wait != Wait::Ready) { |
| 399 | + s.wake(pid, UNIT); |
| 400 | + } |
| 401 | + } |
| 402 | + } |
| 403 | + continue; |
| 404 | + }; |
| 405 | + let (a, mut fiber) = { |
| 406 | + let mut s = sched.borrow_mut(); |
| 407 | + let Some(slot) = s.actors.get_mut(&pid) else { |
| 408 | + continue; |
| 409 | + }; |
| 410 | + let Some(fiber) = slot.fiber.take() else { |
| 411 | + continue; |
| 222 | 412 | }; |
| 223 | | − let slot = s |
| 224 | | − .actors |
| 225 | | − .get_mut(&pid) |
| 226 | | − .expect("tilrt: queued actor is missing"); |
| 227 | | − ( |
| 228 | | − pid, |
| 229 | | − slot.fiber |
| 230 | | − .take() |
| 231 | | − .expect("tilrt: actor fiber already running"), |
| 232 | | − ) |
| 413 | + (slot.actor, fiber) |
| 233 | 414 | }; |
| 415 | + // SAFETY: the actor is live and not running. |
| 416 | + unsafe { (*a).ctx.reductions = REDUCTIONS }; |
| 234 | 417 | match fiber.resume(()) { |
| 235 | 418 | CoroutineResult::Yield(()) => { |
| 236 | 419 | let mut s = sched.borrow_mut(); |
| 237 | 420 | s.actors.get_mut(&pid).expect("tilrt: actor vanished").fiber = Some(fiber); |
| 238 | | − s.run_queue.push_back(pid); |
| 421 | + // SAFETY: the actor is live. |
| 422 | + if unsafe { (*a).wait } == Wait::Ready { |
| 423 | + s.run_queue.push_back(pid); |
| 424 | + } |
| 239 | 425 | } |
| 240 | 426 | CoroutineResult::Return(()) => { |
| 241 | 427 | let slot = sched |
| @@ -244,19 +430,66 @@ fn run(sched: &RefCell<Sched>, root: i64) -> Exit { |
| 244 | 430 | .remove(&pid) |
| 245 | 431 | .expect("tilrt: actor vanished"); |
| 246 | 432 | // SAFETY: the fiber has returned; nothing refers to the actor. |
| 247 | | − let actor = unsafe { Box::from_raw(slot.actor) }; |
| 433 | + drop(unsafe { Box::from_raw(slot.actor) }); |
| 248 | 434 | LIVE_ACTORS.fetch_sub(1, Ordering::Relaxed); |
| 249 | 435 | if pid == root { |
| 250 | | − root_exit = actor.exit; |
| 251 | | − for slot in sched.borrow().actors.values() { |
| 252 | | − // SAFETY: remaining actors are live and not running. |
| 253 | | − unsafe { (*slot.actor).kill_requested = true }; |
| 436 | + // `main` stopped: stop everyone else, silently. |
| 437 | + let others: Vec<i64> = sched.borrow().actors.keys().copied().collect(); |
| 438 | + for other in others { |
| 439 | + let mut s = sched.borrow_mut(); |
| 440 | + if let Some(o) = actor_of(&s, other) { |
| 441 | + o.dead = true; |
| 442 | + o.kill_requested = true; |
| 443 | + if o.wait != Wait::Ready { |
| 444 | + s.wake(other, UNIT); |
| 445 | + } |
| 446 | + } |
| 254 | 447 | } |
| 255 | 448 | } |
| 256 | 449 | } |
| 257 | 450 | } |
| 258 | 451 | } |
| 259 | | − root_exit |
| 452 | + sched.borrow_mut().outcome.take().unwrap_or(Exit::Normal) |
| 453 | +} |
| 454 | + |
| 455 | +/// Jump the virtual clock to the next deadline and wake those actors. |
| 456 | +fn advance_clock(sched: &RefCell<Sched>) -> bool { |
| 457 | + let mut s = sched.borrow_mut(); |
| 458 | + let deadline = |a: &Actor| match a.wait { |
| 459 | + Wait::Receive { |
| 460 | + deadline: Some(d), .. |
| 461 | + } |
| 462 | + | Wait::Sleep { deadline: d } => Some(d), |
| 463 | + _ => None, |
| 464 | + }; |
| 465 | + let Some(next) = s |
| 466 | + .actors |
| 467 | + .values() |
| 468 | + // SAFETY: slots only hold live actors. |
| 469 | + .filter_map(|slot| deadline(unsafe { &*slot.actor })) |
| 470 | + .min() |
| 471 | + else { |
| 472 | + return false; |
| 473 | + }; |
| 474 | + s.clock = next; |
| 475 | + let mut due: Vec<i64> = s |
| 476 | + .actors |
| 477 | + .iter() |
| 478 | + // SAFETY: slots only hold live actors. |
| 479 | + .filter(|(_, slot)| deadline(unsafe { &*slot.actor }) == Some(next)) |
| 480 | + .map(|(p, _)| *p) |
| 481 | + .collect(); |
| 482 | + due.sort(); |
| 483 | + for pid in due { |
| 484 | + let a = actor_of(&s, pid).expect("listed"); |
| 485 | + // A receive that timed out returns `None` (constructor 0). |
| 486 | + let wake = match a.wait { |
| 487 | + Wait::Sleep { .. } => UNIT, |
| 488 | + _ => int(0), |
| 489 | + }; |
| 490 | + s.wake(pid, wake); |
| 491 | + } |
| 492 | + true |
| 260 | 493 | } |
| 261 | 494 | |
| 262 | 495 | /// Function prologue slow path: the reduction budget is spent. |
| @@ -274,7 +507,7 @@ pub unsafe extern "C" fn tl_preempt(ctx: *mut Ctx) { |
| 274 | 507 | } |
| 275 | 508 | |
| 276 | 509 | /// Yield the actor to the scheduler from its own stack; on resume, turn a |
| 277 | | −/// pending exit signal into unwinding. |
| 510 | +/// pending exit into unwinding. |
| 278 | 511 | /// |
| 279 | 512 | /// # Safety |
| 280 | 513 | /// `ctx` must be the running actor's context, on the actor's own stack. |
| @@ -291,10 +524,28 @@ pub(crate) unsafe fn preempt_root(ctx: *mut Ctx) { |
| 291 | 524 | } |
| 292 | 525 | } |
| 293 | 526 | |
| 294 | | −/// Start a new actor running `closure` (consumed). |
| 527 | +/// Park the running actor until it is woken (its `wait` must be set); |
| 528 | +/// returns the wake value, or unit with `yielding = KILL` if it exited |
| 529 | +/// meanwhile. |
| 295 | 530 | /// |
| 296 | | −/// M0: the closure is moved, not deep-copied, since every actor shares one |
| 297 | | −/// scheduler thread. M6 replaces this with a deep copy into the new actor. |
| 531 | +/// # Safety |
| 532 | +/// `ctx` must be the running actor's context. |
| 533 | +pub(crate) unsafe fn park(ctx: *mut Ctx) -> Value { |
| 534 | + // SAFETY: forwarded caller guarantee. |
| 535 | + unsafe { |
| 536 | + tl_preempt(ctx); |
| 537 | + let a = actor(ctx); |
| 538 | + let wake = std::mem::replace(&mut (*a).wake, UNIT); |
| 539 | + if (*ctx).yielding != YIELD_NONE { |
| 540 | + drop_value(ctx, wake); |
| 541 | + return UNIT; |
| 542 | + } |
| 543 | + wake |
| 544 | + } |
| 545 | +} |
| 546 | + |
| 547 | +/// Start a new actor running `closure` (consumed), called as |
| 548 | +/// `code(ctx, self)` (the M0 spike's convention). |
| 298 | 549 | /// |
| 299 | 550 | /// # Safety |
| 300 | 551 | /// `ctx` must be the running actor's context; `closure` an owned closure |
| @@ -315,10 +566,7 @@ pub unsafe extern "C" fn tl_spawn(ctx: *mut Ctx, closure: Value) -> Value { |
| 315 | 566 | pub unsafe extern "C" fn tl_kill(ctx: *mut Ctx, pid: Value) { |
| 316 | 567 | // SAFETY: caller guarantees a running actor. |
| 317 | 568 | let sched = unsafe { &*(*actor(ctx)).sched }; |
| 318 | | − if let Some(slot) = sched.borrow().actors.get(&int_get(pid)) { |
| 319 | | − // SAFETY: slots only hold live actors. |
| 320 | | − unsafe { (*slot.actor).kill_requested = true }; |
| 321 | | − } |
| 569 | + exit_actor(sched, int_get(pid), Exit::Killed); |
| 322 | 570 | } |
| 323 | 571 | |
| 324 | 572 | #[unsafe(no_mangle)] |
| @@ -340,8 +588,8 @@ pub unsafe extern "C" fn tl_main(entry: EntryFn) -> i32 { |
| 340 | 588 | } |
| 341 | 589 | } |
| 342 | 590 | |
| 343 | | −/// Run a compiled program's `entry` as the root actor. A panic of the root |
| 344 | | −/// prints `error: panic: <message>` and gives exit code 101, like |
| 591 | +/// Run a compiled program's `entry` as the root actor. If the root stops |
| 592 | +/// abnormally, print `error: panic: <message>` and return 101, like |
| 345 | 593 | /// `tilc run`. |
| 346 | 594 | /// |
| 347 | 595 | /// # Safety |
| @@ -352,11 +600,14 @@ pub unsafe extern "C" fn tl_main_program(entry: EntryFn) -> i32 { |
| 352 | 600 | let sched = RefCell::new(Sched::default()); |
| 353 | 601 | let root = spawn_actor(&sched, Body::Entry(entry), ROOT_STACK_SIZE); |
| 354 | 602 | match run(&sched, root) { |
| 355 | | − Exit::Normal => 0, |
| 603 | + Exit::Normal | Exit::Running => 0, |
| 356 | 604 | Exit::Crashed(message) => { |
| 357 | 605 | eprintln!("error: panic: {message}"); |
| 358 | 606 | 101 |
| 359 | 607 | } |
| 360 | | − _ => 1, |
| 608 | + Exit::Killed => { |
| 609 | + eprintln!("error: panic: the main actor was killed"); |
| 610 | + 101 |
| 611 | + } |
| 361 | 612 | } |
| 362 | 613 | } |