| @@ -44,16 +44,17 @@ |
| 44 | 44 | //! Invariant: no scheduler lock is held while actor code runs. |
| 45 | 45 | |
| 46 | 46 | use std::cell::RefCell; |
| 47 | | −use std::collections::{HashMap, HashSet}; |
| 48 | | −use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}; |
| 47 | +use std::collections::{HashMap, HashSet, VecDeque}; |
| 48 | +use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering}; |
| 49 | 49 | use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLock}; |
| 50 | +use std::time::{Duration, Instant}; |
| 50 | 51 | |
| 51 | 52 | use crossbeam_deque::{Injector, Steal, Stealer, Worker}; |
| 52 | 53 | |
| 53 | | −use crate::fiber::{Coroutine, CoroutineResult, Stack, Yielder}; |
| 54 | +use crate::fiber::{Coroutine, CoroutineResult, Snapshot, Stack, Yielder}; |
| 54 | 55 | use crate::handoff::Sleepers; |
| 55 | 56 | use crate::inbox::Inbox; |
| 56 | | −use crate::otp::{Exited, Links}; |
| 57 | +use crate::otp::{Exited, Links, Wait}; |
| 57 | 58 | use crate::timers::{Firing, Timer, Timers}; |
| 58 | 59 | |
| 59 | 60 | use crate::abi::{ |
| @@ -77,6 +78,16 @@ const WAKER: mio::Token = mio::Token(0); |
| 77 | 78 | /// Finished program stacks kept for reuse: mapping and unmapping one per |
| 78 | 79 | /// actor is slow, and with several threads every unmap interrupts them all. |
| 79 | 80 | const STACK_POOL: usize = 256; |
| 81 | +/// How long a parked actor stays warm, in wall time, before its stack is |
| 82 | +/// hibernated: it is looked at again two epochs after it was listed, so |
| 83 | +/// after 50 to 150 ms (ADR 0028). `LOUISE_PARKED_EPOCH_MS` changes it; at |
| 84 | +/// 0, every parked actor is hibernated at the next look, which tests |
| 85 | +/// hibernation with every program (`scripts/ci.sh`). An actor that waits less |
| 86 | +/// (a ring passing a token, a server between calls) never pays the page |
| 87 | +/// fault and the copy of a thaw. Wall time, not the scheduler's clock, |
| 88 | +/// which in virtual time stays put while actors run: hibernating changes |
| 89 | +/// no behaviour, only memory. |
| 90 | +const PARKED_EPOCH: Duration = Duration::from_millis(50); |
| 80 | 91 | |
| 81 | 92 | static LIVE_ACTORS: AtomicI64 = AtomicI64::new(0); |
| 82 | 93 | /// Set by `tl_main_program`: the root's crash is reported by it, as |
| @@ -87,8 +98,30 @@ type EntryFn = unsafe extern "C" fn(*mut Ctx) -> Value; |
| 87 | 98 | type ActorClosureFn = unsafe extern "C" fn(*mut Ctx, Value) -> Value; |
| 88 | 99 | |
| 89 | 100 | /// An actor's fiber, movable between scheduler threads. |
| 90 | | −/// The second field is the stack size. |
| 91 | | −pub(crate) struct Fiber(Coroutine<(), (), ()>, usize); |
| 101 | +pub(crate) struct Fiber { |
| 102 | + co: Coroutine<(), (), ()>, |
| 103 | + stack_size: usize, |
| 104 | + /// Its stack while hibernated: it is written back before the fiber |
| 105 | + /// resumes. |
| 106 | + saved: Option<Snapshot>, |
| 107 | +} |
| 108 | + |
| 109 | +impl Fiber { |
| 110 | + /// Save the stack of this suspended fiber and give its memory back, |
| 111 | + /// where the target can (`fiber::Coroutine::hibernate`). |
| 112 | + fn hibernate(&mut self) { |
| 113 | + if self.saved.is_none() { |
| 114 | + self.saved = self.co.hibernate(); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + /// Before resuming: write a hibernated stack back in place. |
| 119 | + fn thaw(&mut self) { |
| 120 | + if let Some(snap) = self.saved.take() { |
| 121 | + self.co.restore(&snap); |
| 122 | + } |
| 123 | + } |
| 124 | +} |
| 92 | 125 | |
| 93 | 126 | // SAFETY: a suspended fiber is its stack and saved registers (`fiber`), |
| 94 | 127 | // so it can resume on any thread, provided no frame on it keeps the |
| @@ -221,6 +254,12 @@ pub(crate) struct Cell { |
| 221 | 254 | /// Where senders put messages, without the lock (ADR 0028). |
| 222 | 255 | inbox: Inbox<Value>, |
| 223 | 256 | proc: Mutex<Proc>, |
| 257 | + /// In a thread's list of parked actors (`Parked`). Read and written |
| 258 | + /// under `proc`'s lock: atomics only to share the cell. |
| 259 | + listed: AtomicBool, |
| 260 | + /// The epoch its current wait began in (`Shared::epoch`), under the |
| 261 | + /// same lock. |
| 262 | + parked_epoch: AtomicU32, |
| 224 | 263 | } |
| 225 | 264 | |
| 226 | 265 | impl Cell { |
| @@ -342,6 +381,14 @@ pub(crate) struct Shared { |
| 342 | 381 | idling: AtomicBool, |
| 343 | 382 | /// Every actor is gone: the threads stop. |
| 344 | 383 | finished: AtomicBool, |
| 384 | + /// Wall time, in [`PARKED_EPOCH`]s, for hibernating parked actors: |
| 385 | + /// counted by whichever thread sees one pass. |
| 386 | + epoch: AtomicU32, |
| 387 | + /// When the current epoch began, in nanoseconds since `started`. |
| 388 | + epoch_at: AtomicU64, |
| 389 | + started: Instant, |
| 390 | + /// [`PARKED_EPOCH`], or `LOUISE_PARKED_EPOCH_MS`, in nanoseconds. |
| 391 | + epoch_ns: u64, |
| 345 | 392 | sleepers: Sleepers, |
| 346 | 393 | /// Interrupts the idle thread's wait on the reactor. |
| 347 | 394 | waker: OnceLock<Arc<mio::Waker>>, |
| @@ -356,6 +403,32 @@ struct Local { |
| 356 | 403 | /// Its index among the scheduler's threads. |
| 357 | 404 | index: usize, |
| 358 | 405 | queue: Worker<i64>, |
| 406 | + /// The actors that parked here, oldest first, to hibernate. |
| 407 | + parked: Parked, |
| 408 | +} |
| 409 | + |
| 410 | +/// Actors that parked on this thread (`run_slice`), oldest first, each at |
| 411 | +/// most once (`Cell::listed`), with the epoch it was listed in. Two epochs |
| 412 | +/// later the thread looks at it again: hibernated if it is still in a wait |
| 413 | +/// that began two epochs ago, listed again if it parked since, dropped if |
| 414 | +/// it is running or gone. |
| 415 | +struct Parked { |
| 416 | + list: VecDeque<(i64, u32)>, |
| 417 | + /// Calls since the clock was last read. |
| 418 | + count: u32, |
| 419 | +} |
| 420 | + |
| 421 | +impl Parked { |
| 422 | + /// The entries two epochs old, at `epoch`. |
| 423 | + fn due(&mut self, epoch: u32, out: &mut Vec<i64>) { |
| 424 | + while let Some(&(pid, listed)) = self.list.front() { |
| 425 | + if listed.wrapping_add(2) > epoch { |
| 426 | + break; |
| 427 | + } |
| 428 | + self.list.pop_front(); |
| 429 | + out.push(pid); |
| 430 | + } |
| 431 | + } |
| 359 | 432 | } |
| 360 | 433 | |
| 361 | 434 | /// Slots in a thread's [`SendCache`]. |
| @@ -578,6 +651,13 @@ impl Shared { |
| 578 | 651 | running: AtomicUsize::new(0), |
| 579 | 652 | idling: AtomicBool::new(false), |
| 580 | 653 | finished: AtomicBool::new(false), |
| 654 | + epoch: AtomicU32::new(0), |
| 655 | + epoch_at: AtomicU64::new(0), |
| 656 | + started: Instant::now(), |
| 657 | + epoch_ns: std::env::var("LOUISE_PARKED_EPOCH_MS") |
| 658 | + .ok() |
| 659 | + .and_then(|ms| ms.parse::<u64>().ok()) |
| 660 | + .map_or(PARKED_EPOCH.as_nanos() as u64, |ms| ms * 1_000_000), |
| 581 | 661 | sleepers: Sleepers::new(), |
| 582 | 662 | waker: OnceLock::new(), |
| 583 | 663 | io_waiting: AtomicUsize::new(0), |
| @@ -867,8 +947,14 @@ fn spawn_actor( |
| 867 | 947 | actor: a, |
| 868 | 948 | kill: AtomicBool::new(false), |
| 869 | 949 | inbox: Inbox::new(), |
| 950 | + listed: AtomicBool::new(false), |
| 951 | + parked_epoch: AtomicU32::new(0), |
| 870 | 952 | proc: Mutex::new(Proc::new( |
| 871 | | − Fiber(fiber, stack_size), |
| 953 | + Fiber { |
| 954 | + co: fiber, |
| 955 | + stack_size, |
| 956 | + saved: None, |
| 957 | + }, |
| 872 | 958 | links, |
| 873 | 959 | monitor.into_iter().collect(), |
| 874 | 960 | )), |
| @@ -1112,12 +1198,17 @@ fn worker(sched: &Shared, index: usize, queue: Worker<i64>) { |
| 1112 | 1198 | owner: sched as *const Shared as usize, |
| 1113 | 1199 | index, |
| 1114 | 1200 | queue, |
| 1201 | + parked: Parked { |
| 1202 | + list: VecDeque::new(), |
| 1203 | + count: 0, |
| 1204 | + }, |
| 1115 | 1205 | }) |
| 1116 | 1206 | }); |
| 1117 | 1207 | loop { |
| 1118 | 1208 | if sched.finished.load(Ordering::SeqCst) { |
| 1119 | 1209 | break; |
| 1120 | 1210 | } |
| 1211 | + hibernate_due(sched, false); |
| 1121 | 1212 | collect_events(sched); |
| 1122 | 1213 | if let Some(pid) = find_work(sched, index) { |
| 1123 | 1214 | // More queued than this one: wake a thread for it, which does |
| @@ -1135,12 +1226,16 @@ fn worker(sched: &Shared, index: usize, queue: Worker<i64>) { |
| 1135 | 1226 | continue; |
| 1136 | 1227 | } |
| 1137 | 1228 | if sched.running.load(Ordering::SeqCst) > 0 || sched.idling.load(Ordering::SeqCst) { |
| 1138 | | − sched.sleepers.sleep(|| { |
| 1139 | | − sched.pending.load(Ordering::SeqCst) == 0 |
| 1140 | | − && !sched.finished.load(Ordering::SeqCst) |
| 1141 | | − && (sched.running.load(Ordering::SeqCst) > 0 |
| 1142 | | − || sched.idling.load(Ordering::SeqCst)) |
| 1143 | | − }); |
| 1229 | + sched.sleepers.sleep( |
| 1230 | + || { |
| 1231 | + sched.pending.load(Ordering::SeqCst) == 0 |
| 1232 | + && !sched.finished.load(Ordering::SeqCst) |
| 1233 | + && (sched.running.load(Ordering::SeqCst) > 0 |
| 1234 | + || sched.idling.load(Ordering::SeqCst)) |
| 1235 | + }, |
| 1236 | + parked_timeout(sched), |
| 1237 | + ); |
| 1238 | + hibernate_due(sched, true); |
| 1144 | 1239 | continue; |
| 1145 | 1240 | } |
| 1146 | 1241 | if sched |
| @@ -1149,6 +1244,7 @@ fn worker(sched: &Shared, index: usize, queue: Worker<i64>) { |
| 1149 | 1244 | .is_ok() |
| 1150 | 1245 | { |
| 1151 | 1246 | idle(sched); |
| 1247 | + hibernate_due(sched, true); |
| 1152 | 1248 | sched.idling.store(false, Ordering::SeqCst); |
| 1153 | 1249 | sched.sleepers.notify(true); |
| 1154 | 1250 | } |
| @@ -1160,6 +1256,100 @@ fn worker(sched: &Shared, index: usize, queue: Worker<i64>) { |
| 1160 | 1256 | lock_stats::flush(); |
| 1161 | 1257 | } |
| 1162 | 1258 | |
| 1259 | +/// Whether the actor waits in a way that nothing else reads its stack |
| 1260 | +/// in: a receive or a sleep. Not a blocking call (it runs on the actor's |
| 1261 | +/// values), nor a socket wait (short by design). |
| 1262 | +fn hibernatable(p: &Proc) -> bool { |
| 1263 | + matches!(p.wait, Wait::Receive { .. } | Wait::Sleep { .. }) && !p.dead |
| 1264 | +} |
| 1265 | + |
| 1266 | +/// The epoch now: counts one more if [`PARKED_EPOCH`] has passed. |
| 1267 | +fn epoch(sched: &Shared) -> u32 { |
| 1268 | + let now = sched.started.elapsed().as_nanos() as u64; |
| 1269 | + let at = sched.epoch_at.load(Ordering::Relaxed); |
| 1270 | + if now.saturating_sub(at) >= sched.epoch_ns |
| 1271 | + && sched |
| 1272 | + .epoch_at |
| 1273 | + .compare_exchange(at, now, Ordering::Relaxed, Ordering::Relaxed) |
| 1274 | + .is_ok() |
| 1275 | + { |
| 1276 | + sched.epoch.fetch_add(1, Ordering::Relaxed); |
| 1277 | + } |
| 1278 | + sched.epoch.load(Ordering::Relaxed) |
| 1279 | +} |
| 1280 | + |
| 1281 | +/// `pid` parked on this thread, and was not listed: list it. |
| 1282 | +fn parked_here(sched: &Shared, pid: i64) { |
| 1283 | + let epoch = sched.epoch.load(Ordering::Relaxed); |
| 1284 | + LOCAL.with(|l| { |
| 1285 | + if let Some(local) = l.borrow_mut().as_mut() { |
| 1286 | + local.parked.list.push_back((pid, epoch)); |
| 1287 | + } |
| 1288 | + }); |
| 1289 | +} |
| 1290 | + |
| 1291 | +/// Look again at this thread's listed actors that are due, and hibernate |
| 1292 | +/// those still parked since then (`check`: read the clock now, as after a |
| 1293 | +/// sleep; else every 256 calls). |
| 1294 | +fn hibernate_due(sched: &Shared, check: bool) { |
| 1295 | + let mut due = Vec::new(); |
| 1296 | + LOCAL.with(|l| { |
| 1297 | + if let Some(local) = l.borrow_mut().as_mut() |
| 1298 | + && !local.parked.list.is_empty() |
| 1299 | + { |
| 1300 | + let parked = &mut local.parked; |
| 1301 | + parked.count = parked.count.wrapping_add(1); |
| 1302 | + if check || sched.epoch_ns == 0 || parked.count.is_multiple_of(256) { |
| 1303 | + parked.due(epoch(sched), &mut due); |
| 1304 | + } |
| 1305 | + } |
| 1306 | + }); |
| 1307 | + for pid in due { |
| 1308 | + hibernate(sched, pid); |
| 1309 | + } |
| 1310 | +} |
| 1311 | + |
| 1312 | +/// How long this thread may sleep before it must hibernate parked actors: |
| 1313 | +/// an epoch if it has any, else as long as it likes. |
| 1314 | +fn parked_timeout(sched: &Shared) -> Option<Duration> { |
| 1315 | + LOCAL.with(|l| { |
| 1316 | + l.borrow() |
| 1317 | + .as_ref() |
| 1318 | + .is_some_and(|local| !local.parked.list.is_empty()) |
| 1319 | + .then(|| Duration::from_nanos(sched.epoch_ns.max(1_000_000))) |
| 1320 | + }) |
| 1321 | +} |
| 1322 | + |
| 1323 | +/// Hibernate `pid`'s stack if it has been parked for two epochs: under |
| 1324 | +/// its lock, suspended and not queued, nothing can resume it, and in a |
| 1325 | +/// receive or a sleep nothing else reads its stack. `run_slice` thaws it |
| 1326 | +/// before it runs again, whoever wakes it (a message, a timer, a kill). |
| 1327 | +/// Parked since less long: listed again. Running or gone: dropped (it is |
| 1328 | +/// listed again when it parks). |
| 1329 | +fn hibernate(sched: &Shared, pid: i64) { |
| 1330 | + let Some(cell) = sched.cell(pid) else { |
| 1331 | + return; |
| 1332 | + }; |
| 1333 | + let mut p = cell.lock(); |
| 1334 | + let since = cell.parked_epoch.load(Ordering::Relaxed); |
| 1335 | + let now = sched.epoch.load(Ordering::Relaxed); |
| 1336 | + let parked = hibernatable(&p); |
| 1337 | + match p.run.idle_fiber() { |
| 1338 | + Some(fiber) if parked && since.wrapping_add(2) <= now => fiber.hibernate(), |
| 1339 | + Some(_) if parked => { |
| 1340 | + drop(p); |
| 1341 | + LOCAL.with(|l| { |
| 1342 | + if let Some(local) = l.borrow_mut().as_mut() { |
| 1343 | + local.parked.list.push_back((pid, since)); |
| 1344 | + } |
| 1345 | + }); |
| 1346 | + return; |
| 1347 | + } |
| 1348 | + _ => {} |
| 1349 | + } |
| 1350 | + cell.listed.store(false, Ordering::Relaxed); |
| 1351 | +} |
| 1352 | + |
| 1163 | 1353 | /// The next actor for thread `index`: its own queue first (FIFO), then |
| 1164 | 1354 | /// the shared queue, then the other threads' queues. |
| 1165 | 1355 | fn find_work(sched: &Shared, index: usize) -> Option<i64> { |
| @@ -1211,11 +1401,12 @@ fn run_slice(sched: &Shared, pid: i64) { |
| 1211 | 1401 | stop_running(sched); |
| 1212 | 1402 | return; |
| 1213 | 1403 | }; |
| 1404 | + fiber.thaw(); |
| 1214 | 1405 | let a = cell.actor; |
| 1215 | 1406 | // SAFETY: the actor is live and runs on this thread only. |
| 1216 | 1407 | unsafe { (*a).ctx.reductions = REDUCTIONS }; |
| 1217 | 1408 | IN_SLICE.set(true); |
| 1218 | | − let result = fiber.0.resume(()); |
| 1409 | + let result = fiber.co.resume(()); |
| 1219 | 1410 | IN_SLICE.set(false); |
| 1220 | 1411 | // An actor queued during the slice woke nobody: this thread runs it |
| 1221 | 1412 | // next, and wakes another only if more is queued (`Shared::push`). |
| @@ -1224,10 +1415,19 @@ fn run_slice(sched: &Shared, pid: i64) { |
| 1224 | 1415 | } |
| 1225 | 1416 | match result { |
| 1226 | 1417 | CoroutineResult::Yield(()) => { |
| 1227 | | − let again = { |
| 1418 | + let (again, list) = { |
| 1228 | 1419 | let mut p = cell.lock(); |
| 1229 | | − p.stop(&cell.inbox, fiber) |
| 1420 | + let again = p.stop(&cell.inbox, fiber); |
| 1421 | + let parked = !again && hibernatable(&p); |
| 1422 | + if parked { |
| 1423 | + let epoch = sched.epoch.load(Ordering::Relaxed); |
| 1424 | + cell.parked_epoch.store(epoch, Ordering::Relaxed); |
| 1425 | + } |
| 1426 | + (again, parked && !cell.listed.swap(true, Ordering::Relaxed)) |
| 1230 | 1427 | }; |
| 1428 | + if list { |
| 1429 | + parked_here(sched, pid); |
| 1430 | + } |
| 1231 | 1431 | if again { |
| 1232 | 1432 | // Preempted (or woken while it ran): back into this |
| 1233 | 1433 | // thread's queue, without waking another thread to steal |
| @@ -1244,10 +1444,10 @@ fn run_slice(sched: &Shared, pid: i64) { |
| 1244 | 1444 | actors.is_empty() |
| 1245 | 1445 | }; |
| 1246 | 1446 | drop(cell); |
| 1247 | | − if fiber.1 == PROGRAM_STACK_SIZE { |
| 1447 | + if fiber.stack_size == PROGRAM_STACK_SIZE { |
| 1248 | 1448 | let mut c = sched.control(); |
| 1249 | 1449 | if c.stacks.len() < STACK_POOL { |
| 1250 | | − c.stacks.push(fiber.0.into_stack()); |
| 1450 | + c.stacks.push(fiber.co.into_stack()); |
| 1251 | 1451 | } |
| 1252 | 1452 | } |
| 1253 | 1453 | // SAFETY: the fiber has returned; nothing refers to the actor. |
| @@ -1345,6 +1545,11 @@ fn idle(sched: &Shared) { |
| 1345 | 1545 | let timeout = deadline |
| 1346 | 1546 | .filter(|_| real_time) |
| 1347 | 1547 | .map(|d| std::time::Duration::from_millis(d.saturating_sub(sched.clock()))); |
| 1548 | + // Wake up to hibernate this thread's parked actors as they age. |
| 1549 | + let timeout = match (timeout, parked_timeout(sched)) { |
| 1550 | + (Some(t), Some(p)) => Some(t.min(p)), |
| 1551 | + (t, p) => t.or(p), |
| 1552 | + }; |
| 1348 | 1553 | (poll, timeout) |
| 1349 | 1554 | }; |
| 1350 | 1555 | let mut events = mio::Events::with_capacity(256); |