| @@ -1,8 +1,7 @@ |
| 1 | | −//! Actors and the scheduler (ADR 0004; M6 native part 1). |
| 1 | +//! Actors and the scheduler (ADR 0004, Revision 1). |
| 2 | 2 | //! |
| 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; |
| 3 | +//! The semantics are the interpreter's (`tilc_core::sched`): |
| 4 | +//! - a round-robin run queue, shared by the scheduler threads; |
| 6 | 5 | //! - an actor is preempted after [`REDUCTIONS`] function entries, and gets |
| 7 | 6 | //! a fresh budget whenever it is scheduled or performs a `proc` |
| 8 | 7 | //! operation (each of which is a scheduling point in the interpreter); |
| @@ -13,22 +12,32 @@ |
| 13 | 12 | //! them an `ExitSignal` if they trap exits; monitors receive `Down`; |
| 14 | 13 | //! - when `main` stops, the other actors are stopped. |
| 15 | 14 | //! |
| 15 | +//! **Threads.** `TILC_THREADS` scheduler threads (default: one per core) |
| 16 | +//! take actors from one run queue, so an actor may run on a different |
| 17 | +//! thread after each suspension. With `TILC_THREADS=1` the order is the |
| 18 | +//! interpreter's, and `tests/run` outputs are reproducible. Messages are |
| 19 | +//! made thread-safe when sent (`send`: move, share or copy). |
| 20 | +//! |
| 21 | +//! **What is shared, and how.** Everything other actors may touch (the |
| 22 | +//! mailbox, links, the wait state: [`Proc`]) lives in [`Sched`], behind |
| 23 | +//! one mutex. An [`Actor`] holds what only the thread running it touches |
| 24 | +//! (its context, drop worklist, yielders), plus an atomic kill flag. A |
| 25 | +//! wake-up queues an actor only if it is suspended; if it is still on its |
| 26 | +//! way to suspending, the thread running it queues it when it yields, so |
| 27 | +//! no wake-up is lost or doubled. |
| 28 | +//! |
| 16 | 29 | //! **Logical exit and unwinding are separate.** An actor exits (monitors |
| 17 | 30 | //! and links are notified) the moment it is killed, as in the interpreter. |
| 18 | 31 | //! Its fiber then runs once more to unwind, dropping everything it holds. |
| 19 | 32 | //! A fiber is never dropped while suspended, because corosensei would |
| 20 | 33 | //! force-unwind C frames. |
| 21 | 34 | //! |
| 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. |
| 35 | +//! Invariant: the scheduler lock is never held while actor code runs, and |
| 36 | +//! never taken twice by one thread. |
| 28 | 37 | |
| 29 | | −use std::cell::RefCell; |
| 30 | | −use std::collections::{HashMap, VecDeque}; |
| 31 | | −use std::sync::atomic::{AtomicI64, Ordering}; |
| 38 | +use std::collections::{HashMap, HashSet, VecDeque}; |
| 39 | +use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; |
| 40 | +use std::sync::{Condvar, Mutex, MutexGuard}; |
| 32 | 41 | |
| 33 | 42 | use corosensei::stack::DefaultStack; |
| 34 | 43 | use corosensei::{Coroutine, CoroutineResult, Yielder}; |
| @@ -49,15 +58,33 @@ const STACK_SIZE: usize = 256 * 1024; |
| 49 | 58 | const PROGRAM_STACK_SIZE: usize = 64 << 20; |
| 50 | 59 | /// The root actor (`main`). |
| 51 | 60 | const ROOT_STACK_SIZE: usize = 1 << 30; |
| 61 | +/// The reactor token of the blocking pool's waker (sockets count from 1). |
| 62 | +const WAKER: mio::Token = mio::Token(0); |
| 63 | +/// Finished program stacks kept for reuse: mapping and unmapping one per |
| 64 | +/// actor is slow, and with several threads every unmap interrupts them all. |
| 65 | +const STACK_POOL: usize = 256; |
| 52 | 66 | |
| 53 | 67 | static LIVE_ACTORS: AtomicI64 = AtomicI64::new(0); |
| 54 | 68 | /// Set by `tl_main_program`: the root's crash is reported by it, as |
| 55 | 69 | /// `tilc run` reports a panic; other crashes as the interpreter does. |
| 56 | | −static PROGRAM_MODE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); |
| 70 | +static PROGRAM_MODE: AtomicBool = AtomicBool::new(false); |
| 57 | 71 | |
| 58 | 72 | type EntryFn = unsafe extern "C" fn(*mut Ctx) -> Value; |
| 59 | 73 | type ActorClosureFn = unsafe extern "C" fn(*mut Ctx, Value) -> Value; |
| 60 | | −type Fiber = Coroutine<(), (), (), DefaultStack>; |
| 74 | + |
| 75 | +/// An actor's fiber, movable between scheduler threads. |
| 76 | +/// The second field is the stack size. |
| 77 | +struct Fiber(Coroutine<(), (), (), DefaultStack>, usize); |
| 78 | + |
| 79 | +// SAFETY: corosensei fibers are `!Send` because code on them could keep |
| 80 | +// references to thread-local storage across a suspension, which would then |
| 81 | +// resume on another thread. Code on actor fibers never does: generated C |
| 82 | +// uses no thread-locals (its state is in `tl_ctx`), and the runtime keeps |
| 83 | +// all actor state in `Actor`/`Sched`; Rust's own thread-locals (stdout |
| 84 | +// locks, panic counts) are never held across a suspension, which only |
| 85 | +// happens in `preempt_root` and `handlers`. Revisit with the runtime's own |
| 86 | +// context switch (issue #35). |
| 87 | +unsafe impl Send for Fiber {} |
| 61 | 88 | |
| 62 | 89 | enum Body { |
| 63 | 90 | Entry(EntryFn), |
| @@ -71,7 +98,6 @@ enum Body { |
| 71 | 98 | /// Why an actor stopped. |
| 72 | 99 | #[derive(Clone, Debug, PartialEq)] |
| 73 | 100 | pub(crate) enum Exit { |
| 74 | | − Running, |
| 75 | 101 | Normal, |
| 76 | 102 | Killed, |
| 77 | 103 | Crashed(String), |
| @@ -80,8 +106,8 @@ pub(crate) enum Exit { |
| 80 | 106 | #[derive(Clone, Copy, PartialEq)] |
| 81 | 107 | pub(crate) enum Wait { |
| 82 | 108 | Ready, |
| 109 | + /// Waiting for a message on one of the actor's `waiting_tags`. |
| 83 | 110 | Receive { |
| 84 | | − tag: i64, |
| 85 | 111 | deadline: Option<u64>, |
| 86 | 112 | }, |
| 87 | 113 | Sleep { |
| @@ -93,26 +119,84 @@ pub(crate) enum Wait { |
| 93 | 119 | Io, |
| 94 | 120 | } |
| 95 | 121 | |
| 122 | +/// What only the thread running the actor touches, plus the kill flag. |
| 96 | 123 | pub struct Actor { |
| 97 | 124 | ctx: Ctx, |
| 98 | 125 | pub(crate) pid: i64, |
| 99 | 126 | next_marker: u64, |
| 100 | | − pub(crate) kill_requested: bool, |
| 101 | | − exit: Exit, |
| 127 | + /// Set (under the scheduler lock) when the actor exits; read by the |
| 128 | + /// actor at its safe points. |
| 129 | + kill_requested: AtomicBool, |
| 102 | 130 | drops: DropStack, |
| 103 | 131 | yielder: *const Yielder<(), ()>, |
| 104 | 132 | /// The `ctl` handler fiber running now, or null on the actor's own |
| 105 | 133 | /// stack (see `handlers`). |
| 106 | 134 | handler: *const crate::handlers::HandlerYielder, |
| 107 | | − sched: *const RefCell<Sched>, |
| 108 | | − // OTP state (see `process`). |
| 109 | | − pub(crate) mailbox: VecDeque<(i64, Value)>, |
| 135 | + sched: *const Shared, |
| 136 | +} |
| 137 | + |
| 138 | +impl Actor { |
| 139 | + pub(crate) fn kill_requested(&self) -> bool { |
| 140 | + self.kill_requested.load(Ordering::Acquire) |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +/// Messages by subject tag, each with its arrival number: receiving from |
| 145 | +/// one subject is O(1) however many other messages wait, and |
| 146 | +/// `receive_any` still takes the oldest of several subjects. |
| 147 | +#[derive(Default)] |
| 148 | +pub(crate) struct Mailbox { |
| 149 | + by_tag: HashMap<i64, VecDeque<(u64, Value)>>, |
| 150 | + arrived: u64, |
| 151 | +} |
| 152 | + |
| 153 | +impl Mailbox { |
| 154 | + pub(crate) fn push(&mut self, tag: i64, message: Value) { |
| 155 | + self.arrived += 1; |
| 156 | + self.by_tag |
| 157 | + .entry(tag) |
| 158 | + .or_default() |
| 159 | + .push_back((self.arrived, message)); |
| 160 | + } |
| 161 | + |
| 162 | + /// The oldest message on one of `tags`, with its tag. |
| 163 | + pub(crate) fn take(&mut self, tags: &[i64]) -> Option<(i64, Value)> { |
| 164 | + let tag = tags |
| 165 | + .iter() |
| 166 | + .filter_map(|t| Some((self.by_tag.get(t)?.front()?.0, *t))) |
| 167 | + .min()? |
| 168 | + .1; |
| 169 | + let queue = self.by_tag.get_mut(&tag)?; |
| 170 | + let (_, message) = queue.pop_front()?; |
| 171 | + if queue.is_empty() { |
| 172 | + self.by_tag.remove(&tag); |
| 173 | + } |
| 174 | + Some((tag, message)) |
| 175 | + } |
| 176 | + |
| 177 | + /// Every message left, to drop. |
| 178 | + pub(crate) fn drain(&mut self) -> impl Iterator<Item = Value> { |
| 179 | + std::mem::take(&mut self.by_tag) |
| 180 | + .into_values() |
| 181 | + .flatten() |
| 182 | + .map(|(_, message)| message) |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +/// An actor's OTP state, which other actors read and write (under the |
| 187 | +/// scheduler lock). |
| 188 | +pub(crate) struct Proc { |
| 189 | + pub(crate) mailbox: Mailbox, |
| 110 | 190 | pub(crate) wait: Wait, |
| 111 | 191 | /// What a parked operation returns when woken. |
| 112 | 192 | pub(crate) wake: Value, |
| 113 | 193 | pub(crate) links: Vec<i64>, |
| 114 | 194 | pub(crate) trap: bool, |
| 115 | 195 | pub(crate) exits_tag: Option<i64>, |
| 196 | + /// While `wait` is `Receive`: the tags waited on, and whether the |
| 197 | + /// answer carries the tag (`receive_any`). |
| 198 | + pub(crate) waiting_tags: Vec<i64>, |
| 199 | + pub(crate) waiting_any: bool, |
| 116 | 200 | /// Exited (logically); its fiber may still have to unwind. |
| 117 | 201 | pub(crate) dead: bool, |
| 118 | 202 | } |
| @@ -121,6 +205,7 @@ struct Slot { |
| 121 | 205 | actor: *mut Actor, |
| 122 | 206 | /// `None` while the fiber is running. |
| 123 | 207 | fiber: Option<Fiber>, |
| 208 | + proc: Proc, |
| 124 | 209 | } |
| 125 | 210 | |
| 126 | 211 | #[derive(Default)] |
| @@ -136,11 +221,97 @@ pub(crate) struct Sched { |
| 136 | 221 | outcome: Option<Exit>, |
| 137 | 222 | /// Calls running on the blocking pool. |
| 138 | 223 | pub(crate) blocking: usize, |
| 139 | | − /// The reactor for sockets (made when the scheduler starts). |
| 224 | + /// The reactor for sockets. Taken out while a thread waits on it. |
| 140 | 225 | poll: Option<mio::Poll>, |
| 226 | + registry: Option<mio::Registry>, |
| 227 | + /// Wakes the reactor when a blocking call finishes. |
| 228 | + pub(crate) waker: Option<std::sync::Arc<mio::Waker>>, |
| 141 | 229 | next_token: usize, |
| 142 | 230 | /// Actors parked on a socket, by its token. |
| 143 | 231 | pub(crate) io_waiters: HashMap<mio::Token, i64>, |
| 232 | + /// Sockets that became ready while no actor waited on them. Events are |
| 233 | + /// edge-triggered, and another thread may poll between an actor's |
| 234 | + /// `WouldBlock` and its parking: the actor then retries instead. |
| 235 | + pub(crate) io_ready: HashSet<mio::Token>, |
| 236 | + /// Actors running now (one per busy thread). |
| 237 | + running: usize, |
| 238 | + /// A thread is waiting for the blocking pool, sockets or the clock. |
| 239 | + idling: bool, |
| 240 | + /// Every actor is gone: the threads stop. |
| 241 | + finished: bool, |
| 242 | + /// Stacks of `PROGRAM_STACK_SIZE` whose fibers finished. |
| 243 | + stacks: Vec<DefaultStack>, |
| 244 | + /// Work was queued: wake the waiting threads when the lock is released. |
| 245 | + notify: bool, |
| 246 | +} |
| 247 | + |
| 248 | +// SAFETY: the raw pointers in `Slot` are only dereferenced under the |
| 249 | +// scheduler lock, or by the one thread running that actor; `Value`s in |
| 250 | +// mailboxes are made thread-safe by `send::transfer`. |
| 251 | +unsafe impl Send for Sched {} |
| 252 | + |
| 253 | +/// The scheduler state shared by the threads. |
| 254 | +pub(crate) struct Shared { |
| 255 | + state: Mutex<Sched>, |
| 256 | + /// Signalled when work is queued, a thread stops idling, or the last |
| 257 | + /// actor finished. |
| 258 | + work: Condvar, |
| 259 | +} |
| 260 | + |
| 261 | +/// The locked scheduler. Releasing it wakes the waiting threads if work |
| 262 | +/// was queued meanwhile. |
| 263 | +pub(crate) struct Locked<'a> { |
| 264 | + guard: Option<MutexGuard<'a, Sched>>, |
| 265 | + work: &'a Condvar, |
| 266 | +} |
| 267 | + |
| 268 | +impl Shared { |
| 269 | + fn new() -> Shared { |
| 270 | + Shared { |
| 271 | + state: Mutex::new(Sched::default()), |
| 272 | + work: Condvar::new(), |
| 273 | + } |
| 274 | + } |
| 275 | + |
| 276 | + pub(crate) fn lock(&self) -> Locked<'_> { |
| 277 | + Locked { |
| 278 | + guard: Some(self.state.lock().expect("tilrt: scheduler poisoned")), |
| 279 | + work: &self.work, |
| 280 | + } |
| 281 | + } |
| 282 | +} |
| 283 | + |
| 284 | +impl Locked<'_> { |
| 285 | + /// Release the lock until another thread signals work. |
| 286 | + fn wait(mut self) -> Self { |
| 287 | + let guard = self.guard.take().expect("locked"); |
| 288 | + let guard = self.work.wait(guard).expect("tilrt: scheduler poisoned"); |
| 289 | + self.guard = Some(guard); |
| 290 | + self |
| 291 | + } |
| 292 | +} |
| 293 | + |
| 294 | +impl std::ops::Deref for Locked<'_> { |
| 295 | + type Target = Sched; |
| 296 | + fn deref(&self) -> &Sched { |
| 297 | + self.guard.as_ref().expect("locked") |
| 298 | + } |
| 299 | +} |
| 300 | + |
| 301 | +impl std::ops::DerefMut for Locked<'_> { |
| 302 | + fn deref_mut(&mut self) -> &mut Sched { |
| 303 | + self.guard.as_mut().expect("locked") |
| 304 | + } |
| 305 | +} |
| 306 | + |
| 307 | +impl Drop for Locked<'_> { |
| 308 | + fn drop(&mut self) { |
| 309 | + if let Some(guard) = &mut self.guard |
| 310 | + && std::mem::take(&mut guard.notify) |
| 311 | + { |
| 312 | + self.work.notify_all(); |
| 313 | + } |
| 314 | + } |
| 144 | 315 | } |
| 145 | 316 | |
| 146 | 317 | /// # Safety |
| @@ -183,33 +354,52 @@ pub(crate) unsafe fn next_marker(ctx: *mut Ctx) -> u64 { |
| 183 | 354 | /// # Safety |
| 184 | 355 | /// `ctx` must be the running actor's context; the references must not |
| 185 | 356 | /// outlive the current runtime call. |
| 186 | | −pub(crate) unsafe fn this<'a>(ctx: *mut Ctx) -> (&'a mut Actor, &'a RefCell<Sched>) { |
| 357 | +pub(crate) unsafe fn this<'a>(ctx: *mut Ctx) -> (&'a Actor, &'a Shared) { |
| 187 | 358 | // SAFETY: forwarded caller guarantee. |
| 188 | 359 | unsafe { |
| 189 | 360 | let a = actor(ctx); |
| 190 | | − (&mut *a, &*(*a).sched) |
| 361 | + (&*a, &*(*a).sched) |
| 191 | 362 | } |
| 192 | 363 | } |
| 193 | 364 | |
| 194 | | −/// Actor `pid`, if its fiber has not finished. |
| 195 | | −pub(crate) fn actor_of<'a>(s: &Sched, pid: i64) -> Option<&'a mut Actor> { |
| 196 | | − // SAFETY: slots only hold live actors; callers do not keep the |
| 197 | | − // reference across scheduling points. |
| 198 | | − s.actors.get(&pid).map(|slot| unsafe { &mut *slot.actor }) |
| 199 | | −} |
| 200 | | − |
| 201 | 365 | impl Sched { |
| 202 | 366 | pub(crate) fn tag(&mut self) -> i64 { |
| 203 | 367 | self.next_tag += 1; |
| 204 | 368 | self.next_tag |
| 205 | 369 | } |
| 206 | 370 | |
| 207 | | − /// Make a parked actor runnable; its operation returns `wake`. |
| 371 | + /// The OTP state of actor `pid`, if its fiber has not finished. |
| 372 | + pub(crate) fn proc(&mut self, pid: i64) -> Option<&mut Proc> { |
| 373 | + self.actors.get_mut(&pid).map(|slot| &mut slot.proc) |
| 374 | + } |
| 375 | + |
| 376 | + /// The OTP state of actor `pid`, if it is alive (not exited). |
| 377 | + pub(crate) fn alive(&mut self, pid: i64) -> Option<&mut Proc> { |
| 378 | + self.proc(pid).filter(|p| !p.dead) |
| 379 | + } |
| 380 | + |
| 381 | + /// Make a parked actor runnable; its operation returns `wake`. If its |
| 382 | + /// fiber is still running (on its way to suspending), the thread |
| 383 | + /// running it queues it. |
| 208 | 384 | pub(crate) fn wake(&mut self, pid: i64, wake: Value) { |
| 209 | | − if let Some(a) = actor_of(self, pid) { |
| 210 | | − a.wait = Wait::Ready; |
| 211 | | − a.wake = wake; |
| 385 | + let Some(slot) = self.actors.get_mut(&pid) else { |
| 386 | + return; |
| 387 | + }; |
| 388 | + slot.proc.wait = Wait::Ready; |
| 389 | + slot.proc.wake = wake; |
| 390 | + if slot.fiber.is_some() { |
| 212 | 391 | self.run_queue.push_back(pid); |
| 392 | + self.notify = true; |
| 393 | + } |
| 394 | + } |
| 395 | + |
| 396 | + /// Wake `pid` unless it is runnable or in a blocking call. |
| 397 | + fn interrupt(&mut self, pid: i64) { |
| 398 | + if self |
| 399 | + .proc(pid) |
| 400 | + .is_some_and(|p| p.wait != Wait::Ready && p.wait != Wait::Blocking) |
| 401 | + { |
| 402 | + self.wake(pid, UNIT); |
| 213 | 403 | } |
| 214 | 404 | } |
| 215 | 405 | |
| @@ -218,20 +408,46 @@ impl Sched { |
| 218 | 408 | mio::Token(self.next_token) |
| 219 | 409 | } |
| 220 | 410 | |
| 221 | | − pub(crate) fn reactor(&self) -> &mio::Poll { |
| 222 | | − self.poll |
| 411 | + pub(crate) fn registry(&self) -> &mio::Registry { |
| 412 | + self.registry |
| 223 | 413 | .as_ref() |
| 224 | 414 | .expect("tilrt: the reactor starts with the scheduler") |
| 225 | 415 | } |
| 226 | 416 | |
| 227 | 417 | /// Whether `pid` is alive (not exited). |
| 228 | | − pub(crate) fn exists(&self, pid: i64) -> bool { |
| 229 | | − actor_of(self, pid).is_some_and(|a| !a.dead) |
| 418 | + pub(crate) fn exists(&mut self, pid: i64) -> bool { |
| 419 | + self.alive(pid).is_some() |
| 230 | 420 | } |
| 421 | + |
| 422 | + /// Mark `pid` as exiting, so it unwinds at its next safe point. |
| 423 | + fn request_kill(&mut self, pid: i64) { |
| 424 | + if let Some(slot) = self.actors.get(&pid) { |
| 425 | + // SAFETY: slots only hold live actors. |
| 426 | + unsafe { (*slot.actor).kill_requested.store(true, Ordering::Release) }; |
| 427 | + } |
| 428 | + } |
| 429 | +} |
| 430 | + |
| 431 | +/// How a new actor is tied to the one spawning it. |
| 432 | +#[derive(Clone, Copy, PartialEq)] |
| 433 | +pub(crate) enum Tie { |
| 434 | + None, |
| 435 | + Link, |
| 436 | + Monitor, |
| 231 | 437 | } |
| 232 | 438 | |
| 233 | | −fn spawn_actor(sched: &RefCell<Sched>, body: Body, stack_size: usize) -> i64 { |
| 234 | | − let mut s = sched.borrow_mut(); |
| 439 | +/// Start an actor, tied to `parent` as `tie` says before it can run, so |
| 440 | +/// even one that stops at once is linked or monitored. Returns its pid, |
| 441 | +/// and the monitor's tag. |
| 442 | +fn spawn_actor( |
| 443 | + sched: &Shared, |
| 444 | + body: Body, |
| 445 | + stack_size: usize, |
| 446 | + parent: Option<i64>, |
| 447 | + tie: Tie, |
| 448 | +) -> (i64, Option<i64>) { |
| 449 | + let link = parent.filter(|_| tie == Tie::Link); |
| 450 | + let mut s = sched.lock(); |
| 235 | 451 | let pid = s.next_pid; |
| 236 | 452 | s.next_pid += 1; |
| 237 | 453 | let a = Box::into_raw(Box::new(Actor { |
| @@ -246,24 +462,21 @@ fn spawn_actor(sched: &RefCell<Sched>, body: Body, stack_size: usize) -> i64 { |
| 246 | 462 | }, |
| 247 | 463 | pid, |
| 248 | 464 | next_marker: 0, |
| 249 | | − kill_requested: false, |
| 250 | | − exit: Exit::Running, |
| 465 | + kill_requested: AtomicBool::new(false), |
| 251 | 466 | drops: DropStack::default(), |
| 252 | 467 | yielder: std::ptr::null(), |
| 253 | 468 | handler: std::ptr::null(), |
| 254 | 469 | sched, |
| 255 | | − mailbox: VecDeque::new(), |
| 256 | | − wait: Wait::Ready, |
| 257 | | − wake: UNIT, |
| 258 | | − links: Vec::new(), |
| 259 | | − trap: false, |
| 260 | | − exits_tag: None, |
| 261 | | − dead: false, |
| 262 | 470 | })); |
| 263 | 471 | // SAFETY: `a` is a fresh allocation; `rt` points back at it. |
| 264 | 472 | unsafe { (*a).ctx.rt = a.cast() }; |
| 265 | | − let stack = DefaultStack::new(stack_size).expect("tilrt: cannot allocate actor stack"); |
| 266 | | − let fiber = Fiber::with_stack(stack, move |yielder: &Yielder<(), ()>, ()| { |
| 473 | + let pooled = (stack_size == PROGRAM_STACK_SIZE) |
| 474 | + .then(|| s.stacks.pop()) |
| 475 | + .flatten(); |
| 476 | + let stack = pooled.unwrap_or_else(|| { |
| 477 | + DefaultStack::new(stack_size).expect("tilrt: cannot allocate actor stack") |
| 478 | + }); |
| 479 | + let fiber = Coroutine::with_stack(stack, move |yielder: &Yielder<(), ()>, ()| { |
| 267 | 480 | // SAFETY: the actor outlives its fiber (freed only after Return). |
| 268 | 481 | unsafe { |
| 269 | 482 | (*a).yielder = yielder; |
| @@ -274,22 +487,52 @@ fn spawn_actor(sched: &RefCell<Sched>, body: Body, stack_size: usize) -> i64 { |
| 274 | 487 | pid, |
| 275 | 488 | Slot { |
| 276 | 489 | actor: a, |
| 277 | | − fiber: Some(fiber), |
| 490 | + fiber: Some(Fiber(fiber, stack_size)), |
| 491 | + proc: Proc { |
| 492 | + mailbox: Mailbox::default(), |
| 493 | + wait: Wait::Ready, |
| 494 | + wake: UNIT, |
| 495 | + links: link.into_iter().collect(), |
| 496 | + trap: false, |
| 497 | + exits_tag: None, |
| 498 | + waiting_tags: Vec::new(), |
| 499 | + waiting_any: false, |
| 500 | + dead: false, |
| 501 | + }, |
| 278 | 502 | }, |
| 279 | 503 | ); |
| 504 | + if let Some(parent) = link.and_then(|p| s.proc(p)) { |
| 505 | + parent.links.push(pid); |
| 506 | + } |
| 507 | + let monitor = match (parent, tie) { |
| 508 | + (Some(watcher), Tie::Monitor) => { |
| 509 | + let tag = s.tag(); |
| 510 | + s.monitors.push((pid, watcher, tag)); |
| 511 | + Some(tag) |
| 512 | + } |
| 513 | + _ => None, |
| 514 | + }; |
| 280 | 515 | s.run_queue.push_back(pid); |
| 516 | + s.notify = true; |
| 281 | 517 | LIVE_ACTORS.fetch_add(1, Ordering::Relaxed); |
| 282 | | − pid |
| 518 | + (pid, monitor) |
| 283 | 519 | } |
| 284 | 520 | |
| 285 | | −/// Spawn a compiled program's actor running `body` (consumed). |
| 521 | +/// Spawn a compiled program's actor running `body` (consumed), tied to |
| 522 | +/// the running actor. Returns its pid, and the monitor's tag. |
| 286 | 523 | /// |
| 287 | 524 | /// # Safety |
| 288 | 525 | /// `ctx` must be the running actor's context. |
| 289 | | −pub(crate) unsafe fn spawn_program(ctx: *mut Ctx, body: Value) -> i64 { |
| 526 | +pub(crate) unsafe fn spawn_program(ctx: *mut Ctx, body: Value, tie: Tie) -> (i64, Option<i64>) { |
| 290 | 527 | // SAFETY: forwarded caller guarantee. |
| 291 | | − let (_, sched) = unsafe { this(ctx) }; |
| 292 | | − spawn_actor(sched, Body::Program(body), PROGRAM_STACK_SIZE) |
| 528 | + let (a, sched) = unsafe { this(ctx) }; |
| 529 | + spawn_actor( |
| 530 | + sched, |
| 531 | + Body::Program(body), |
| 532 | + PROGRAM_STACK_SIZE, |
| 533 | + Some(a.pid), |
| 534 | + tie, |
| 535 | + ) |
| 293 | 536 | } |
| 294 | 537 | |
| 295 | 538 | /// Run an actor's body to completion and record why it exited. |
| @@ -301,12 +544,12 @@ unsafe fn run_body(a: *mut Actor, body: Body) { |
| 301 | 544 | unsafe { |
| 302 | 545 | let ctx = &raw mut (*a).ctx; |
| 303 | 546 | let result = match body { |
| 304 | | − Body::Closure(clo) | Body::Program(clo) if (*a).kill_requested => { |
| 547 | + Body::Closure(clo) | Body::Program(clo) if (*a).kill_requested() => { |
| 305 | 548 | drop_value(ctx, clo); |
| 306 | 549 | (*ctx).yielding = YIELD_KILL; |
| 307 | 550 | UNIT |
| 308 | 551 | } |
| 309 | | − _ if (*a).kill_requested => { |
| 552 | + _ if (*a).kill_requested() => { |
| 310 | 553 | (*ctx).yielding = YIELD_KILL; |
| 311 | 554 | UNIT |
| 312 | 555 | } |
| @@ -335,58 +578,58 @@ unsafe fn run_body(a: *mut Actor, body: Body) { |
| 335 | 578 | (*ctx).yielding = YIELD_NONE; |
| 336 | 579 | let sched = &*(*a).sched; |
| 337 | 580 | exit_actor(sched, (*a).pid, reason); |
| 338 | | − // Release what the actor still owns. |
| 339 | | − for (_, message) in std::mem::take(&mut (*a).mailbox) { |
| 581 | + // Release what the actor still owns. Nobody delivers to it now. |
| 582 | + let (mut mailbox, wake) = { |
| 583 | + let mut s = sched.lock(); |
| 584 | + let p = s.proc((*a).pid).expect("tilrt: running actor vanished"); |
| 585 | + ( |
| 586 | + std::mem::take(&mut p.mailbox), |
| 587 | + std::mem::replace(&mut p.wake, UNIT), |
| 588 | + ) |
| 589 | + }; |
| 590 | + for message in mailbox.drain() { |
| 340 | 591 | drop_value(ctx, message); |
| 341 | 592 | } |
| 342 | | − drop_value(ctx, std::mem::replace(&mut (*a).wake, UNIT)); |
| 593 | + drop_value(ctx, wake); |
| 343 | 594 | } |
| 344 | 595 | } |
| 345 | 596 | |
| 346 | 597 | /// Stop `pid` (logically): record its exit, notify monitors, propagate |
| 347 | 598 | /// through links, and make sure its fiber unwinds. |
| 348 | | −pub(crate) fn exit_actor(sched: &RefCell<Sched>, pid: i64, reason: Exit) { |
| 349 | | − let links = { |
| 350 | | − let mut s = sched.borrow_mut(); |
| 351 | | − let Some(a) = actor_of(&s, pid) else { |
| 599 | +pub(crate) fn exit_actor(sched: &Shared, pid: i64, reason: Exit) { |
| 600 | + let (links, fired) = { |
| 601 | + let mut s = sched.lock(); |
| 602 | + let root = s.root; |
| 603 | + let Some(p) = s.alive(pid) else { |
| 352 | 604 | return; |
| 353 | 605 | }; |
| 354 | | − if a.dead { |
| 355 | | − return; |
| 356 | | − } |
| 357 | | − a.dead = true; |
| 358 | | − a.exit = reason.clone(); |
| 359 | | − if pid == s.root && s.outcome.is_none() { |
| 606 | + p.dead = true; |
| 607 | + let links = std::mem::take(&mut p.links); |
| 608 | + if pid == root && s.outcome.is_none() { |
| 360 | 609 | s.outcome = Some(reason.clone()); |
| 361 | 610 | } |
| 362 | 611 | if let Exit::Crashed(m) = &reason { |
| 363 | 612 | let program = PROGRAM_MODE.load(Ordering::Relaxed); |
| 364 | | − if !(program && pid == s.root) { |
| 613 | + if !(program && pid == root) { |
| 365 | 614 | let prefix = if program { "" } else { "tilrt: " }; |
| 366 | 615 | eprintln!("{prefix}actor {pid} crashed: {m}"); |
| 367 | 616 | } |
| 368 | 617 | } |
| 369 | 618 | // Its fiber unwinds the next time it runs (after a blocking call |
| 370 | 619 | // returns: that call still reads the actor's values). |
| 371 | | − a.kill_requested = true; |
| 372 | | − if a.wait != Wait::Ready && a.wait != Wait::Blocking { |
| 373 | | − s.wake(pid, UNIT); |
| 374 | | − } |
| 375 | | − std::mem::take(&mut a.links) |
| 376 | | − }; |
| 377 | | − let fired: Vec<(i64, i64, i64)> = { |
| 378 | | − let mut s = sched.borrow_mut(); |
| 620 | + s.request_kill(pid); |
| 621 | + s.interrupt(pid); |
| 379 | 622 | let (fired, kept) = s.monitors.drain(..).partition(|(w, _, _)| *w == pid); |
| 380 | 623 | s.monitors = kept; |
| 381 | | − fired |
| 624 | + (links, fired) |
| 382 | 625 | }; |
| 383 | 626 | for (_, watcher, tag) in fired { |
| 384 | 627 | crate::process::deliver_down(sched, watcher, tag, pid, &reason); |
| 385 | 628 | } |
| 386 | 629 | for linked in links { |
| 387 | 630 | let trap = { |
| 388 | | − let s = sched.borrow(); |
| 389 | | − let Some(other) = actor_of(&s, linked).filter(|a| !a.dead) else { |
| 631 | + let mut s = sched.lock(); |
| 632 | + let Some(other) = s.alive(linked) else { |
| 390 | 633 | continue; |
| 391 | 634 | }; |
| 392 | 635 | other.links.retain(|l| *l != pid); |
| @@ -402,212 +645,291 @@ pub(crate) fn exit_actor(sched: &RefCell<Sched>, pid: i64, reason: Exit) { |
| 402 | 645 | } |
| 403 | 646 | } |
| 404 | 647 | |
| 405 | | −/// Run until no actor is left. When the root exits, every other actor is |
| 406 | | −/// stopped (and unwound). Returns the root's exit. |
| 407 | | −fn run(sched: &RefCell<Sched>, root: i64) -> Exit { |
| 648 | +/// The number of scheduler threads: `TILC_THREADS`, or one per core. |
| 649 | +fn thread_count() -> usize { |
| 650 | + std::env::var("TILC_THREADS") |
| 651 | + .ok() |
| 652 | + .and_then(|n| n.parse().ok()) |
| 653 | + .filter(|&n| n > 0) |
| 654 | + .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, usize::from)) |
| 655 | +} |
| 656 | + |
| 657 | +/// Run until no actor is left, on `threads` threads (this one included). |
| 658 | +/// When the root exits, every other actor is stopped (and unwound). |
| 659 | +/// Returns the root's exit. |
| 660 | +fn run(sched: &Shared, root: i64, threads: usize) -> Exit { |
| 408 | 661 | { |
| 409 | | − let mut s = sched.borrow_mut(); |
| 662 | + let mut s = sched.lock(); |
| 410 | 663 | s.root = root; |
| 411 | | − s.poll = Some(mio::Poll::new().expect("tilrt: cannot create the reactor")); |
| 664 | + let poll = mio::Poll::new().expect("tilrt: cannot create the reactor"); |
| 665 | + s.registry = Some( |
| 666 | + poll.registry() |
| 667 | + .try_clone() |
| 668 | + .expect("tilrt: cannot share the reactor"), |
| 669 | + ); |
| 670 | + s.waker = Some(std::sync::Arc::new( |
| 671 | + mio::Waker::new(poll.registry(), WAKER).expect("tilrt: cannot create the waker"), |
| 672 | + )); |
| 673 | + s.poll = Some(poll); |
| 412 | 674 | } |
| 675 | + std::thread::scope(|scope| { |
| 676 | + for i in 1..threads { |
| 677 | + std::thread::Builder::new() |
| 678 | + .name(format!("tilrt-sched-{i}")) |
| 679 | + .spawn_scoped(scope, || worker(sched)) |
| 680 | + .expect("tilrt: cannot start a scheduler thread"); |
| 681 | + } |
| 682 | + worker(sched); |
| 683 | + }); |
| 684 | + sched.lock().outcome.take().unwrap_or(Exit::Normal) |
| 685 | +} |
| 686 | + |
| 687 | +/// One scheduler thread: run actors from the queue. When no actor can run |
| 688 | +/// on any thread, one thread waits for blocking calls, sockets or the next |
| 689 | +/// deadline, as the single-threaded scheduler did. |
| 690 | +fn worker(sched: &Shared) { |
| 691 | + let mut s = sched.lock(); |
| 413 | 692 | loop { |
| 414 | | − collect_blocking(sched, false); |
| 415 | | − if !sched.borrow().io_waiters.is_empty() { |
| 416 | | − poll_io(sched, Some(std::time::Duration::ZERO)); |
| 693 | + if s.finished { |
| 694 | + return; |
| 417 | 695 | } |
| 418 | | − let next = sched.borrow_mut().run_queue.pop_front(); |
| 419 | | − let Some(pid) = next else { |
| 420 | | − if sched.borrow().actors.is_empty() { |
| 421 | | − break; |
| 422 | | − } |
| 423 | | − let (io, blocking) = { |
| 424 | | − let s = sched.borrow(); |
| 425 | | − (!s.io_waiters.is_empty(), s.blocking > 0) |
| 426 | | − }; |
| 427 | | − if blocking && !io { |
| 428 | | − collect_blocking(sched, true); |
| 429 | | − continue; |
| 696 | + collect_blocking(&mut s); |
| 697 | + if !s.io_waiters.is_empty() { |
| 698 | + poll_io(&mut s); |
| 699 | + } |
| 700 | + if let Some(pid) = s.run_queue.pop_front() { |
| 701 | + s = run_slice(sched, s, pid); |
| 702 | + continue; |
| 703 | + } |
| 704 | + if s.actors.is_empty() { |
| 705 | + s.finished = true; |
| 706 | + s.notify = true; |
| 707 | + return; |
| 708 | + } |
| 709 | + if s.running > 0 || s.idling { |
| 710 | + // Another thread will queue work, or idle for everyone. |
| 711 | + s = s.wait(); |
| 712 | + continue; |
| 713 | + } |
| 714 | + s.idling = true; |
| 715 | + drop(s); |
| 716 | + idle(sched); |
| 717 | + s = sched.lock(); |
| 718 | + s.idling = false; |
| 719 | + s.notify = true; |
| 720 | + } |
| 721 | +} |
| 722 | + |
| 723 | +/// Resume `pid` for one slice, without holding the lock. |
| 724 | +fn run_slice<'a>(sched: &'a Shared, mut s: Locked<'a>, pid: i64) -> Locked<'a> { |
| 725 | + let Some(slot) = s.actors.get_mut(&pid) else { |
| 726 | + return s; |
| 727 | + }; |
| 728 | + let Some(mut fiber) = slot.fiber.take() else { |
| 729 | + return s; |
| 730 | + }; |
| 731 | + let a = slot.actor; |
| 732 | + s.running += 1; |
| 733 | + drop(s); |
| 734 | + // SAFETY: the actor is live and runs on this thread only. |
| 735 | + unsafe { (*a).ctx.reductions = REDUCTIONS }; |
| 736 | + let result = fiber.0.resume(()); |
| 737 | + let mut s = sched.lock(); |
| 738 | + s.running -= 1; |
| 739 | + if s.running == 0 { |
| 740 | + s.notify = true; // Someone may have to idle for everyone. |
| 741 | + } |
| 742 | + match result { |
| 743 | + CoroutineResult::Yield(()) => { |
| 744 | + let slot = s.actors.get_mut(&pid).expect("tilrt: actor vanished"); |
| 745 | + slot.fiber = Some(fiber); |
| 746 | + if slot.proc.wait == Wait::Ready { |
| 747 | + s.run_queue.push_back(pid); |
| 430 | 748 | } |
| 431 | | − if io { |
| 432 | | − // Real time passes while waiting for sockets; timers still |
| 433 | | − // fire when it reaches their deadline. |
| 434 | | − let deadline = next_deadline(sched); |
| 435 | | − let clock = sched.borrow().clock; |
| 436 | | − let timeout = match (blocking, deadline) { |
| 437 | | − (true, _) => Some(std::time::Duration::from_millis(1)), |
| 438 | | − (false, Some(d)) => { |
| 439 | | − Some(std::time::Duration::from_millis(d.saturating_sub(clock))) |
| 440 | | − } |
| 441 | | − (false, None) => None, |
| 442 | | − }; |
| 443 | | − let start = std::time::Instant::now(); |
| 444 | | − let woke = poll_io(sched, timeout); |
| 445 | | − sched.borrow_mut().clock += start.elapsed().as_millis() as u64; |
| 446 | | − collect_blocking(sched, false); |
| 447 | | − if !woke |
| 448 | | − && let Some(d) = deadline |
| 449 | | − && sched.borrow().clock >= d |
| 450 | | − { |
| 451 | | − advance_clock(sched); |
| 452 | | − } |
| 453 | | − continue; |
| 749 | + s |
| 750 | + } |
| 751 | + CoroutineResult::Return(()) => { |
| 752 | + let slot = s.actors.remove(&pid).expect("tilrt: actor vanished"); |
| 753 | + if fiber.1 == PROGRAM_STACK_SIZE && s.stacks.len() < STACK_POOL { |
| 754 | + let stack = fiber.0.into_stack(); |
| 755 | + s.stacks.push(stack); |
| 756 | + } else { |
| 757 | + drop(fiber); |
| 454 | 758 | } |
| 455 | | − if !advance_clock(sched) { |
| 456 | | − // Nothing can ever run again. |
| 457 | | − exit_actor( |
| 458 | | − sched, |
| 459 | | − root, |
| 460 | | − Exit::Crashed("deadlock: every actor is waiting for a message".into()), |
| 461 | | − ); |
| 462 | | − let alive: Vec<i64> = sched.borrow().actors.keys().copied().collect(); |
| 463 | | − for pid in alive { |
| 464 | | − exit_actor(sched, pid, Exit::Killed); |
| 465 | | − let mut s = sched.borrow_mut(); |
| 466 | | − if actor_of(&s, pid) |
| 467 | | − .is_some_and(|a| a.wait != Wait::Ready && a.wait != Wait::Blocking) |
| 468 | | − { |
| 469 | | − s.wake(pid, UNIT); |
| 759 | + // SAFETY: the fiber has returned; nothing refers to the actor. |
| 760 | + drop(unsafe { Box::from_raw(slot.actor) }); |
| 761 | + LIVE_ACTORS.fetch_sub(1, Ordering::Relaxed); |
| 762 | + if pid == s.root { |
| 763 | + // `main` stopped: stop everyone else, silently. |
| 764 | + let others: Vec<i64> = s.actors.keys().copied().collect(); |
| 765 | + for other in others { |
| 766 | + if let Some(p) = s.proc(other) { |
| 767 | + p.dead = true; |
| 470 | 768 | } |
| 769 | + s.request_kill(other); |
| 770 | + s.interrupt(other); |
| 471 | 771 | } |
| 472 | 772 | } |
| 473 | | − continue; |
| 474 | | − }; |
| 475 | | − let (a, mut fiber) = { |
| 476 | | − let mut s = sched.borrow_mut(); |
| 477 | | − let Some(slot) = s.actors.get_mut(&pid) else { |
| 478 | | − continue; |
| 479 | | − }; |
| 480 | | − let Some(fiber) = slot.fiber.take() else { |
| 481 | | − continue; |
| 482 | | − }; |
| 483 | | − (slot.actor, fiber) |
| 484 | | − }; |
| 485 | | − // SAFETY: the actor is live and not running. |
| 486 | | − unsafe { (*a).ctx.reductions = REDUCTIONS }; |
| 487 | | − match fiber.resume(()) { |
| 488 | | − CoroutineResult::Yield(()) => { |
| 489 | | − let mut s = sched.borrow_mut(); |
| 490 | | − s.actors.get_mut(&pid).expect("tilrt: actor vanished").fiber = Some(fiber); |
| 491 | | − // SAFETY: the actor is live. |
| 492 | | − if unsafe { (*a).wait } == Wait::Ready { |
| 493 | | − s.run_queue.push_back(pid); |
| 494 | | − } |
| 495 | | − } |
| 496 | | − CoroutineResult::Return(()) => { |
| 497 | | − let slot = sched |
| 498 | | − .borrow_mut() |
| 499 | | − .actors |
| 500 | | − .remove(&pid) |
| 501 | | − .expect("tilrt: actor vanished"); |
| 502 | | − // SAFETY: the fiber has returned; nothing refers to the actor. |
| 503 | | − drop(unsafe { Box::from_raw(slot.actor) }); |
| 504 | | − LIVE_ACTORS.fetch_sub(1, Ordering::Relaxed); |
| 505 | | − if pid == root { |
| 506 | | − // `main` stopped: stop everyone else, silently. |
| 507 | | − let others: Vec<i64> = sched.borrow().actors.keys().copied().collect(); |
| 508 | | − for other in others { |
| 509 | | − let mut s = sched.borrow_mut(); |
| 510 | | − if let Some(o) = actor_of(&s, other) { |
| 511 | | − o.dead = true; |
| 512 | | − o.kill_requested = true; |
| 513 | | − if o.wait != Wait::Ready && o.wait != Wait::Blocking { |
| 514 | | − s.wake(other, UNIT); |
| 515 | | − } |
| 516 | | − } |
| 517 | | − } |
| 518 | | − } |
| 773 | + s.notify = true; |
| 774 | + s |
| 775 | + } |
| 776 | + } |
| 777 | +} |
| 778 | + |
| 779 | +/// Every actor waits: wait for blocking calls, sockets or the clock, or |
| 780 | +/// detect a deadlock. Called by one thread at a time, without the lock. |
| 781 | +/// |
| 782 | +/// Each decision is taken under one lock, and the thread stops idling as |
| 783 | +/// soon as an actor runs or is queued (another thread may have polled the |
| 784 | +/// reactor meanwhile). Blocking calls signal the reactor when they finish |
| 785 | +/// (`WAKER`), so the reactor is the only thing waited on. |
| 786 | +fn idle(sched: &Shared) { |
| 787 | + let (mut poll, real_time, clock, deadline) = { |
| 788 | + let mut s = sched.lock(); |
| 789 | + collect_blocking(&mut s); |
| 790 | + if s.running > 0 || !s.run_queue.is_empty() { |
| 791 | + return; |
| 792 | + } |
| 793 | + if s.io_waiters.is_empty() && s.blocking == 0 { |
| 794 | + // Only the clock can wake an actor now. |
| 795 | + if !advance_clock(&mut s) { |
| 796 | + deadlock(sched, s); |
| 519 | 797 | } |
| 798 | + return; |
| 520 | 799 | } |
| 800 | + let Some(poll) = s.poll.take() else { |
| 801 | + return; |
| 802 | + }; |
| 803 | + // Real time passes while waiting for sockets, and timers fire when |
| 804 | + // it reaches their deadline. Waiting only for blocking calls keeps |
| 805 | + // the clock virtual. |
| 806 | + let real_time = !s.io_waiters.is_empty(); |
| 807 | + (poll, real_time, s.clock, next_deadline(&s)) |
| 808 | + }; |
| 809 | + let timeout = match deadline { |
| 810 | + Some(d) if real_time => Some(std::time::Duration::from_millis(d.saturating_sub(clock))), |
| 811 | + _ => None, |
| 812 | + }; |
| 813 | + let start = std::time::Instant::now(); |
| 814 | + let mut events = mio::Events::with_capacity(256); |
| 815 | + wait_events(&mut poll, &mut events, timeout); |
| 816 | + let mut s = sched.lock(); |
| 817 | + s.poll = Some(poll); |
| 818 | + if real_time { |
| 819 | + s.clock += start.elapsed().as_millis() as u64; |
| 820 | + } |
| 821 | + let woke = wake_io(&mut s, &events); |
| 822 | + collect_blocking(&mut s); |
| 823 | + if real_time |
| 824 | + && !woke |
| 825 | + && let Some(d) = deadline |
| 826 | + && s.clock >= d |
| 827 | + { |
| 828 | + advance_clock(&mut s); |
| 829 | + } |
| 830 | +} |
| 831 | + |
| 832 | +/// Nothing can ever run again: crash the root (stopping everyone). |
| 833 | +fn deadlock(sched: &Shared, s: Locked<'_>) { |
| 834 | + let root = s.root; |
| 835 | + let alive: Vec<i64> = s.actors.keys().copied().collect(); |
| 836 | + drop(s); |
| 837 | + exit_actor( |
| 838 | + sched, |
| 839 | + root, |
| 840 | + Exit::Crashed("deadlock: every actor is waiting for a message".into()), |
| 841 | + ); |
| 842 | + for pid in alive { |
| 843 | + exit_actor(sched, pid, Exit::Killed); |
| 844 | + sched.lock().interrupt(pid); |
| 521 | 845 | } |
| 522 | | − sched.borrow_mut().outcome.take().unwrap_or(Exit::Normal) |
| 523 | 846 | } |
| 524 | 847 | |
| 525 | | −/// Wake the actors whose blocking calls finished (waiting for one if |
| 526 | | −/// `wait`). |
| 527 | | −fn collect_blocking(sched: &RefCell<Sched>, wait: bool) { |
| 528 | | − if sched.borrow().blocking == 0 { |
| 848 | +/// Wake the actors whose blocking calls finished. |
| 849 | +fn collect_blocking(s: &mut Sched) { |
| 850 | + if s.blocking == 0 { |
| 529 | 851 | return; |
| 530 | 852 | } |
| 531 | | − let mut first = wait; |
| 532 | | − while let Some(done) = crate::blocking::finished(first) { |
| 533 | | − first = false; |
| 534 | | − let mut s = sched.borrow_mut(); |
| 853 | + while let Some(done) = crate::blocking::finished() { |
| 535 | 854 | s.blocking -= 1; |
| 536 | 855 | s.wake(done.pid, done.result); |
| 537 | 856 | } |
| 538 | 857 | } |
| 539 | 858 | |
| 540 | | −/// Wait up to `timeout` (forever if `None`) for socket events and wake the |
| 541 | | −/// actors parked on them. Returns whether any actor woke. |
| 542 | | −fn poll_io(sched: &RefCell<Sched>, timeout: Option<std::time::Duration>) -> bool { |
| 859 | +/// Wake the actors whose sockets are ready, without waiting. Skipped while |
| 860 | +/// an idle thread holds the reactor. |
| 861 | +fn poll_io(s: &mut Sched) { |
| 862 | + let Some(mut poll) = s.poll.take() else { |
| 863 | + return; |
| 864 | + }; |
| 543 | 865 | let mut events = mio::Events::with_capacity(256); |
| 866 | + wait_events(&mut poll, &mut events, Some(std::time::Duration::ZERO)); |
| 867 | + s.poll = Some(poll); |
| 868 | + wake_io(s, &events); |
| 869 | +} |
| 870 | + |
| 871 | +fn wait_events( |
| 872 | + poll: &mut mio::Poll, |
| 873 | + events: &mut mio::Events, |
| 874 | + timeout: Option<std::time::Duration>, |
| 875 | +) { |
| 876 | + if let Err(e) = poll.poll(events, timeout) |
| 877 | + && e.kind() != std::io::ErrorKind::Interrupted |
| 544 | 878 | { |
| 545 | | − let mut s = sched.borrow_mut(); |
| 546 | | − let poll = s.poll.as_mut().expect("tilrt: reactor"); |
| 547 | | − if let Err(e) = poll.poll(&mut events, timeout) |
| 548 | | − && e.kind() != std::io::ErrorKind::Interrupted |
| 549 | | − { |
| 550 | | − panic!("tilrt: reactor failed: {e}"); |
| 551 | | − } |
| 879 | + panic!("tilrt: reactor failed: {e}"); |
| 552 | 880 | } |
| 881 | +} |
| 882 | + |
| 883 | +/// Wake the actors parked on `events`; returns whether any woke. |
| 884 | +fn wake_io(s: &mut Sched, events: &mio::Events) -> bool { |
| 553 | 885 | let mut woke = false; |
| 554 | | − let mut s = sched.borrow_mut(); |
| 555 | | − for event in &events { |
| 886 | + for event in events { |
| 887 | + if event.token() == WAKER { |
| 888 | + continue; // A blocking call finished: see `collect_blocking`. |
| 889 | + } |
| 556 | 890 | if let Some(pid) = s.io_waiters.remove(&event.token()) { |
| 557 | 891 | s.wake(pid, UNIT); |
| 558 | 892 | woke = true; |
| 893 | + } else { |
| 894 | + s.io_ready.insert(event.token()); |
| 559 | 895 | } |
| 560 | 896 | } |
| 561 | 897 | woke |
| 562 | 898 | } |
| 563 | 899 | |
| 564 | | −fn next_deadline(sched: &RefCell<Sched>) -> Option<u64> { |
| 565 | | − let s = sched.borrow(); |
| 566 | | − s.actors |
| 567 | | − .values() |
| 568 | | − // SAFETY: slots only hold live actors. |
| 569 | | − .filter_map(|slot| match unsafe { &*slot.actor }.wait { |
| 570 | | − Wait::Receive { |
| 571 | | − deadline: Some(d), .. |
| 572 | | − } |
| 573 | | − | Wait::Sleep { deadline: d } => Some(d), |
| 574 | | − _ => None, |
| 575 | | − }) |
| 576 | | − .min() |
| 577 | | −} |
| 578 | | − |
| 579 | | −/// Jump the virtual clock to the next deadline and wake those actors. |
| 580 | | −fn advance_clock(sched: &RefCell<Sched>) -> bool { |
| 581 | | − let mut s = sched.borrow_mut(); |
| 582 | | − let deadline = |a: &Actor| match a.wait { |
| 900 | +fn deadline_of(p: &Proc) -> Option<u64> { |
| 901 | + match p.wait { |
| 583 | 902 | Wait::Receive { |
| 584 | 903 | deadline: Some(d), .. |
| 585 | 904 | } |
| 586 | 905 | | Wait::Sleep { deadline: d } => Some(d), |
| 587 | 906 | _ => None, |
| 588 | | − }; |
| 589 | | − let Some(next) = s |
| 590 | | − .actors |
| 907 | + } |
| 908 | +} |
| 909 | + |
| 910 | +fn next_deadline(s: &Sched) -> Option<u64> { |
| 911 | + s.actors |
| 591 | 912 | .values() |
| 592 | | − // SAFETY: slots only hold live actors. |
| 593 | | − .filter_map(|slot| deadline(unsafe { &*slot.actor })) |
| 913 | + .filter_map(|slot| deadline_of(&slot.proc)) |
| 594 | 914 | .min() |
| 595 | | − else { |
| 915 | +} |
| 916 | + |
| 917 | +/// Jump the virtual clock to the next deadline and wake those actors. |
| 918 | +fn advance_clock(s: &mut Sched) -> bool { |
| 919 | + let Some(next) = next_deadline(s) else { |
| 596 | 920 | return false; |
| 597 | 921 | }; |
| 598 | 922 | s.clock = s.clock.max(next); |
| 599 | 923 | let mut due: Vec<i64> = s |
| 600 | 924 | .actors |
| 601 | 925 | .iter() |
| 602 | | − // SAFETY: slots only hold live actors. |
| 603 | | − .filter(|(_, slot)| deadline(unsafe { &*slot.actor }) == Some(next)) |
| 926 | + .filter(|(_, slot)| deadline_of(&slot.proc) == Some(next)) |
| 604 | 927 | .map(|(p, _)| *p) |
| 605 | 928 | .collect(); |
| 606 | 929 | due.sort(); |
| 607 | 930 | for pid in due { |
| 608 | | − let a = actor_of(&s, pid).expect("listed"); |
| 609 | 931 | // A receive that timed out returns `None` (constructor 0). |
| 610 | | − let wake = match a.wait { |
| 932 | + let wake = match s.proc(pid).expect("listed").wait { |
| 611 | 933 | Wait::Sleep { .. } => UNIT, |
| 612 | 934 | _ => int(0), |
| 613 | 935 | }; |
| @@ -642,15 +964,15 @@ pub(crate) unsafe fn preempt_root(ctx: *mut Ctx) { |
| 642 | 964 | let a = actor(ctx); |
| 643 | 965 | (*ctx).reductions = REDUCTIONS; |
| 644 | 966 | (*(*a).yielder).suspend(()); |
| 645 | | − if (*a).kill_requested && (*ctx).yielding == YIELD_NONE { |
| 967 | + if (*a).kill_requested() && (*ctx).yielding == YIELD_NONE { |
| 646 | 968 | (*ctx).yielding = YIELD_KILL; |
| 647 | 969 | } |
| 648 | 970 | } |
| 649 | 971 | } |
| 650 | 972 | |
| 651 | | −/// Park the running actor until it is woken (its `wait` must be set); |
| 652 | | −/// returns the wake value, or unit with `yielding = KILL` if it exited |
| 653 | | −/// meanwhile. |
| 973 | +/// Park the running actor until it is woken (its `wait` must be set, |
| 974 | +/// under the lock, before calling); returns the wake value, or unit with |
| 975 | +/// `yielding = KILL` if it exited meanwhile. |
| 654 | 976 | /// |
| 655 | 977 | /// # Safety |
| 656 | 978 | /// `ctx` must be the running actor's context. |
| @@ -658,8 +980,12 @@ pub(crate) unsafe fn park(ctx: *mut Ctx) -> Value { |
| 658 | 980 | // SAFETY: forwarded caller guarantee. |
| 659 | 981 | unsafe { |
| 660 | 982 | tl_preempt(ctx); |
| 661 | | − let a = actor(ctx); |
| 662 | | − let wake = std::mem::replace(&mut (*a).wake, UNIT); |
| 983 | + let (a, sched) = this(ctx); |
| 984 | + let wake = { |
| 985 | + let mut s = sched.lock(); |
| 986 | + let p = s.proc(a.pid).expect("tilrt: running actor vanished"); |
| 987 | + std::mem::replace(&mut p.wake, UNIT) |
| 988 | + }; |
| 663 | 989 | if (*ctx).yielding != YIELD_NONE { |
| 664 | 990 | drop_value(ctx, wake); |
| 665 | 991 | return UNIT; |
| @@ -677,8 +1003,8 @@ pub(crate) unsafe fn park(ctx: *mut Ctx) -> Value { |
| 677 | 1003 | #[unsafe(no_mangle)] |
| 678 | 1004 | pub unsafe extern "C" fn tl_spawn(ctx: *mut Ctx, closure: Value) -> Value { |
| 679 | 1005 | // SAFETY: caller guarantees a running actor. |
| 680 | | − let sched = unsafe { &*(*actor(ctx)).sched }; |
| 681 | | − int(spawn_actor(sched, Body::Closure(closure), STACK_SIZE)) |
| 1006 | + let (_, sched) = unsafe { this(ctx) }; |
| 1007 | + int(spawn_actor(sched, Body::Closure(closure), STACK_SIZE, None, Tie::None).0) |
| 682 | 1008 | } |
| 683 | 1009 | |
| 684 | 1010 | /// Ask actor `pid` to exit. It unwinds at its next safe point. Unknown or |
| @@ -689,7 +1015,7 @@ pub unsafe extern "C" fn tl_spawn(ctx: *mut Ctx, closure: Value) -> Value { |
| 689 | 1015 | #[unsafe(no_mangle)] |
| 690 | 1016 | pub unsafe extern "C" fn tl_kill(ctx: *mut Ctx, pid: Value) { |
| 691 | 1017 | // SAFETY: caller guarantees a running actor. |
| 692 | | − let sched = unsafe { &*(*actor(ctx)).sched }; |
| 1018 | + let (_, sched) = unsafe { this(ctx) }; |
| 693 | 1019 | exit_actor(sched, int_get(pid), Exit::Killed); |
| 694 | 1020 | } |
| 695 | 1021 | |
| @@ -704,9 +1030,9 @@ pub extern "C" fn tl_actor_count() -> i64 { |
| 704 | 1030 | /// `entry` must follow the generated-code calling convention. |
| 705 | 1031 | #[unsafe(no_mangle)] |
| 706 | 1032 | pub unsafe extern "C" fn tl_main(entry: EntryFn) -> i32 { |
| 707 | | − let sched = RefCell::new(Sched::default()); |
| 708 | | − let root = spawn_actor(&sched, Body::Entry(entry), ROOT_STACK_SIZE); |
| 709 | | − match run(&sched, root) { |
| 1033 | + let sched = Shared::new(); |
| 1034 | + let (root, _) = spawn_actor(&sched, Body::Entry(entry), ROOT_STACK_SIZE, None, Tie::None); |
| 1035 | + match run(&sched, root, thread_count()) { |
| 710 | 1036 | Exit::Normal => 0, |
| 711 | 1037 | _ => 1, |
| 712 | 1038 | } |
| @@ -721,10 +1047,10 @@ pub unsafe extern "C" fn tl_main(entry: EntryFn) -> i32 { |
| 721 | 1047 | #[unsafe(no_mangle)] |
| 722 | 1048 | pub unsafe extern "C" fn tl_main_program(entry: EntryFn) -> i32 { |
| 723 | 1049 | PROGRAM_MODE.store(true, Ordering::Relaxed); |
| 724 | | − let sched = RefCell::new(Sched::default()); |
| 725 | | − let root = spawn_actor(&sched, Body::Entry(entry), ROOT_STACK_SIZE); |
| 726 | | − match run(&sched, root) { |
| 727 | | − Exit::Normal | Exit::Running => 0, |
| 1050 | + let sched = Shared::new(); |
| 1051 | + let (root, _) = spawn_actor(&sched, Body::Entry(entry), ROOT_STACK_SIZE, None, Tie::None); |
| 1052 | + match run(&sched, root, thread_count()) { |
| 1053 | + Exit::Normal => 0, |
| 728 | 1054 | Exit::Crashed(message) => { |
| 729 | 1055 | eprintln!("error: panic: {message}"); |
| 730 | 1056 | 101 |