| @@ -46,7 +46,7 @@ |
| 46 | 46 | use std::cell::RefCell; |
| 47 | 47 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 48 | 48 | use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering}; |
| 49 | | −use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLock}; |
| 49 | +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLock, RwLockReadGuard, RwLockWriteGuard}; |
| 50 | 50 | use std::time::{Duration, Instant}; |
| 51 | 51 | |
| 52 | 52 | use crossbeam_deque::{Injector, Steal, Stealer, Worker}; |
| @@ -284,58 +284,110 @@ impl Cell { |
| 284 | 284 | /// Take the actor's lock. |
| 285 | 285 | fn lock(&self) -> MutexGuard<'_, Proc> { |
| 286 | 286 | #[cfg(feature = "lock-stats")] |
| 287 | | − return lock_stats::lock(&self.proc); |
| 287 | + return lock_stats::lock(lock_stats::Kind::Actor, &self.proc); |
| 288 | 288 | #[cfg(not(feature = "lock-stats"))] |
| 289 | 289 | self.proc.lock().expect("louise: actor poisoned") |
| 290 | 290 | } |
| 291 | 291 | } |
| 292 | 292 | |
| 293 | 293 | /// `--features lock-stats` (ADR 0028): how many times scheduler threads |
| 294 | | −/// took an actor's lock, and how many of those found it taken (a sender's |
| 295 | | −/// `try_lock`, to hand a message over, is not counted). Counted per |
| 296 | | −/// thread (a shared counter would itself be contended), added up when the |
| 297 | | −/// thread stops, and printed at exit with `LOUISE_LEAKS`. |
| 294 | +/// took each kind of lock ([`lock_stats::Kind`]), and how many of those |
| 295 | +/// found it taken (a sender's `try_lock`, to hand a message over, is not |
| 296 | +/// counted). Counted per thread (a shared counter would itself be |
| 297 | +/// contended), added up when the thread stops, and printed at exit with |
| 298 | +/// `LOUISE_LEAKS`. |
| 298 | 299 | #[cfg(feature = "lock-stats")] |
| 299 | 300 | pub(crate) mod lock_stats { |
| 300 | 301 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 301 | | − use std::sync::{Mutex, MutexGuard, TryLockError}; |
| 302 | + use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockError}; |
| 302 | 303 | |
| 303 | | − static TAKEN: AtomicU64 = AtomicU64::new(0); |
| 304 | | − static CONTENDED: AtomicU64 = AtomicU64::new(0); |
| 304 | + /// The locks counted. |
| 305 | + #[derive(Clone, Copy)] |
| 306 | + pub(crate) enum Kind { |
| 307 | + Actor, |
| 308 | + Control, |
| 309 | + TableRead, |
| 310 | + TableWrite, |
| 311 | + Stacks, |
| 312 | + } |
| 313 | + |
| 314 | + const KINDS: usize = 5; |
| 315 | + |
| 316 | + /// What each [`Kind`] is called in the report. |
| 317 | + pub(crate) const NAMES: [&str; KINDS] = [ |
| 318 | + "actor locks", |
| 319 | + "control lock", |
| 320 | + "actor table (read)", |
| 321 | + "actor table (write)", |
| 322 | + "stack pool", |
| 323 | + ]; |
| 324 | + |
| 325 | + static TAKEN: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; |
| 326 | + static CONTENDED: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; |
| 305 | 327 | |
| 306 | 328 | thread_local! { |
| 307 | | − // (taken, contended). Read and written only between suspensions. |
| 308 | | − static MINE: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, 0)) }; |
| 329 | + // (taken, contended) per kind. Read and written only between |
| 330 | + // suspensions. |
| 331 | + static MINE: std::cell::Cell<[(u64, u64); KINDS]> = |
| 332 | + const { std::cell::Cell::new([(0, 0); KINDS]) }; |
| 309 | 333 | } |
| 310 | 334 | |
| 311 | | − pub(super) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { |
| 312 | | − let (taken, contended) = MINE.get(); |
| 313 | | − match m.try_lock() { |
| 335 | + fn count(kind: Kind, contended: bool) { |
| 336 | + let mut mine = MINE.get(); |
| 337 | + let (taken, found) = &mut mine[kind as usize]; |
| 338 | + *taken += 1; |
| 339 | + *found += u64::from(contended); |
| 340 | + MINE.set(mine); |
| 341 | + } |
| 342 | + |
| 343 | + fn counted<G, E>(kind: Kind, tried: Result<G, TryLockError<E>>, wait: impl FnOnce() -> G) -> G { |
| 344 | + match tried { |
| 314 | 345 | Ok(guard) => { |
| 315 | | − MINE.set((taken + 1, contended)); |
| 346 | + count(kind, false); |
| 316 | 347 | guard |
| 317 | 348 | } |
| 318 | 349 | Err(TryLockError::WouldBlock) => { |
| 319 | | − MINE.set((taken + 1, contended + 1)); |
| 320 | | − m.lock().expect("louise: actor poisoned") |
| 350 | + count(kind, true); |
| 351 | + wait() |
| 321 | 352 | } |
| 322 | | − Err(TryLockError::Poisoned(_)) => panic!("louise: actor poisoned"), |
| 353 | + Err(TryLockError::Poisoned(_)) => panic!("louise: scheduler poisoned"), |
| 323 | 354 | } |
| 324 | 355 | } |
| 325 | 356 | |
| 357 | + pub(super) fn lock<T>(kind: Kind, m: &Mutex<T>) -> MutexGuard<'_, T> { |
| 358 | + counted(kind, m.try_lock(), || { |
| 359 | + m.lock().expect("louise: scheduler poisoned") |
| 360 | + }) |
| 361 | + } |
| 362 | + |
| 363 | + pub(super) fn read<T>(m: &RwLock<T>) -> RwLockReadGuard<'_, T> { |
| 364 | + counted(Kind::TableRead, m.try_read(), || { |
| 365 | + m.read().expect("louise: scheduler poisoned") |
| 366 | + }) |
| 367 | + } |
| 368 | + |
| 369 | + pub(super) fn write<T>(m: &RwLock<T>) -> RwLockWriteGuard<'_, T> { |
| 370 | + counted(Kind::TableWrite, m.try_write(), || { |
| 371 | + m.write().expect("louise: scheduler poisoned") |
| 372 | + }) |
| 373 | + } |
| 374 | + |
| 326 | 375 | /// Add this thread's counts to the totals. |
| 327 | 376 | pub(super) fn flush() { |
| 328 | | − let (taken, contended) = MINE.replace((0, 0)); |
| 329 | | − TAKEN.fetch_add(taken, Ordering::Relaxed); |
| 330 | | − CONTENDED.fetch_add(contended, Ordering::Relaxed); |
| 377 | + for (i, (taken, contended)) in MINE.replace([(0, 0); KINDS]).into_iter().enumerate() { |
| 378 | + TAKEN[i].fetch_add(taken, Ordering::Relaxed); |
| 379 | + CONTENDED[i].fetch_add(contended, Ordering::Relaxed); |
| 380 | + } |
| 331 | 381 | } |
| 332 | 382 | |
| 333 | | − /// (taken, contended), once the scheduler threads stopped. |
| 334 | | − pub(crate) fn totals() -> (u64, u64) { |
| 335 | | − ( |
| 336 | | − TAKEN.load(Ordering::Relaxed), |
| 337 | | − CONTENDED.load(Ordering::Relaxed), |
| 338 | | − ) |
| 383 | + /// (taken, contended) per kind, once the scheduler threads stopped. |
| 384 | + pub(crate) fn totals() -> [(u64, u64); KINDS] { |
| 385 | + std::array::from_fn(|i| { |
| 386 | + ( |
| 387 | + TAKEN[i].load(Ordering::Relaxed), |
| 388 | + CONTENDED[i].load(Ordering::Relaxed), |
| 389 | + ) |
| 390 | + }) |
| 339 | 391 | } |
| 340 | 392 | } |
| 341 | 393 | |
| @@ -362,8 +414,83 @@ struct Control { |
| 362 | 414 | /// edge-triggered, and another thread may poll between an actor's |
| 363 | 415 | /// `WouldBlock` and its parking: the actor then retries instead. |
| 364 | 416 | io_ready: HashSet<mio::Token>, |
| 365 | | − /// Stacks of `PROGRAM_STACK_SIZE` whose fibers finished. |
| 366 | | − stacks: Vec<Stack>, |
| 417 | +} |
| 418 | + |
| 419 | +/// The actor table: every actor whose fiber has not finished, by pid. |
| 420 | +/// |
| 421 | +/// In [`SHARDS`] parts by pid, each behind its own lock (issue #131): one |
| 422 | +/// lock was taken for every lookup of another actor (a send, a link) and |
| 423 | +/// every spawn and finish, and on 22 threads `tests/bench/churn.lse` |
| 424 | +/// found it taken for 58% of its reads and 86% of its writes. Consecutive |
| 425 | +/// pids fall in different shards. |
| 426 | +struct Table { |
| 427 | + shards: [RwLock<IdMap<Arc<Cell>>>; SHARDS], |
| 428 | + /// The number of actors, kept beside the shards: whether the table |
| 429 | + /// is empty is known when an actor is removed without locking them all. |
| 430 | + live: AtomicUsize, |
| 431 | +} |
| 432 | + |
| 433 | +const SHARDS: usize = 64; |
| 434 | + |
| 435 | +impl Default for Table { |
| 436 | + fn default() -> Table { |
| 437 | + Table { |
| 438 | + shards: std::array::from_fn(|_| RwLock::new(IdMap::default())), |
| 439 | + live: AtomicUsize::new(0), |
| 440 | + } |
| 441 | + } |
| 442 | +} |
| 443 | + |
| 444 | +impl Table { |
| 445 | + fn shard(&self, pid: i64) -> &RwLock<IdMap<Arc<Cell>>> { |
| 446 | + &self.shards[pid as usize % SHARDS] |
| 447 | + } |
| 448 | + |
| 449 | + fn read(&self, pid: i64) -> RwLockReadGuard<'_, IdMap<Arc<Cell>>> { |
| 450 | + #[cfg(feature = "lock-stats")] |
| 451 | + return lock_stats::read(self.shard(pid)); |
| 452 | + #[cfg(not(feature = "lock-stats"))] |
| 453 | + self.shard(pid).read().expect("louise: scheduler poisoned") |
| 454 | + } |
| 455 | + |
| 456 | + fn write(&self, pid: i64) -> RwLockWriteGuard<'_, IdMap<Arc<Cell>>> { |
| 457 | + #[cfg(feature = "lock-stats")] |
| 458 | + return lock_stats::write(self.shard(pid)); |
| 459 | + #[cfg(not(feature = "lock-stats"))] |
| 460 | + self.shard(pid).write().expect("louise: scheduler poisoned") |
| 461 | + } |
| 462 | + |
| 463 | + fn get(&self, pid: i64) -> Option<Arc<Cell>> { |
| 464 | + self.read(pid).get(&pid).cloned() |
| 465 | + } |
| 466 | + |
| 467 | + /// Add a new actor. Counted first: an actor it spawns can only finish |
| 468 | + /// after this. |
| 469 | + fn insert(&self, pid: i64, cell: Arc<Cell>) { |
| 470 | + self.live.fetch_add(1, Ordering::AcqRel); |
| 471 | + self.write(pid).insert(pid, cell); |
| 472 | + } |
| 473 | + |
| 474 | + /// Remove a finished actor; whether it was the last. |
| 475 | + fn remove(&self, pid: i64) -> bool { |
| 476 | + let removed = self.write(pid).remove(&pid).is_some(); |
| 477 | + removed && self.live.fetch_sub(1, Ordering::AcqRel) == 1 |
| 478 | + } |
| 479 | + |
| 480 | + /// Every actor, in pid order (the order they were spawned in, as the |
| 481 | + /// interpreter keeps them). |
| 482 | + fn all(&self) -> Vec<(i64, Arc<Cell>)> { |
| 483 | + let mut all: Vec<(i64, Arc<Cell>)> = Vec::new(); |
| 484 | + for shard in &self.shards { |
| 485 | + #[cfg(feature = "lock-stats")] |
| 486 | + let shard = lock_stats::read(shard); |
| 487 | + #[cfg(not(feature = "lock-stats"))] |
| 488 | + let shard = shard.read().expect("louise: scheduler poisoned"); |
| 489 | + all.extend(shard.iter().map(|(pid, cell)| (*pid, cell.clone()))); |
| 490 | + } |
| 491 | + all.sort_unstable_by_key(|(pid, _)| *pid); |
| 492 | + all |
| 493 | + } |
| 367 | 494 | } |
| 368 | 495 | |
| 369 | 496 | /// The scheduler, shared by its threads. |
| @@ -371,11 +498,16 @@ struct Control { |
| 371 | 498 | /// **Lock order:** `control`, then the right to fire timers, then one |
| 372 | 499 | /// timer heap, then an actor's `proc` lock, then the sleepers' lock. A |
| 373 | 500 | /// thread holding one never takes an earlier one, and holds at most one |
| 374 | | −/// actor lock. The actor table is held only for one map operation, never |
| 375 | | −/// while taking another lock, so it may be read under any of them (timers |
| 376 | | −/// find their actors through it while holding `control` and a heap). |
| 501 | +/// actor lock. The actor table (one shard of it) and the stack pool are |
| 502 | +/// each held only for one operation, never while taking another lock, so |
| 503 | +/// they may be taken under any of them (timers find their actors through |
| 504 | +/// the table while holding `control` and a heap). |
| 377 | 505 | pub(crate) struct Shared { |
| 378 | | − actors: RwLock<IdMap<Arc<Cell>>>, |
| 506 | + actors: Table, |
| 507 | + /// Stacks of `PROGRAM_STACK_SIZE` whose fibers finished, for new |
| 508 | + /// actors. Its own lock: under `control`, spawning and finishing |
| 509 | + /// actors waited on sockets and blocking calls. |
| 510 | + stacks: Mutex<Vec<Stack>>, |
| 379 | 511 | next_pid: AtomicI64, |
| 380 | 512 | next_tag: AtomicI64, |
| 381 | 513 | /// Time in milliseconds: virtual (jumps happen under `control`), or |
| @@ -662,7 +794,8 @@ pub(crate) unsafe fn this<'a>(ctx: *mut Ctx) -> (&'a Actor, &'a Shared) { |
| 662 | 794 | impl Shared { |
| 663 | 795 | fn new(threads: usize) -> Shared { |
| 664 | 796 | Shared { |
| 665 | | − actors: RwLock::new(IdMap::default()), |
| 797 | + actors: Table::default(), |
| 798 | + stacks: Mutex::new(Vec::new()), |
| 666 | 799 | next_pid: AtomicI64::new(0), |
| 667 | 800 | next_tag: AtomicI64::new(0), |
| 668 | 801 | clock: AtomicU64::new(0), |
| @@ -692,15 +825,22 @@ impl Shared { |
| 692 | 825 | } |
| 693 | 826 | |
| 694 | 827 | fn control(&self) -> MutexGuard<'_, Control> { |
| 828 | + #[cfg(feature = "lock-stats")] |
| 829 | + return lock_stats::lock(lock_stats::Kind::Control, &self.control); |
| 830 | + #[cfg(not(feature = "lock-stats"))] |
| 695 | 831 | self.control.lock().expect("louise: scheduler poisoned") |
| 696 | 832 | } |
| 697 | 833 | |
| 834 | + /// The pool of finished program stacks. |
| 835 | + fn stacks(&self) -> MutexGuard<'_, Vec<Stack>> { |
| 836 | + #[cfg(feature = "lock-stats")] |
| 837 | + return lock_stats::lock(lock_stats::Kind::Stacks, &self.stacks); |
| 838 | + #[cfg(not(feature = "lock-stats"))] |
| 839 | + self.stacks.lock().expect("louise: scheduler poisoned") |
| 840 | + } |
| 841 | + |
| 698 | 842 | fn cell(&self, pid: i64) -> Option<Arc<Cell>> { |
| 699 | | − self.actors |
| 700 | | − .read() |
| 701 | | − .expect("louise: scheduler poisoned") |
| 702 | | − .get(&pid) |
| 703 | | − .cloned() |
| 843 | + self.actors.get(pid) |
| 704 | 844 | } |
| 705 | 845 | |
| 706 | 846 | /// Put `message` (owned) in `pid`'s inbox on `tag`, and wake `pid` if |
| @@ -935,7 +1075,7 @@ fn spawn_actor( |
| 935 | 1075 | .filter(|_| tie == Tie::Monitor) |
| 936 | 1076 | .map(|watcher| (watcher, sched.tag())); |
| 937 | 1077 | let pooled = (stack_size == PROGRAM_STACK_SIZE) |
| 938 | | − .then(|| sched.control().stacks.pop()) |
| 1078 | + .then(|| sched.stacks().pop()) |
| 939 | 1079 | .flatten(); |
| 940 | 1080 | let stack = pooled |
| 941 | 1081 | .unwrap_or_else(|| Stack::new(stack_size).expect("louise: cannot allocate actor stack")); |
| @@ -992,11 +1132,7 @@ fn spawn_actor( |
| 992 | 1132 | (*a).ctx.rt = a.cast(); |
| 993 | 1133 | (*a).cell = Arc::as_ptr(&cell); |
| 994 | 1134 | } |
| 995 | | − sched |
| 996 | | − .actors |
| 997 | | − .write() |
| 998 | | − .expect("louise: scheduler poisoned") |
| 999 | | − .insert(pid, cell); |
| 1135 | + sched.actors.insert(pid, cell); |
| 1000 | 1136 | LIVE_ACTORS.fetch_add(1, Ordering::Relaxed); |
| 1001 | 1137 | // The parent links once the child exists (so the parent's exit always |
| 1002 | 1138 | // reaches it), and before it can run. |
| @@ -1074,9 +1210,7 @@ unsafe fn run_body(a: *mut Actor, body: Body) { |
| 1074 | 1210 | let sched = &*(*a).sched; |
| 1075 | 1211 | exit_actor(sched, (*a).pid, reason); |
| 1076 | 1212 | // Release what the actor still owns. Nobody delivers to it now. |
| 1077 | | − let (mut mailbox, wake) = sched |
| 1078 | | − .with_proc((*a).pid, |p| p.release((*a).inbox())) |
| 1079 | | − .expect("louise: running actor vanished"); |
| 1213 | + let (mut mailbox, wake) = (*a).with_proc(|p| p.release((*a).inbox())); |
| 1080 | 1214 | for message in mailbox.drain() { |
| 1081 | 1215 | drop_value(ctx, message); |
| 1082 | 1216 | } |
| @@ -1145,13 +1279,7 @@ pub(crate) fn exit_actor(sched: &Shared, pid: i64, reason: Exit) { |
| 1145 | 1279 | /// `main` stopped: stop every other actor, silently. |
| 1146 | 1280 | fn stop_all(sched: &Shared) { |
| 1147 | 1281 | sched.stopping.store(true, Ordering::Release); |
| 1148 | | − let cells: Vec<(i64, Arc<Cell>)> = sched |
| 1149 | | − .actors |
| 1150 | | − .read() |
| 1151 | | − .expect("louise: scheduler poisoned") |
| 1152 | | − .iter() |
| 1153 | | − .map(|(pid, cell)| (*pid, cell.clone())) |
| 1154 | | − .collect(); |
| 1282 | + let cells = sched.actors.all(); |
| 1155 | 1283 | for (pid, cell) in cells { |
| 1156 | 1284 | cell.kill.store(true, Ordering::Release); |
| 1157 | 1285 | let wake = { |
| @@ -1471,11 +1599,7 @@ fn run_slice(sched: &Shared, pid: i64) { |
| 1471 | 1599 | } |
| 1472 | 1600 | CoroutineResult::Return(()) => { |
| 1473 | 1601 | cell.lock().run.finish(); |
| 1474 | | − let empty = { |
| 1475 | | − let mut actors = sched.actors.write().expect("louise: scheduler poisoned"); |
| 1476 | | − actors.remove(&pid); |
| 1477 | | − actors.is_empty() |
| 1478 | | − }; |
| 1602 | + let empty = sched.actors.remove(pid); |
| 1479 | 1603 | drop(cell); |
| 1480 | 1604 | if fiber.stack_size == PROGRAM_STACK_SIZE { |
| 1481 | 1605 | let stack = fiber.co.into_stack(); |
| @@ -1485,12 +1609,16 @@ fn run_slice(sched: &Shared, pid: i64) { |
| 1485 | 1609 | // (ADR 0028). |
| 1486 | 1610 | std::mem::forget(stack); |
| 1487 | 1611 | } else { |
| 1488 | | − let mut c = sched.control(); |
| 1489 | | − if c.stacks.len() < STACK_POOL { |
| 1490 | | − if c.stacks.len() >= WARM_STACKS { |
| 1612 | + // The pool has its own lock, and the system calls |
| 1613 | + // (`madvise` for a cold stack, `munmap` past the pool) |
| 1614 | + // are made outside it. Two threads may both see room: |
| 1615 | + // the bounds are loose by a few stacks. |
| 1616 | + let pooled = sched.stacks().len(); |
| 1617 | + if pooled < STACK_POOL { |
| 1618 | + if pooled >= WARM_STACKS { |
| 1491 | 1619 | stack.release(); |
| 1492 | 1620 | } |
| 1493 | | − c.stacks.push(stack); |
| 1621 | + sched.stacks().push(stack); |
| 1494 | 1622 | } |
| 1495 | 1623 | } |
| 1496 | 1624 | } |
| @@ -1609,13 +1737,7 @@ fn idle(sched: &Shared) { |
| 1609 | 1737 | |
| 1610 | 1738 | /// Nothing can ever run again: crash the root (stopping everyone). |
| 1611 | 1739 | fn deadlock(sched: &Shared) { |
| 1612 | | − let alive: Vec<i64> = sched |
| 1613 | | − .actors |
| 1614 | | − .read() |
| 1615 | | − .expect("louise: scheduler poisoned") |
| 1616 | | − .keys() |
| 1617 | | − .copied() |
| 1618 | | − .collect(); |
| 1740 | + let alive: Vec<i64> = sched.actors.all().into_iter().map(|(pid, _)| pid).collect(); |
| 1619 | 1741 | exit_actor( |
| 1620 | 1742 | sched, |
| 1621 | 1743 | sched.root.load(Ordering::Acquire), |
| @@ -1889,7 +2011,7 @@ pub unsafe extern "C" fn tl_main_program(entry: EntryFn) -> i32 { |
| 1889 | 2011 | let exit = run(&sched, root, threads); |
| 1890 | 2012 | // The process exits next, which frees the pooled stacks' mappings at |
| 1891 | 2013 | // once: no `munmap` each. (The list itself is freed, for LeakSanitizer.) |
| 1892 | | − for stack in std::mem::take(&mut sched.control().stacks) { |
| 2014 | + for stack in std::mem::take(&mut *sched.stacks()) { |
| 1893 | 2015 | std::mem::forget(stack); |
| 1894 | 2016 | } |
| 1895 | 2017 | // Every actor stopped: write what they printed before reporting. |