| @@ -12,19 +12,23 @@ |
| 12 | 12 | //! them an `ExitSignal` if they trap exits; monitors receive `Down`; |
| 13 | 13 | //! - when `main` stops, the other actors are stopped. |
| 14 | 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). |
| 15 | +//! **Threads** (ADR 0004, Revision 2). `TILC_THREADS` scheduler threads |
| 16 | +//! (default: one per core) each have a FIFO run queue; a thread with |
| 17 | +//! nothing to do steals from the shared queue, then from the others. An |
| 18 | +//! actor may run on a different thread after each suspension. With |
| 19 | +//! `TILC_THREADS=1` there is one queue, the order is the interpreter's, |
| 20 | +//! and `tests/run` outputs are reproducible. Messages are made |
| 21 | +//! thread-safe when sent (`send`: move, share or copy). |
| 20 | 22 | //! |
| 21 | 23 | //! **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 |
| 24 | +//! mailbox, links, monitors, the wait state: [`Proc`]) is behind the |
| 25 | +//! actor's own lock, in its [`Cell`]. An [`Actor`] holds what only the |
| 26 | +//! thread running it touches (its context, drop worklist, yielders). A |
| 25 | 27 | //! wake-up queues an actor only if it is suspended; if it is still on its |
| 26 | 28 | //! way to suspending, the thread running it queues it when it yields, so |
| 27 | | −//! no wake-up is lost or doubled. |
| 29 | +//! no wake-up is lost or doubled (`handoff::RunState`). Timers, sockets |
| 30 | +//! and blocking calls are behind one control lock, taken off the hot |
| 31 | +//! paths of sending, receiving and scheduling. |
| 28 | 32 | //! |
| 29 | 33 | //! **Logical exit and unwinding are separate.** An actor exits (monitors |
| 30 | 34 | //! and links are notified) the moment it is killed, as in the interpreter. |
| @@ -32,14 +36,18 @@ |
| 32 | 36 | //! A fiber is never dropped while suspended, because its frames would |
| 33 | 37 | //! never release what they hold. |
| 34 | 38 | //! |
| 35 | | −//! Invariant: the scheduler lock is never held while actor code runs, and |
| 36 | | −//! never taken twice by one thread. |
| 39 | +//! Invariant: no scheduler lock is held while actor code runs. |
| 37 | 40 | |
| 38 | | −use std::collections::{HashMap, HashSet, VecDeque}; |
| 39 | | −use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; |
| 40 | | −use std::sync::{Condvar, Mutex, MutexGuard}; |
| 41 | +use std::cell::RefCell; |
| 42 | +use std::cmp::Reverse; |
| 43 | +use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque}; |
| 44 | +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}; |
| 45 | +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLock}; |
| 46 | + |
| 47 | +use crossbeam_deque::{Injector, Steal, Stealer, Worker}; |
| 41 | 48 | |
| 42 | 49 | use crate::fiber::{Coroutine, CoroutineResult, Stack, Yielder}; |
| 50 | +use crate::handoff::{RunState, Sleepers}; |
| 43 | 51 | |
| 44 | 52 | use crate::abi::{ |
| 45 | 53 | Ctx, UNIT, Value, YIELD_FINAL, YIELD_KILL, YIELD_NONE, YIELD_PANIC, int, int_get, |
| @@ -118,25 +126,25 @@ pub(crate) enum Wait { |
| 118 | 126 | Io, |
| 119 | 127 | } |
| 120 | 128 | |
| 121 | | −/// What only the thread running the actor touches, plus the kill flag. |
| 129 | +/// What only the thread running the actor touches. |
| 122 | 130 | pub struct Actor { |
| 123 | 131 | ctx: Ctx, |
| 124 | 132 | pub(crate) pid: i64, |
| 125 | 133 | next_marker: u64, |
| 126 | | − /// Set (under the scheduler lock) when the actor exits; read by the |
| 127 | | − /// actor at its safe points. |
| 128 | | − kill_requested: AtomicBool, |
| 129 | 134 | drops: DropStack, |
| 130 | 135 | yielder: *const Yielder<(), ()>, |
| 131 | 136 | /// The `ctl` handler fiber running now, or null on the actor's own |
| 132 | 137 | /// stack (see `handlers`). |
| 133 | 138 | handler: *const crate::handlers::HandlerYielder, |
| 134 | 139 | sched: *const Shared, |
| 140 | + /// Its shared half (the table keeps it alive while the actor lives). |
| 141 | + cell: *const Cell, |
| 135 | 142 | } |
| 136 | 143 | |
| 137 | 144 | impl Actor { |
| 138 | 145 | pub(crate) fn kill_requested(&self) -> bool { |
| 139 | | − self.kill_requested.load(Ordering::Acquire) |
| 146 | + // SAFETY: the cell outlives the actor's fiber. |
| 147 | + unsafe { (*self.cell).kill.load(Ordering::Acquire) } |
| 140 | 148 | } |
| 141 | 149 | } |
| 142 | 150 | |
| @@ -182,135 +190,155 @@ impl Mailbox { |
| 182 | 190 | } |
| 183 | 191 | } |
| 184 | 192 | |
| 185 | | −/// An actor's OTP state, which other actors read and write (under the |
| 186 | | −/// scheduler lock). |
| 193 | +/// An actor's OTP state, which other actors read and write under the |
| 194 | +/// actor's lock. |
| 187 | 195 | pub(crate) struct Proc { |
| 188 | 196 | pub(crate) mailbox: Mailbox, |
| 189 | 197 | pub(crate) wait: Wait, |
| 190 | 198 | /// What a parked operation returns when woken. |
| 191 | 199 | pub(crate) wake: Value, |
| 192 | 200 | pub(crate) links: Vec<i64>, |
| 201 | + /// (watcher, tag): who receives `Down` when this actor exits. |
| 202 | + pub(crate) monitors: Vec<(i64, i64)>, |
| 193 | 203 | pub(crate) trap: bool, |
| 194 | 204 | pub(crate) exits_tag: Option<i64>, |
| 195 | 205 | /// While `wait` is `Receive`: the tags waited on, and whether the |
| 196 | 206 | /// answer carries the tag (`receive_any`). |
| 197 | 207 | pub(crate) waiting_tags: Vec<i64>, |
| 198 | 208 | pub(crate) waiting_any: bool, |
| 209 | + /// Counts waits, so a timer set for an earlier one is ignored. |
| 210 | + wait_gen: u64, |
| 199 | 211 | /// Exited (logically); its fiber may still have to unwind. |
| 200 | 212 | pub(crate) dead: bool, |
| 213 | + run: RunState<Fiber>, |
| 214 | +} |
| 215 | + |
| 216 | +impl Proc { |
| 217 | + /// Make the actor ready; its parked operation returns `value`. |
| 218 | + /// Returns whether the caller must [`Shared::schedule`] it (after |
| 219 | + /// releasing the lock). |
| 220 | + pub(crate) fn wake(&mut self, value: Value) -> bool { |
| 221 | + self.wait = Wait::Ready; |
| 222 | + self.wake = value; |
| 223 | + self.run.wake() |
| 224 | + } |
| 225 | + |
| 226 | + /// Wake it unless it is ready or in a blocking call. |
| 227 | + fn interrupt(&mut self) -> bool { |
| 228 | + if self.wait != Wait::Ready && self.wait != Wait::Blocking { |
| 229 | + return self.wake(UNIT); |
| 230 | + } |
| 231 | + false |
| 232 | + } |
| 233 | + |
| 234 | + /// Start waiting as `wait`; returns the wait's number, for its timer. |
| 235 | + pub(crate) fn park_as(&mut self, wait: Wait) -> u64 { |
| 236 | + self.wait_gen += 1; |
| 237 | + self.wait = wait; |
| 238 | + self.wait_gen |
| 239 | + } |
| 240 | + |
| 241 | + fn deadline(&self) -> Option<u64> { |
| 242 | + match self.wait { |
| 243 | + Wait::Receive { |
| 244 | + deadline: Some(d), .. |
| 245 | + } |
| 246 | + | Wait::Sleep { deadline: d } => Some(d), |
| 247 | + _ => None, |
| 248 | + } |
| 249 | + } |
| 201 | 250 | } |
| 202 | 251 | |
| 203 | | −struct Slot { |
| 252 | +/// An actor's shared half. |
| 253 | +pub(crate) struct Cell { |
| 204 | 254 | actor: *mut Actor, |
| 205 | | − /// `None` while the fiber is running. |
| 206 | | − fiber: Option<Fiber>, |
| 207 | | − proc: Proc, |
| 255 | + /// Set when the actor exits; read by the actor at its safe points. |
| 256 | + kill: AtomicBool, |
| 257 | + proc: Mutex<Proc>, |
| 208 | 258 | } |
| 209 | 259 | |
| 260 | +// SAFETY: `actor` is dereferenced only by the thread running the actor |
| 261 | +// (and freed after its fiber returned); the rest is atomic or locked. |
| 262 | +unsafe impl Send for Cell {} |
| 263 | +// SAFETY: as above. |
| 264 | +unsafe impl Sync for Cell {} |
| 265 | + |
| 266 | +/// What the control lock guards: the clock's timers, sockets, blocking |
| 267 | +/// calls, and the end of the program. |
| 210 | 268 | #[derive(Default)] |
| 211 | | −pub(crate) struct Sched { |
| 212 | | − actors: HashMap<i64, Slot>, |
| 213 | | − run_queue: VecDeque<i64>, |
| 214 | | − next_pid: i64, |
| 215 | | − pub(crate) next_tag: i64, |
| 216 | | − pub(crate) clock: u64, |
| 217 | | − /// (watched, watcher, tag) |
| 218 | | − pub(crate) monitors: Vec<(i64, i64, i64)>, |
| 219 | | − root: i64, |
| 269 | +struct Control { |
| 270 | + /// (deadline, pid, wait number), soonest first, then by pid (due |
| 271 | + /// actors wake in pid order, as in the interpreter). |
| 272 | + timers: BinaryHeap<Reverse<(u64, i64, u64)>>, |
| 220 | 273 | outcome: Option<Exit>, |
| 221 | 274 | /// Calls running on the blocking pool. |
| 222 | | − pub(crate) blocking: usize, |
| 275 | + blocking: usize, |
| 223 | 276 | /// The reactor for sockets. Taken out while a thread waits on it. |
| 224 | 277 | poll: Option<mio::Poll>, |
| 225 | 278 | registry: Option<mio::Registry>, |
| 226 | | − /// Wakes the reactor when a blocking call finishes. |
| 227 | | − pub(crate) waker: Option<std::sync::Arc<mio::Waker>>, |
| 228 | 279 | next_token: usize, |
| 229 | 280 | /// Actors parked on a socket, by its token. |
| 230 | | − pub(crate) io_waiters: HashMap<mio::Token, i64>, |
| 281 | + io_waiters: HashMap<mio::Token, i64>, |
| 231 | 282 | /// Sockets that became ready while no actor waited on them. Events are |
| 232 | 283 | /// edge-triggered, and another thread may poll between an actor's |
| 233 | 284 | /// `WouldBlock` and its parking: the actor then retries instead. |
| 234 | | − pub(crate) io_ready: HashSet<mio::Token>, |
| 235 | | − /// Actors running now (one per busy thread). |
| 236 | | − running: usize, |
| 237 | | − /// A thread is waiting for the blocking pool, sockets or the clock. |
| 238 | | − idling: bool, |
| 239 | | − /// Every actor is gone: the threads stop. |
| 240 | | − finished: bool, |
| 285 | + io_ready: HashSet<mio::Token>, |
| 241 | 286 | /// Stacks of `PROGRAM_STACK_SIZE` whose fibers finished. |
| 242 | 287 | stacks: Vec<Stack>, |
| 243 | | − /// Work was queued: wake the waiting threads when the lock is released. |
| 244 | | − notify: bool, |
| 245 | 288 | } |
| 246 | 289 | |
| 247 | | −// SAFETY: the raw pointers in `Slot` are only dereferenced under the |
| 248 | | −// scheduler lock, or by the one thread running that actor; `Value`s in |
| 249 | | −// mailboxes are made thread-safe by `send::transfer`. |
| 250 | | −unsafe impl Send for Sched {} |
| 251 | | − |
| 252 | | −/// The scheduler state shared by the threads. |
| 290 | +/// The scheduler, shared by its threads. |
| 291 | +/// |
| 292 | +/// **Lock order:** the actor table, then `control`, then an actor's |
| 293 | +/// `proc` lock, then the sleepers' lock. A thread holding one never takes |
| 294 | +/// an earlier one, and holds at most one actor lock. |
| 253 | 295 | pub(crate) struct Shared { |
| 254 | | − state: Mutex<Sched>, |
| 255 | | − /// Signalled when work is queued, a thread stops idling, or the last |
| 256 | | − /// actor finished. |
| 257 | | − work: Condvar, |
| 296 | + actors: RwLock<HashMap<i64, Arc<Cell>>>, |
| 297 | + next_pid: AtomicI64, |
| 298 | + next_tag: AtomicI64, |
| 299 | + /// Virtual time in milliseconds (written under `control`). |
| 300 | + clock: AtomicU64, |
| 301 | + root: AtomicI64, |
| 302 | + control: Mutex<Control>, |
| 303 | + /// Run queues: one per thread (in `LOCAL`), plus this one for actors |
| 304 | + /// queued by other threads (the first actor). |
| 305 | + injector: Injector<i64>, |
| 306 | + stealers: OnceLock<Vec<Stealer<i64>>>, |
| 307 | + /// Actors in a run queue, and actors running. |
| 308 | + pending: AtomicUsize, |
| 309 | + running: AtomicUsize, |
| 310 | + /// A thread is waiting for the blocking pool, sockets or the clock. |
| 311 | + idling: AtomicBool, |
| 312 | + /// Every actor is gone: the threads stop. |
| 313 | + finished: AtomicBool, |
| 314 | + sleepers: Sleepers, |
| 315 | + /// Interrupts the idle thread's wait on the reactor. |
| 316 | + waker: OnceLock<Arc<mio::Waker>>, |
| 317 | + io_waiting: AtomicUsize, |
| 318 | + blocking: AtomicUsize, |
| 258 | 319 | } |
| 259 | 320 | |
| 260 | | −/// The locked scheduler. Releasing it wakes the waiting threads if work |
| 261 | | −/// was queued meanwhile. |
| 262 | | −pub(crate) struct Locked<'a> { |
| 263 | | − guard: Option<MutexGuard<'a, Sched>>, |
| 264 | | − work: &'a Condvar, |
| 321 | +thread_local! { |
| 322 | + /// This scheduler thread's run queue, and its scheduler's address. |
| 323 | + /// Only touched briefly (never held across a fiber switch). |
| 324 | + static LOCAL: RefCell<Option<(usize, Worker<i64>)>> = const { RefCell::new(None) }; |
| 265 | 325 | } |
| 266 | 326 | |
| 267 | | −impl Shared { |
| 268 | | − fn new() -> Shared { |
| 269 | | − Shared { |
| 270 | | − state: Mutex::new(Sched::default()), |
| 271 | | − work: Condvar::new(), |
| 272 | | − } |
| 273 | | − } |
| 274 | | − |
| 275 | | − pub(crate) fn lock(&self) -> Locked<'_> { |
| 276 | | − Locked { |
| 277 | | − guard: Some(self.state.lock().expect("tilrt: scheduler poisoned")), |
| 278 | | − work: &self.work, |
| 327 | +/// Push to this thread's queue if it is one of `sched`'s threads. |
| 328 | +#[inline(never)] |
| 329 | +fn push_local(sched: &Shared, pid: i64) -> bool { |
| 330 | + LOCAL.with(|l| match &*l.borrow() { |
| 331 | + Some((owner, w)) if *owner == sched as *const Shared as usize => { |
| 332 | + w.push(pid); |
| 333 | + true |
| 279 | 334 | } |
| 280 | | − } |
| 281 | | −} |
| 282 | | − |
| 283 | | −impl Locked<'_> { |
| 284 | | − /// Release the lock until another thread signals work. |
| 285 | | − fn wait(mut self) -> Self { |
| 286 | | − let guard = self.guard.take().expect("locked"); |
| 287 | | − let guard = self.work.wait(guard).expect("tilrt: scheduler poisoned"); |
| 288 | | − self.guard = Some(guard); |
| 289 | | − self |
| 290 | | − } |
| 291 | | −} |
| 292 | | − |
| 293 | | −impl std::ops::Deref for Locked<'_> { |
| 294 | | − type Target = Sched; |
| 295 | | − fn deref(&self) -> &Sched { |
| 296 | | − self.guard.as_ref().expect("locked") |
| 297 | | − } |
| 335 | + _ => false, |
| 336 | + }) |
| 298 | 337 | } |
| 299 | 338 | |
| 300 | | −impl std::ops::DerefMut for Locked<'_> { |
| 301 | | − fn deref_mut(&mut self) -> &mut Sched { |
| 302 | | − self.guard.as_mut().expect("locked") |
| 303 | | − } |
| 304 | | −} |
| 305 | | − |
| 306 | | −impl Drop for Locked<'_> { |
| 307 | | − fn drop(&mut self) { |
| 308 | | − if let Some(guard) = &mut self.guard |
| 309 | | − && std::mem::take(&mut guard.notify) |
| 310 | | − { |
| 311 | | − self.work.notify_all(); |
| 312 | | − } |
| 313 | | − } |
| 339 | +#[inline(never)] |
| 340 | +fn pop_local() -> Option<i64> { |
| 341 | + LOCAL.with(|l| l.borrow().as_ref().and_then(|(_, w)| w.pop())) |
| 314 | 342 | } |
| 315 | 343 | |
| 316 | 344 | /// # Safety |
| @@ -361,70 +389,159 @@ pub(crate) unsafe fn this<'a>(ctx: *mut Ctx) -> (&'a Actor, &'a Shared) { |
| 361 | 389 | } |
| 362 | 390 | } |
| 363 | 391 | |
| 364 | | −impl Sched { |
| 365 | | − pub(crate) fn tag(&mut self) -> i64 { |
| 366 | | − self.next_tag += 1; |
| 367 | | − self.next_tag |
| 392 | +impl Shared { |
| 393 | + fn new() -> Shared { |
| 394 | + Shared { |
| 395 | + actors: RwLock::new(HashMap::new()), |
| 396 | + next_pid: AtomicI64::new(0), |
| 397 | + next_tag: AtomicI64::new(0), |
| 398 | + clock: AtomicU64::new(0), |
| 399 | + root: AtomicI64::new(-1), |
| 400 | + control: Mutex::new(Control::default()), |
| 401 | + injector: Injector::new(), |
| 402 | + stealers: OnceLock::new(), |
| 403 | + pending: AtomicUsize::new(0), |
| 404 | + running: AtomicUsize::new(0), |
| 405 | + idling: AtomicBool::new(false), |
| 406 | + finished: AtomicBool::new(false), |
| 407 | + sleepers: Sleepers::new(), |
| 408 | + waker: OnceLock::new(), |
| 409 | + io_waiting: AtomicUsize::new(0), |
| 410 | + blocking: AtomicUsize::new(0), |
| 411 | + } |
| 368 | 412 | } |
| 369 | 413 | |
| 370 | | − /// The OTP state of actor `pid`, if its fiber has not finished. |
| 371 | | − pub(crate) fn proc(&mut self, pid: i64) -> Option<&mut Proc> { |
| 372 | | − self.actors.get_mut(&pid).map(|slot| &mut slot.proc) |
| 414 | + fn control(&self) -> MutexGuard<'_, Control> { |
| 415 | + self.control.lock().expect("tilrt: scheduler poisoned") |
| 373 | 416 | } |
| 374 | 417 | |
| 375 | | − /// The OTP state of actor `pid`, if it is alive (not exited). |
| 376 | | − pub(crate) fn alive(&mut self, pid: i64) -> Option<&mut Proc> { |
| 377 | | − self.proc(pid).filter(|p| !p.dead) |
| 418 | + fn cell(&self, pid: i64) -> Option<Arc<Cell>> { |
| 419 | + self.actors |
| 420 | + .read() |
| 421 | + .expect("tilrt: scheduler poisoned") |
| 422 | + .get(&pid) |
| 423 | + .cloned() |
| 378 | 424 | } |
| 379 | 425 | |
| 380 | | − /// Make a parked actor runnable; its operation returns `wake`. If its |
| 381 | | − /// fiber is still running (on its way to suspending), the thread |
| 382 | | − /// running it queues it. |
| 383 | | − pub(crate) fn wake(&mut self, pid: i64, wake: Value) { |
| 384 | | − let Some(slot) = self.actors.get_mut(&pid) else { |
| 385 | | − return; |
| 386 | | − }; |
| 387 | | − slot.proc.wait = Wait::Ready; |
| 388 | | − slot.proc.wake = wake; |
| 389 | | − if slot.fiber.is_some() { |
| 390 | | − self.run_queue.push_back(pid); |
| 391 | | − self.notify = true; |
| 426 | + pub(crate) fn tag(&self) -> i64 { |
| 427 | + self.next_tag.fetch_add(1, Ordering::Relaxed) + 1 |
| 428 | + } |
| 429 | + |
| 430 | + /// The virtual clock, in milliseconds. |
| 431 | + pub(crate) fn clock(&self) -> u64 { |
| 432 | + self.clock.load(Ordering::Acquire) |
| 433 | + } |
| 434 | + |
| 435 | + /// Run `f` on the OTP state of `pid`, if its fiber has not finished. |
| 436 | + pub(crate) fn with_proc<R>(&self, pid: i64, f: impl FnOnce(&mut Proc) -> R) -> Option<R> { |
| 437 | + let cell = self.cell(pid)?; |
| 438 | + let mut p = cell.proc.lock().expect("tilrt: actor poisoned"); |
| 439 | + Some(f(&mut p)) |
| 440 | + } |
| 441 | + |
| 442 | + /// Run `f` on the OTP state of `pid`, if it is alive (not exited). |
| 443 | + pub(crate) fn with_alive<R>(&self, pid: i64, f: impl FnOnce(&mut Proc) -> R) -> Option<R> { |
| 444 | + let cell = self.cell(pid)?; |
| 445 | + let mut p = cell.proc.lock().expect("tilrt: actor poisoned"); |
| 446 | + if p.dead { |
| 447 | + return None; |
| 448 | + } |
| 449 | + Some(f(&mut p)) |
| 450 | + } |
| 451 | + |
| 452 | + /// Whether `pid` is alive (not exited). |
| 453 | + pub(crate) fn exists(&self, pid: i64) -> bool { |
| 454 | + self.with_alive(pid, |_| ()).is_some() |
| 455 | + } |
| 456 | + |
| 457 | + /// Queue `pid`, which [`Proc::wake`] (or a new actor) made runnable. |
| 458 | + pub(crate) fn schedule(&self, pid: i64) { |
| 459 | + self.push(pid); |
| 460 | + self.nudge_idler(); |
| 461 | + } |
| 462 | + |
| 463 | + fn push(&self, pid: i64) { |
| 464 | + self.pending.fetch_add(1, Ordering::SeqCst); |
| 465 | + if !push_local(self, pid) { |
| 466 | + self.injector.push(pid); |
| 392 | 467 | } |
| 468 | + self.sleepers.notify(false); |
| 393 | 469 | } |
| 394 | 470 | |
| 395 | | − /// Wake `pid` unless it is runnable or in a blocking call. |
| 396 | | − fn interrupt(&mut self, pid: i64) { |
| 397 | | − if self |
| 398 | | − .proc(pid) |
| 399 | | − .is_some_and(|p| p.wait != Wait::Ready && p.wait != Wait::Blocking) |
| 471 | + /// The idle thread may be waiting on the reactor for something that |
| 472 | + /// no longer matters (work arrived, a sooner timer, the end): wake it. |
| 473 | + fn nudge_idler(&self) { |
| 474 | + if self.idling.load(Ordering::SeqCst) |
| 475 | + && let Some(w) = self.waker.get() |
| 400 | 476 | { |
| 401 | | − self.wake(pid, UNIT); |
| 477 | + let _ = w.wake(); |
| 402 | 478 | } |
| 403 | 479 | } |
| 404 | 480 | |
| 405 | | − pub(crate) fn io_token(&mut self) -> mio::Token { |
| 406 | | − self.next_token += 1; |
| 407 | | − mio::Token(self.next_token) |
| 481 | + /// Wake `pid` with a timeout at `deadline` if it is still in wait |
| 482 | + /// number `generation` then. |
| 483 | + pub(crate) fn add_timer(&self, deadline: u64, pid: i64, generation: u64) { |
| 484 | + self.control() |
| 485 | + .timers |
| 486 | + .push(Reverse((deadline, pid, generation))); |
| 487 | + self.nudge_idler(); |
| 488 | + } |
| 489 | + |
| 490 | + pub(crate) fn io_token(&self) -> mio::Token { |
| 491 | + let mut c = self.control(); |
| 492 | + c.next_token += 1; |
| 493 | + mio::Token(c.next_token) |
| 408 | 494 | } |
| 409 | 495 | |
| 410 | | − pub(crate) fn registry(&self) -> &mio::Registry { |
| 411 | | − self.registry |
| 496 | + /// Run `f` with the reactor's registry. |
| 497 | + pub(crate) fn with_registry<R>(&self, f: impl FnOnce(&mio::Registry) -> R) -> R { |
| 498 | + let c = self.control(); |
| 499 | + f(c.registry |
| 412 | 500 | .as_ref() |
| 413 | | − .expect("tilrt: the reactor starts with the scheduler") |
| 501 | + .expect("tilrt: the reactor starts with the scheduler")) |
| 414 | 502 | } |
| 415 | 503 | |
| 416 | | − /// Whether `pid` is alive (not exited). |
| 417 | | − pub(crate) fn exists(&mut self, pid: i64) -> bool { |
| 418 | | − self.alive(pid).is_some() |
| 504 | + /// Park `pid` (its wait already `Io`) on socket `token`, unless the |
| 505 | + /// socket became ready meanwhile: then returns false, and the caller |
| 506 | + /// retries instead of parking. |
| 507 | + pub(crate) fn io_wait(&self, token: mio::Token, pid: i64) -> bool { |
| 508 | + let mut c = self.control(); |
| 509 | + if c.io_ready.remove(&token) { |
| 510 | + return false; |
| 511 | + } |
| 512 | + if c.io_waiters.insert(token, pid).is_none() { |
| 513 | + self.io_waiting.fetch_add(1, Ordering::SeqCst); |
| 514 | + } |
| 515 | + true |
| 419 | 516 | } |
| 420 | 517 | |
| 421 | | − /// Mark `pid` as exiting, so it unwinds at its next safe point. |
| 422 | | − fn request_kill(&mut self, pid: i64) { |
| 423 | | − if let Some(slot) = self.actors.get(&pid) { |
| 424 | | − // SAFETY: slots only hold live actors. |
| 425 | | − unsafe { (*slot.actor).kill_requested.store(true, Ordering::Release) }; |
| 518 | + /// Forget `pid`'s wait on `token` (after waking, or being stopped). |
| 519 | + pub(crate) fn io_unwait(&self, token: mio::Token) { |
| 520 | + let mut c = self.control(); |
| 521 | + if c.io_waiters.remove(&token).is_some() { |
| 522 | + self.io_waiting.fetch_sub(1, Ordering::SeqCst); |
| 426 | 523 | } |
| 427 | 524 | } |
| 525 | + |
| 526 | + /// A socket was closed: forget its pending readiness. |
| 527 | + pub(crate) fn io_closed(&self, token: mio::Token) { |
| 528 | + self.control().io_ready.remove(&token); |
| 529 | + } |
| 530 | + |
| 531 | + /// A blocking call starts: returns the waker it signals when done. |
| 532 | + pub(crate) fn blocking_started(&self) -> Arc<mio::Waker> { |
| 533 | + self.control().blocking += 1; |
| 534 | + self.blocking.fetch_add(1, Ordering::SeqCst); |
| 535 | + self.waker |
| 536 | + .get() |
| 537 | + .expect("tilrt: the reactor starts with the scheduler") |
| 538 | + .clone() |
| 539 | + } |
| 540 | + |
| 541 | + /// An actor runs or is queued. |
| 542 | + fn busy(&self) -> bool { |
| 543 | + self.running.load(Ordering::SeqCst) > 0 || self.pending.load(Ordering::SeqCst) > 0 |
| 544 | + } |
| 428 | 545 | } |
| 429 | 546 | |
| 430 | 547 | /// How a new actor is tied to the one spawning it. |
| @@ -445,10 +562,16 @@ fn spawn_actor( |
| 445 | 562 | parent: Option<i64>, |
| 446 | 563 | tie: Tie, |
| 447 | 564 | ) -> (i64, Option<i64>) { |
| 565 | + let pid = sched.next_pid.fetch_add(1, Ordering::Relaxed); |
| 448 | 566 | let link = parent.filter(|_| tie == Tie::Link); |
| 449 | | − let mut s = sched.lock(); |
| 450 | | − let pid = s.next_pid; |
| 451 | | − s.next_pid += 1; |
| 567 | + let monitor = parent |
| 568 | + .filter(|_| tie == Tie::Monitor) |
| 569 | + .map(|watcher| (watcher, sched.tag())); |
| 570 | + let pooled = (stack_size == PROGRAM_STACK_SIZE) |
| 571 | + .then(|| sched.control().stacks.pop()) |
| 572 | + .flatten(); |
| 573 | + let stack = pooled |
| 574 | + .unwrap_or_else(|| Stack::new(stack_size).expect("tilrt: cannot allocate actor stack")); |
| 452 | 575 | let a = Box::into_raw(Box::new(Actor { |
| 453 | 576 | ctx: Ctx { |
| 454 | 577 | yielding: YIELD_NONE, |
| @@ -461,19 +584,12 @@ fn spawn_actor( |
| 461 | 584 | }, |
| 462 | 585 | pid, |
| 463 | 586 | next_marker: 0, |
| 464 | | − kill_requested: AtomicBool::new(false), |
| 465 | 587 | drops: DropStack::default(), |
| 466 | 588 | yielder: std::ptr::null(), |
| 467 | 589 | handler: std::ptr::null(), |
| 468 | 590 | sched, |
| 591 | + cell: std::ptr::null(), |
| 469 | 592 | })); |
| 470 | | − // SAFETY: `a` is a fresh allocation; `rt` points back at it. |
| 471 | | − unsafe { (*a).ctx.rt = a.cast() }; |
| 472 | | − let pooled = (stack_size == PROGRAM_STACK_SIZE) |
| 473 | | − .then(|| s.stacks.pop()) |
| 474 | | − .flatten(); |
| 475 | | − let stack = pooled |
| 476 | | − .unwrap_or_else(|| Stack::new(stack_size).expect("tilrt: cannot allocate actor stack")); |
| 477 | 593 | let fiber = Coroutine::with_stack(stack, move |yielder: &Yielder<(), ()>, ()| { |
| 478 | 594 | // SAFETY: the actor outlives its fiber (freed only after Return). |
| 479 | 595 | unsafe { |
| @@ -481,39 +597,51 @@ fn spawn_actor( |
| 481 | 597 | run_body(a, body); |
| 482 | 598 | } |
| 483 | 599 | }); |
| 484 | | − s.actors.insert( |
| 485 | | − pid, |
| 486 | | − Slot { |
| 487 | | − actor: a, |
| 488 | | − fiber: Some(Fiber(fiber, stack_size)), |
| 489 | | − proc: Proc { |
| 490 | | − mailbox: Mailbox::default(), |
| 491 | | − wait: Wait::Ready, |
| 492 | | − wake: UNIT, |
| 493 | | − links: link.into_iter().collect(), |
| 494 | | − trap: false, |
| 495 | | − exits_tag: None, |
| 496 | | − waiting_tags: Vec::new(), |
| 497 | | − waiting_any: false, |
| 498 | | − dead: false, |
| 499 | | − }, |
| 500 | | − }, |
| 501 | | − ); |
| 502 | | − if let Some(parent) = link.and_then(|p| s.proc(p)) { |
| 503 | | − parent.links.push(pid); |
| 600 | + let mut run = RunState::new(Fiber(fiber, stack_size)); |
| 601 | + run.queue_new(); |
| 602 | + let cell = Arc::new(Cell { |
| 603 | + actor: a, |
| 604 | + kill: AtomicBool::new(false), |
| 605 | + proc: Mutex::new(Proc { |
| 606 | + mailbox: Mailbox::default(), |
| 607 | + wait: Wait::Ready, |
| 608 | + wake: UNIT, |
| 609 | + links: link.into_iter().collect(), |
| 610 | + monitors: monitor.into_iter().collect(), |
| 611 | + trap: false, |
| 612 | + exits_tag: None, |
| 613 | + waiting_tags: Vec::new(), |
| 614 | + waiting_any: false, |
| 615 | + wait_gen: 0, |
| 616 | + dead: false, |
| 617 | + run, |
| 618 | + }), |
| 619 | + }); |
| 620 | + // SAFETY: `a` is a fresh allocation; `rt` points back at it, `cell` |
| 621 | + // at its shared half (kept alive by the table until it finishes). |
| 622 | + unsafe { |
| 623 | + (*a).ctx.rt = a.cast(); |
| 624 | + (*a).cell = Arc::as_ptr(&cell); |
| 504 | 625 | } |
| 505 | | − let monitor = match (parent, tie) { |
| 506 | | − (Some(watcher), Tie::Monitor) => { |
| 507 | | − let tag = s.tag(); |
| 508 | | − s.monitors.push((pid, watcher, tag)); |
| 509 | | − Some(tag) |
| 510 | | − } |
| 511 | | − _ => None, |
| 512 | | − }; |
| 513 | | − s.run_queue.push_back(pid); |
| 514 | | − s.notify = true; |
| 626 | + sched |
| 627 | + .actors |
| 628 | + .write() |
| 629 | + .expect("tilrt: scheduler poisoned") |
| 630 | + .insert(pid, cell); |
| 515 | 631 | LIVE_ACTORS.fetch_add(1, Ordering::Relaxed); |
| 516 | | − (pid, monitor) |
| 632 | + // The parent links once the child exists (so the parent's exit always |
| 633 | + // reaches it), and before it can run. |
| 634 | + let orphan = link.is_some_and(|p| { |
| 635 | + sched |
| 636 | + .with_alive(p, |parent| parent.links.push(pid)) |
| 637 | + .is_none() |
| 638 | + }); |
| 639 | + sched.schedule(pid); |
| 640 | + if orphan { |
| 641 | + // Linked to an actor that already exited: stop at once. |
| 642 | + exit_actor(sched, pid, Exit::Killed); |
| 643 | + } |
| 644 | + (pid, monitor.map(|(_, tag)| tag)) |
| 517 | 645 | } |
| 518 | 646 | |
| 519 | 647 | /// Spawn a compiled program's actor running `body` (consumed), tied to |
| @@ -577,14 +705,14 @@ unsafe fn run_body(a: *mut Actor, body: Body) { |
| 577 | 705 | let sched = &*(*a).sched; |
| 578 | 706 | exit_actor(sched, (*a).pid, reason); |
| 579 | 707 | // Release what the actor still owns. Nobody delivers to it now. |
| 580 | | − let (mut mailbox, wake) = { |
| 581 | | − let mut s = sched.lock(); |
| 582 | | − let p = s.proc((*a).pid).expect("tilrt: running actor vanished"); |
| 583 | | − ( |
| 584 | | − std::mem::take(&mut p.mailbox), |
| 585 | | − std::mem::replace(&mut p.wake, UNIT), |
| 586 | | − ) |
| 587 | | − }; |
| 708 | + let (mut mailbox, wake) = sched |
| 709 | + .with_proc((*a).pid, |p| { |
| 710 | + ( |
| 711 | + std::mem::take(&mut p.mailbox), |
| 712 | + std::mem::replace(&mut p.wake, UNIT), |
| 713 | + ) |
| 714 | + }) |
| 715 | + .expect("tilrt: running actor vanished"); |
| 588 | 716 | for message in mailbox.drain() { |
| 589 | 717 | drop_value(ctx, message); |
| 590 | 718 | } |
| @@ -595,43 +723,51 @@ unsafe fn run_body(a: *mut Actor, body: Body) { |
| 595 | 723 | /// Stop `pid` (logically): record its exit, notify monitors, propagate |
| 596 | 724 | /// through links, and make sure its fiber unwinds. |
| 597 | 725 | pub(crate) fn exit_actor(sched: &Shared, pid: i64, reason: Exit) { |
| 598 | | − let (links, fired) = { |
| 599 | | − let mut s = sched.lock(); |
| 600 | | − let root = s.root; |
| 601 | | − let Some(p) = s.alive(pid) else { |
| 726 | + let Some(cell) = sched.cell(pid) else { |
| 727 | + return; |
| 728 | + }; |
| 729 | + let (links, monitors, wake) = { |
| 730 | + let mut p = cell.proc.lock().expect("tilrt: actor poisoned"); |
| 731 | + if p.dead { |
| 602 | 732 | return; |
| 603 | | − }; |
| 604 | | − p.dead = true; |
| 605 | | − let links = std::mem::take(&mut p.links); |
| 606 | | − if pid == root && s.outcome.is_none() { |
| 607 | | − s.outcome = Some(reason.clone()); |
| 608 | | − } |
| 609 | | − if let Exit::Crashed(m) = &reason { |
| 610 | | − let program = PROGRAM_MODE.load(Ordering::Relaxed); |
| 611 | | − if !(program && pid == root) { |
| 612 | | − let prefix = if program { "" } else { "tilrt: " }; |
| 613 | | − eprintln!("{prefix}actor {pid} crashed: {m}"); |
| 614 | | − } |
| 615 | 733 | } |
| 734 | + p.dead = true; |
| 616 | 735 | // Its fiber unwinds the next time it runs (after a blocking call |
| 617 | 736 | // returns: that call still reads the actor's values). |
| 618 | | − s.request_kill(pid); |
| 619 | | − s.interrupt(pid); |
| 620 | | − let (fired, kept) = s.monitors.drain(..).partition(|(w, _, _)| *w == pid); |
| 621 | | − s.monitors = kept; |
| 622 | | − (links, fired) |
| 737 | + cell.kill.store(true, Ordering::Release); |
| 738 | + ( |
| 739 | + std::mem::take(&mut p.links), |
| 740 | + std::mem::take(&mut p.monitors), |
| 741 | + p.interrupt(), |
| 742 | + ) |
| 623 | 743 | }; |
| 624 | | − for (_, watcher, tag) in fired { |
| 744 | + drop(cell); |
| 745 | + if wake { |
| 746 | + sched.schedule(pid); |
| 747 | + } |
| 748 | + let root = sched.root.load(Ordering::Acquire); |
| 749 | + if pid == root { |
| 750 | + sched |
| 751 | + .control() |
| 752 | + .outcome |
| 753 | + .get_or_insert_with(|| reason.clone()); |
| 754 | + } |
| 755 | + if let Exit::Crashed(m) = &reason { |
| 756 | + let program = PROGRAM_MODE.load(Ordering::Relaxed); |
| 757 | + if !(program && pid == root) { |
| 758 | + let prefix = if program { "" } else { "tilrt: " }; |
| 759 | + eprintln!("{prefix}actor {pid} crashed: {m}"); |
| 760 | + } |
| 761 | + } |
| 762 | + for (watcher, tag) in monitors { |
| 625 | 763 | crate::process::deliver_down(sched, watcher, tag, pid, &reason); |
| 626 | 764 | } |
| 627 | 765 | for linked in links { |
| 628 | | − let trap = { |
| 629 | | − let mut s = sched.lock(); |
| 630 | | − let Some(other) = s.alive(linked) else { |
| 631 | | − continue; |
| 632 | | − }; |
| 766 | + let Some(trap) = sched.with_alive(linked, |other| { |
| 633 | 767 | other.links.retain(|l| *l != pid); |
| 634 | 768 | other.trap |
| 769 | + }) else { |
| 770 | + continue; |
| 635 | 771 | }; |
| 636 | 772 | // As in Erlang: actors that trap exits are told about every exit, |
| 637 | 773 | // normal ones included; others only die of abnormal ones. |
| @@ -643,6 +779,28 @@ pub(crate) fn exit_actor(sched: &Shared, pid: i64, reason: Exit) { |
| 643 | 779 | } |
| 644 | 780 | } |
| 645 | 781 | |
| 782 | +/// `main` stopped: stop every other actor, silently. |
| 783 | +fn stop_all(sched: &Shared) { |
| 784 | + let cells: Vec<(i64, Arc<Cell>)> = sched |
| 785 | + .actors |
| 786 | + .read() |
| 787 | + .expect("tilrt: scheduler poisoned") |
| 788 | + .iter() |
| 789 | + .map(|(pid, cell)| (*pid, cell.clone())) |
| 790 | + .collect(); |
| 791 | + for (pid, cell) in cells { |
| 792 | + cell.kill.store(true, Ordering::Release); |
| 793 | + let wake = { |
| 794 | + let mut p = cell.proc.lock().expect("tilrt: actor poisoned"); |
| 795 | + p.dead = true; |
| 796 | + p.interrupt() |
| 797 | + }; |
| 798 | + if wake { |
| 799 | + sched.schedule(pid); |
| 800 | + } |
| 801 | + } |
| 802 | +} |
| 803 | + |
| 646 | 804 | /// The number of scheduler threads: `TILC_THREADS`, or one per core. |
| 647 | 805 | fn thread_count() -> usize { |
| 648 | 806 | std::env::var("TILC_THREADS") |
| @@ -656,153 +814,242 @@ fn thread_count() -> usize { |
| 656 | 814 | /// When the root exits, every other actor is stopped (and unwound). |
| 657 | 815 | /// Returns the root's exit. |
| 658 | 816 | fn run(sched: &Shared, root: i64, threads: usize) -> Exit { |
| 817 | + sched.root.store(root, Ordering::Release); |
| 659 | 818 | { |
| 660 | | − let mut s = sched.lock(); |
| 661 | | − s.root = root; |
| 819 | + let mut c = sched.control(); |
| 662 | 820 | let poll = mio::Poll::new().expect("tilrt: cannot create the reactor"); |
| 663 | | − s.registry = Some( |
| 821 | + c.registry = Some( |
| 664 | 822 | poll.registry() |
| 665 | 823 | .try_clone() |
| 666 | 824 | .expect("tilrt: cannot share the reactor"), |
| 667 | 825 | ); |
| 668 | | − s.waker = Some(std::sync::Arc::new( |
| 669 | | − mio::Waker::new(poll.registry(), WAKER).expect("tilrt: cannot create the waker"), |
| 670 | | − )); |
| 671 | | − s.poll = Some(poll); |
| 826 | + let waker = |
| 827 | + mio::Waker::new(poll.registry(), WAKER).expect("tilrt: cannot create the waker"); |
| 828 | + let _ = sched.waker.set(Arc::new(waker)); |
| 829 | + c.poll = Some(poll); |
| 672 | 830 | } |
| 831 | + // FIFO queues: with one thread, actors run in the order they were |
| 832 | + // queued, as in the interpreter. |
| 833 | + let workers: Vec<Worker<i64>> = (0..threads).map(|_| Worker::new_fifo()).collect(); |
| 834 | + let _ = sched |
| 835 | + .stealers |
| 836 | + .set(workers.iter().map(Worker::stealer).collect()); |
| 673 | 837 | std::thread::scope(|scope| { |
| 674 | | − for i in 1..threads { |
| 838 | + let mut workers = workers.into_iter().enumerate(); |
| 839 | + let (_, first) = workers.next().expect("one thread at least"); |
| 840 | + for (i, w) in workers { |
| 675 | 841 | std::thread::Builder::new() |
| 676 | 842 | .name(format!("tilrt-sched-{i}")) |
| 677 | | − .spawn_scoped(scope, || worker(sched)) |
| 843 | + .spawn_scoped(scope, move || worker(sched, i, w)) |
| 678 | 844 | .expect("tilrt: cannot start a scheduler thread"); |
| 679 | 845 | } |
| 680 | | − worker(sched); |
| 846 | + worker(sched, 0, first); |
| 681 | 847 | }); |
| 682 | | − sched.lock().outcome.take().unwrap_or(Exit::Normal) |
| 848 | + sched.control().outcome.take().unwrap_or(Exit::Normal) |
| 683 | 849 | } |
| 684 | 850 | |
| 685 | | −/// One scheduler thread: run actors from the queue. When no actor can run |
| 686 | | −/// on any thread, one thread waits for blocking calls, sockets or the next |
| 687 | | −/// deadline, as the single-threaded scheduler did. |
| 688 | | −fn worker(sched: &Shared) { |
| 689 | | − let mut s = sched.lock(); |
| 851 | +/// One scheduler thread: run actors from its queue, else from the shared |
| 852 | +/// one, else steal from the others. When no actor runs or is queued |
| 853 | +/// anywhere, one thread idles for everyone (blocking calls, sockets, the |
| 854 | +/// clock); the others sleep. |
| 855 | +fn worker(sched: &Shared, index: usize, queue: Worker<i64>) { |
| 856 | + LOCAL.with(|l| *l.borrow_mut() = Some((sched as *const Shared as usize, queue))); |
| 690 | 857 | loop { |
| 691 | | − if s.finished { |
| 692 | | − return; |
| 858 | + if sched.finished.load(Ordering::SeqCst) { |
| 859 | + break; |
| 693 | 860 | } |
| 694 | | − collect_blocking(&mut s); |
| 695 | | − if !s.io_waiters.is_empty() { |
| 696 | | − poll_io(&mut s); |
| 697 | | − } |
| 698 | | − if let Some(pid) = s.run_queue.pop_front() { |
| 699 | | − s = run_slice(sched, s, pid); |
| 861 | + collect_events(sched); |
| 862 | + if let Some(pid) = find_work(sched, index) { |
| 863 | + run_slice(sched, pid); |
| 700 | 864 | continue; |
| 701 | 865 | } |
| 702 | | − if s.actors.is_empty() { |
| 703 | | − s.finished = true; |
| 704 | | − s.notify = true; |
| 705 | | − return; |
| 866 | + if sched.pending.load(Ordering::SeqCst) > 0 { |
| 867 | + // Queued, but not stealable yet (a push in progress). |
| 868 | + std::thread::yield_now(); |
| 869 | + continue; |
| 706 | 870 | } |
| 707 | | − if s.running > 0 || s.idling { |
| 708 | | − // Another thread will queue work, or idle for everyone. |
| 709 | | − s = s.wait(); |
| 871 | + if sched.running.load(Ordering::SeqCst) > 0 || sched.idling.load(Ordering::SeqCst) { |
| 872 | + sched.sleepers.sleep(|| { |
| 873 | + sched.pending.load(Ordering::SeqCst) == 0 |
| 874 | + && !sched.finished.load(Ordering::SeqCst) |
| 875 | + && (sched.running.load(Ordering::SeqCst) > 0 |
| 876 | + || sched.idling.load(Ordering::SeqCst)) |
| 877 | + }); |
| 710 | 878 | continue; |
| 711 | 879 | } |
| 712 | | − s.idling = true; |
| 713 | | − drop(s); |
| 714 | | − idle(sched); |
| 715 | | − s = sched.lock(); |
| 716 | | − s.idling = false; |
| 717 | | − s.notify = true; |
| 880 | + if sched |
| 881 | + .idling |
| 882 | + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) |
| 883 | + .is_ok() |
| 884 | + { |
| 885 | + idle(sched); |
| 886 | + sched.idling.store(false, Ordering::SeqCst); |
| 887 | + sched.sleepers.notify(true); |
| 888 | + } |
| 718 | 889 | } |
| 890 | + LOCAL.with(|l| l.borrow_mut().take()); |
| 719 | 891 | } |
| 720 | 892 | |
| 721 | | −/// Resume `pid` for one slice, without holding the lock. |
| 722 | | −fn run_slice<'a>(sched: &'a Shared, mut s: Locked<'a>, pid: i64) -> Locked<'a> { |
| 723 | | − let Some(slot) = s.actors.get_mut(&pid) else { |
| 724 | | − return s; |
| 893 | +/// The next actor for thread `index`: its own queue first (FIFO), then |
| 894 | +/// the shared queue, then the other threads' queues. |
| 895 | +fn find_work(sched: &Shared, index: usize) -> Option<i64> { |
| 896 | + if let Some(pid) = pop_local() { |
| 897 | + return Some(pid); |
| 898 | + } |
| 899 | + let stealers = sched.stealers.get().expect("stealers"); |
| 900 | + loop { |
| 901 | + let mut retry = false; |
| 902 | + let from_injector = LOCAL.with(|l| match &*l.borrow() { |
| 903 | + Some((_, w)) => sched.injector.steal_batch_and_pop(w), |
| 904 | + None => Steal::Empty, |
| 905 | + }); |
| 906 | + match from_injector { |
| 907 | + Steal::Success(pid) => return Some(pid), |
| 908 | + Steal::Retry => retry = true, |
| 909 | + Steal::Empty => {} |
| 910 | + } |
| 911 | + for k in 1..stealers.len() { |
| 912 | + let victim = &stealers[(index + k) % stealers.len()]; |
| 913 | + let stolen = LOCAL.with(|l| match &*l.borrow() { |
| 914 | + Some((_, w)) => victim.steal_batch_and_pop(w), |
| 915 | + None => Steal::Empty, |
| 916 | + }); |
| 917 | + match stolen { |
| 918 | + Steal::Success(pid) => return Some(pid), |
| 919 | + Steal::Retry => retry = true, |
| 920 | + Steal::Empty => {} |
| 921 | + } |
| 922 | + } |
| 923 | + if !retry { |
| 924 | + return None; |
| 925 | + } |
| 926 | + } |
| 927 | +} |
| 928 | + |
| 929 | +/// Resume `pid` for one slice. |
| 930 | +fn run_slice(sched: &Shared, pid: i64) { |
| 931 | + // Running before no longer pending: the scheduler never looks idle |
| 932 | + // while an actor is between the two. |
| 933 | + sched.running.fetch_add(1, Ordering::SeqCst); |
| 934 | + sched.pending.fetch_sub(1, Ordering::SeqCst); |
| 935 | + let Some(cell) = sched.cell(pid) else { |
| 936 | + stop_running(sched); |
| 937 | + return; |
| 725 | 938 | }; |
| 726 | | − let Some(mut fiber) = slot.fiber.take() else { |
| 727 | | − return s; |
| 939 | + let fiber = cell.proc.lock().expect("tilrt: actor poisoned").run.start(); |
| 940 | + let Some(mut fiber) = fiber else { |
| 941 | + stop_running(sched); |
| 942 | + return; |
| 728 | 943 | }; |
| 729 | | − let a = slot.actor; |
| 730 | | − s.running += 1; |
| 731 | | − drop(s); |
| 944 | + let a = cell.actor; |
| 732 | 945 | // SAFETY: the actor is live and runs on this thread only. |
| 733 | 946 | unsafe { (*a).ctx.reductions = REDUCTIONS }; |
| 734 | 947 | let result = fiber.0.resume(()); |
| 735 | | − let mut s = sched.lock(); |
| 736 | | − s.running -= 1; |
| 737 | | − if s.running == 0 { |
| 738 | | − s.notify = true; // Someone may have to idle for everyone. |
| 739 | | − } |
| 740 | 948 | match result { |
| 741 | 949 | CoroutineResult::Yield(()) => { |
| 742 | | − let slot = s.actors.get_mut(&pid).expect("tilrt: actor vanished"); |
| 743 | | − slot.fiber = Some(fiber); |
| 744 | | − if slot.proc.wait == Wait::Ready { |
| 745 | | − s.run_queue.push_back(pid); |
| 950 | + let again = { |
| 951 | + let mut p = cell.proc.lock().expect("tilrt: actor poisoned"); |
| 952 | + let ready = p.wait == Wait::Ready; |
| 953 | + p.run.stop(fiber, ready) |
| 954 | + }; |
| 955 | + if again { |
| 956 | + sched.push(pid); |
| 746 | 957 | } |
| 747 | | − s |
| 748 | 958 | } |
| 749 | 959 | CoroutineResult::Return(()) => { |
| 750 | | − let slot = s.actors.remove(&pid).expect("tilrt: actor vanished"); |
| 751 | | − if fiber.1 == PROGRAM_STACK_SIZE && s.stacks.len() < STACK_POOL { |
| 752 | | − let stack = fiber.0.into_stack(); |
| 753 | | − s.stacks.push(stack); |
| 754 | | − } else { |
| 755 | | − drop(fiber); |
| 960 | + cell.proc |
| 961 | + .lock() |
| 962 | + .expect("tilrt: actor poisoned") |
| 963 | + .run |
| 964 | + .finish(); |
| 965 | + let empty = { |
| 966 | + let mut actors = sched.actors.write().expect("tilrt: scheduler poisoned"); |
| 967 | + actors.remove(&pid); |
| 968 | + actors.is_empty() |
| 969 | + }; |
| 970 | + drop(cell); |
| 971 | + if fiber.1 == PROGRAM_STACK_SIZE { |
| 972 | + let mut c = sched.control(); |
| 973 | + if c.stacks.len() < STACK_POOL { |
| 974 | + c.stacks.push(fiber.0.into_stack()); |
| 975 | + } |
| 756 | 976 | } |
| 757 | 977 | // SAFETY: the fiber has returned; nothing refers to the actor. |
| 758 | | − drop(unsafe { Box::from_raw(slot.actor) }); |
| 978 | + drop(unsafe { Box::from_raw(a) }); |
| 759 | 979 | LIVE_ACTORS.fetch_sub(1, Ordering::Relaxed); |
| 760 | | − if pid == s.root { |
| 761 | | − // `main` stopped: stop everyone else, silently. |
| 762 | | − let others: Vec<i64> = s.actors.keys().copied().collect(); |
| 763 | | − for other in others { |
| 764 | | − if let Some(p) = s.proc(other) { |
| 765 | | − p.dead = true; |
| 766 | | − } |
| 767 | | − s.request_kill(other); |
| 768 | | − s.interrupt(other); |
| 769 | | − } |
| 980 | + if pid == sched.root.load(Ordering::Acquire) { |
| 981 | + stop_all(sched); |
| 982 | + } |
| 983 | + if empty { |
| 984 | + sched.finished.store(true, Ordering::SeqCst); |
| 985 | + sched.sleepers.notify(true); |
| 986 | + sched.nudge_idler(); |
| 770 | 987 | } |
| 771 | | − s.notify = true; |
| 772 | | − s |
| 773 | 988 | } |
| 774 | 989 | } |
| 990 | + stop_running(sched); |
| 991 | +} |
| 992 | + |
| 993 | +fn stop_running(sched: &Shared) { |
| 994 | + if sched.running.fetch_sub(1, Ordering::SeqCst) == 1 |
| 995 | + && sched.pending.load(Ordering::SeqCst) == 0 |
| 996 | + { |
| 997 | + // Nothing runs or is queued: someone may have to idle. |
| 998 | + sched.sleepers.notify(true); |
| 999 | + sched.nudge_idler(); |
| 1000 | + } |
| 1001 | +} |
| 1002 | + |
| 1003 | +/// Between slices: collect finished blocking calls and ready sockets, |
| 1004 | +/// without waiting (skipped if another thread is at it). |
| 1005 | +fn collect_events(sched: &Shared) { |
| 1006 | + if sched.blocking.load(Ordering::SeqCst) == 0 && sched.io_waiting.load(Ordering::SeqCst) == 0 { |
| 1007 | + return; |
| 1008 | + } |
| 1009 | + let Ok(mut c) = sched.control.try_lock() else { |
| 1010 | + return; |
| 1011 | + }; |
| 1012 | + collect_blocking(sched, &mut c); |
| 1013 | + if !c.io_waiters.is_empty() |
| 1014 | + && let Some(mut poll) = c.poll.take() |
| 1015 | + { |
| 1016 | + let mut events = mio::Events::with_capacity(256); |
| 1017 | + wait_events(&mut poll, &mut events, Some(std::time::Duration::ZERO)); |
| 1018 | + c.poll = Some(poll); |
| 1019 | + wake_io(sched, &mut c, &events); |
| 1020 | + } |
| 775 | 1021 | } |
| 776 | 1022 | |
| 777 | | −/// Every actor waits: wait for blocking calls, sockets or the clock, or |
| 778 | | −/// detect a deadlock. Called by one thread at a time, without the lock. |
| 1023 | +/// No actor runs or is queued: wait for blocking calls, sockets or the |
| 1024 | +/// clock, or detect a deadlock. Called by one thread at a time. |
| 779 | 1025 | /// |
| 780 | | −/// Each decision is taken under one lock, and the thread stops idling as |
| 781 | | −/// soon as an actor runs or is queued (another thread may have polled the |
| 782 | | −/// reactor meanwhile). Blocking calls signal the reactor when they finish |
| 783 | | −/// (`WAKER`), so the reactor is the only thing waited on. |
| 1026 | +/// Each decision is taken under the control lock, and the thread stops |
| 1027 | +/// idling as soon as an actor runs or is queued. Blocking calls, new |
| 1028 | +/// timers and new work signal the reactor (`WAKER`), so the reactor is the |
| 1029 | +/// only thing waited on. |
| 784 | 1030 | fn idle(sched: &Shared) { |
| 785 | 1031 | let (mut poll, real_time, clock, deadline) = { |
| 786 | | − let mut s = sched.lock(); |
| 787 | | − collect_blocking(&mut s); |
| 788 | | − if s.running > 0 || !s.run_queue.is_empty() { |
| 1032 | + let mut c = sched.control(); |
| 1033 | + collect_blocking(sched, &mut c); |
| 1034 | + if sched.busy() { |
| 789 | 1035 | return; |
| 790 | 1036 | } |
| 791 | | − if s.io_waiters.is_empty() && s.blocking == 0 { |
| 1037 | + if c.io_waiters.is_empty() && c.blocking == 0 { |
| 792 | 1038 | // Only the clock can wake an actor now. |
| 793 | | − if !advance_clock(&mut s) { |
| 794 | | − deadlock(sched, s); |
| 1039 | + if !advance_clock(sched, &mut c) { |
| 1040 | + drop(c); |
| 1041 | + deadlock(sched); |
| 795 | 1042 | } |
| 796 | 1043 | return; |
| 797 | 1044 | } |
| 798 | | − let Some(poll) = s.poll.take() else { |
| 1045 | + let deadline = next_deadline(sched, &mut c); |
| 1046 | + let Some(poll) = c.poll.take() else { |
| 799 | 1047 | return; |
| 800 | 1048 | }; |
| 801 | 1049 | // Real time passes while waiting for sockets, and timers fire when |
| 802 | 1050 | // it reaches their deadline. Waiting only for blocking calls keeps |
| 803 | 1051 | // the clock virtual. |
| 804 | | − let real_time = !s.io_waiters.is_empty(); |
| 805 | | − (poll, real_time, s.clock, next_deadline(&s)) |
| 1052 | + (poll, !c.io_waiters.is_empty(), sched.clock(), deadline) |
| 806 | 1053 | }; |
| 807 | 1054 | let timeout = match deadline { |
| 808 | 1055 | Some(d) if real_time => Some(std::time::Duration::from_millis(d.saturating_sub(clock))), |
| @@ -811,61 +1058,62 @@ fn idle(sched: &Shared) { |
| 811 | 1058 | let start = std::time::Instant::now(); |
| 812 | 1059 | let mut events = mio::Events::with_capacity(256); |
| 813 | 1060 | wait_events(&mut poll, &mut events, timeout); |
| 814 | | − let mut s = sched.lock(); |
| 815 | | − s.poll = Some(poll); |
| 1061 | + let mut c = sched.control(); |
| 1062 | + c.poll = Some(poll); |
| 816 | 1063 | if real_time { |
| 817 | | − s.clock += start.elapsed().as_millis() as u64; |
| 1064 | + sched |
| 1065 | + .clock |
| 1066 | + .fetch_add(start.elapsed().as_millis() as u64, Ordering::AcqRel); |
| 818 | 1067 | } |
| 819 | | − let woke = wake_io(&mut s, &events); |
| 820 | | − collect_blocking(&mut s); |
| 1068 | + let woke = wake_io(sched, &mut c, &events); |
| 1069 | + collect_blocking(sched, &mut c); |
| 821 | 1070 | if real_time |
| 822 | 1071 | && !woke |
| 1072 | + && !sched.busy() |
| 823 | 1073 | && let Some(d) = deadline |
| 824 | | − && s.clock >= d |
| 1074 | + && sched.clock() >= d |
| 825 | 1075 | { |
| 826 | | − advance_clock(&mut s); |
| 1076 | + advance_clock(sched, &mut c); |
| 827 | 1077 | } |
| 828 | 1078 | } |
| 829 | 1079 | |
| 830 | 1080 | /// Nothing can ever run again: crash the root (stopping everyone). |
| 831 | | −fn deadlock(sched: &Shared, s: Locked<'_>) { |
| 832 | | − let root = s.root; |
| 833 | | − let alive: Vec<i64> = s.actors.keys().copied().collect(); |
| 834 | | − drop(s); |
| 1081 | +fn deadlock(sched: &Shared) { |
| 1082 | + let alive: Vec<i64> = sched |
| 1083 | + .actors |
| 1084 | + .read() |
| 1085 | + .expect("tilrt: scheduler poisoned") |
| 1086 | + .keys() |
| 1087 | + .copied() |
| 1088 | + .collect(); |
| 835 | 1089 | exit_actor( |
| 836 | 1090 | sched, |
| 837 | | − root, |
| 1091 | + sched.root.load(Ordering::Acquire), |
| 838 | 1092 | Exit::Crashed("deadlock: every actor is waiting for a message".into()), |
| 839 | 1093 | ); |
| 840 | 1094 | for pid in alive { |
| 841 | 1095 | exit_actor(sched, pid, Exit::Killed); |
| 842 | | − sched.lock().interrupt(pid); |
| 1096 | + let wake = sched.with_proc(pid, |p| p.interrupt()) == Some(true); |
| 1097 | + if wake { |
| 1098 | + sched.schedule(pid); |
| 1099 | + } |
| 843 | 1100 | } |
| 844 | 1101 | } |
| 845 | 1102 | |
| 846 | 1103 | /// Wake the actors whose blocking calls finished. |
| 847 | | −fn collect_blocking(s: &mut Sched) { |
| 848 | | − if s.blocking == 0 { |
| 1104 | +fn collect_blocking(sched: &Shared, c: &mut Control) { |
| 1105 | + if c.blocking == 0 { |
| 849 | 1106 | return; |
| 850 | 1107 | } |
| 851 | 1108 | while let Some(done) = crate::blocking::finished() { |
| 852 | | − s.blocking -= 1; |
| 853 | | − s.wake(done.pid, done.result); |
| 1109 | + c.blocking -= 1; |
| 1110 | + sched.blocking.fetch_sub(1, Ordering::SeqCst); |
| 1111 | + if sched.with_proc(done.pid, |p| p.wake(done.result)) == Some(true) { |
| 1112 | + sched.push(done.pid); |
| 1113 | + } |
| 854 | 1114 | } |
| 855 | 1115 | } |
| 856 | 1116 | |
| 857 | | −/// Wake the actors whose sockets are ready, without waiting. Skipped while |
| 858 | | −/// an idle thread holds the reactor. |
| 859 | | −fn poll_io(s: &mut Sched) { |
| 860 | | − let Some(mut poll) = s.poll.take() else { |
| 861 | | − return; |
| 862 | | − }; |
| 863 | | − let mut events = mio::Events::with_capacity(256); |
| 864 | | − wait_events(&mut poll, &mut events, Some(std::time::Duration::ZERO)); |
| 865 | | − s.poll = Some(poll); |
| 866 | | − wake_io(s, &events); |
| 867 | | −} |
| 868 | | − |
| 869 | 1117 | fn wait_events( |
| 870 | 1118 | poll: &mut mio::Poll, |
| 871 | 1119 | events: &mut mio::Events, |
| @@ -879,59 +1127,73 @@ fn wait_events( |
| 879 | 1127 | } |
| 880 | 1128 | |
| 881 | 1129 | /// Wake the actors parked on `events`; returns whether any woke. |
| 882 | | −fn wake_io(s: &mut Sched, events: &mio::Events) -> bool { |
| 1130 | +fn wake_io(sched: &Shared, c: &mut Control, events: &mio::Events) -> bool { |
| 883 | 1131 | let mut woke = false; |
| 884 | 1132 | for event in events { |
| 885 | 1133 | if event.token() == WAKER { |
| 886 | | − continue; // A blocking call finished: see `collect_blocking`. |
| 1134 | + continue; // Blocking calls, new work: see the callers. |
| 887 | 1135 | } |
| 888 | | − if let Some(pid) = s.io_waiters.remove(&event.token()) { |
| 889 | | − s.wake(pid, UNIT); |
| 1136 | + if let Some(pid) = c.io_waiters.remove(&event.token()) { |
| 1137 | + sched.io_waiting.fetch_sub(1, Ordering::SeqCst); |
| 1138 | + if sched.with_proc(pid, |p| p.wake(UNIT)) == Some(true) { |
| 1139 | + sched.push(pid); |
| 1140 | + } |
| 890 | 1141 | woke = true; |
| 891 | 1142 | } else { |
| 892 | | − s.io_ready.insert(event.token()); |
| 1143 | + c.io_ready.insert(event.token()); |
| 893 | 1144 | } |
| 894 | 1145 | } |
| 895 | 1146 | woke |
| 896 | 1147 | } |
| 897 | 1148 | |
| 898 | | −fn deadline_of(p: &Proc) -> Option<u64> { |
| 899 | | − match p.wait { |
| 900 | | − Wait::Receive { |
| 901 | | − deadline: Some(d), .. |
| 902 | | − } |
| 903 | | − | Wait::Sleep { deadline: d } => Some(d), |
| 904 | | − _ => None, |
| 905 | | − } |
| 1149 | +/// Whether timer `(deadline, pid, generation)` still applies: the actor |
| 1150 | +/// is in that wait, with that deadline. |
| 1151 | +fn timer_live(sched: &Shared, deadline: u64, pid: i64, generation: u64) -> bool { |
| 1152 | + sched |
| 1153 | + .with_proc(pid, |p| { |
| 1154 | + p.wait_gen == generation && p.deadline() == Some(deadline) |
| 1155 | + }) |
| 1156 | + .unwrap_or(false) |
| 906 | 1157 | } |
| 907 | 1158 | |
| 908 | | −fn next_deadline(s: &Sched) -> Option<u64> { |
| 909 | | − s.actors |
| 910 | | − .values() |
| 911 | | − .filter_map(|slot| deadline_of(&slot.proc)) |
| 912 | | − .min() |
| 1159 | +/// The soonest deadline still waited for (dropping timers that no longer |
| 1160 | +/// apply). |
| 1161 | +fn next_deadline(sched: &Shared, c: &mut Control) -> Option<u64> { |
| 1162 | + while let Some(&Reverse((deadline, pid, generation))) = c.timers.peek() { |
| 1163 | + if timer_live(sched, deadline, pid, generation) { |
| 1164 | + return Some(deadline); |
| 1165 | + } |
| 1166 | + c.timers.pop(); |
| 1167 | + } |
| 1168 | + None |
| 913 | 1169 | } |
| 914 | 1170 | |
| 915 | | −/// Jump the virtual clock to the next deadline and wake those actors. |
| 916 | | −fn advance_clock(s: &mut Sched) -> bool { |
| 917 | | − let Some(next) = next_deadline(s) else { |
| 1171 | +/// Jump the virtual clock to the next deadline and wake those actors, in |
| 1172 | +/// pid order. |
| 1173 | +fn advance_clock(sched: &Shared, c: &mut Control) -> bool { |
| 1174 | + let Some(next) = next_deadline(sched, c) else { |
| 918 | 1175 | return false; |
| 919 | 1176 | }; |
| 920 | | − s.clock = s.clock.max(next); |
| 921 | | − let mut due: Vec<i64> = s |
| 922 | | − .actors |
| 923 | | − .iter() |
| 924 | | − .filter(|(_, slot)| deadline_of(&slot.proc) == Some(next)) |
| 925 | | − .map(|(p, _)| *p) |
| 926 | | − .collect(); |
| 927 | | − due.sort(); |
| 928 | | − for pid in due { |
| 929 | | − // A receive that timed out returns `None` (constructor 0). |
| 930 | | − let wake = match s.proc(pid).expect("listed").wait { |
| 931 | | − Wait::Sleep { .. } => UNIT, |
| 932 | | − _ => int(0), |
| 933 | | − }; |
| 934 | | − s.wake(pid, wake); |
| 1177 | + sched.clock.fetch_max(next, Ordering::AcqRel); |
| 1178 | + while let Some(&Reverse((deadline, pid, generation))) = c.timers.peek() { |
| 1179 | + if deadline != next { |
| 1180 | + break; |
| 1181 | + } |
| 1182 | + c.timers.pop(); |
| 1183 | + let woke = sched.with_proc(pid, |p| { |
| 1184 | + if p.wait_gen != generation || p.deadline() != Some(deadline) { |
| 1185 | + return false; |
| 1186 | + } |
| 1187 | + // A receive that timed out returns `None` (constructor 0). |
| 1188 | + let value = match p.wait { |
| 1189 | + Wait::Sleep { .. } => UNIT, |
| 1190 | + _ => int(0), |
| 1191 | + }; |
| 1192 | + p.wake(value) |
| 1193 | + }); |
| 1194 | + if woke == Some(true) { |
| 1195 | + sched.push(pid); |
| 1196 | + } |
| 935 | 1197 | } |
| 936 | 1198 | true |
| 937 | 1199 | } |
| @@ -968,9 +1230,9 @@ pub(crate) unsafe fn preempt_root(ctx: *mut Ctx) { |
| 968 | 1230 | } |
| 969 | 1231 | } |
| 970 | 1232 | |
| 971 | | −/// Park the running actor until it is woken (its `wait` must be set, |
| 972 | | −/// under the lock, before calling); returns the wake value, or unit with |
| 973 | | −/// `yielding = KILL` if it exited meanwhile. |
| 1233 | +/// Park the running actor until it is woken (its `wait` must be set |
| 1234 | +/// before calling); returns the wake value, or unit with `yielding = KILL` |
| 1235 | +/// if it exited meanwhile. |
| 974 | 1236 | /// |
| 975 | 1237 | /// # Safety |
| 976 | 1238 | /// `ctx` must be the running actor's context. |
| @@ -979,11 +1241,9 @@ pub(crate) unsafe fn park(ctx: *mut Ctx) -> Value { |
| 979 | 1241 | unsafe { |
| 980 | 1242 | tl_preempt(ctx); |
| 981 | 1243 | let (a, sched) = this(ctx); |
| 982 | | − let wake = { |
| 983 | | − let mut s = sched.lock(); |
| 984 | | − let p = s.proc(a.pid).expect("tilrt: running actor vanished"); |
| 985 | | − std::mem::replace(&mut p.wake, UNIT) |
| 986 | | − }; |
| 1244 | + let wake = sched |
| 1245 | + .with_proc(a.pid, |p| std::mem::replace(&mut p.wake, UNIT)) |
| 1246 | + .expect("tilrt: running actor vanished"); |
| 987 | 1247 | if (*ctx).yielding != YIELD_NONE { |
| 988 | 1248 | drop_value(ctx, wake); |
| 989 | 1249 | return UNIT; |