//! What a scheduler thread keeps to itself: its run queue ([`Local`]), its //! send cache, and the thread-locals they live in. On an actor's fiber, //! these are read only in the `#[inline(never)]` functions here, which //! never suspend (see `Fiber`'s `Send`). use std::cell::RefCell; use std::sync::Arc; use crossbeam_deque::{Steal, Worker}; use crate::abi::{UNIT, Value}; use super::Shared; use super::actor::Cell; use super::hibernate::Parked; /// What a scheduler thread keeps to itself. pub(super) struct Local { /// Its scheduler's address. pub(super) owner: usize, /// Its index among the scheduler's threads. pub(super) index: usize, pub(super) queue: Worker, /// The actor woken by the one running here, to run next (Tokio's LIFO /// slot, Go's `runnext`): its caches are warm, and no other thread may /// take it. Only with more than one thread (one keeps FIFO order). pub(super) next: Option, /// Actors run from `next` in a row: two actors waking each other would /// otherwise starve the queue (Tokio 1.29, #5686). pub(super) streak: u8, /// For [`Local::random`]. pub(super) seed: u64, /// The actors that parked here, oldest first, to hibernate. pub(super) parked: Parked, } /// Actors run from a thread's next slot in a row, at most (Tokio's cap). const NEXT_STREAK: u8 = 3; /// Where [`place_here`] put an actor. pub(super) enum Placed { /// In this thread's next slot: it runs after this slice. Next, /// At the back of this thread's queue; `true` if it is spare work /// another thread should take: queued during a slice (this thread is /// busy), or behind another actor. Queued(bool), /// In the inbound queue of its home, this other thread /// (`Shared::queue`). Inbound(usize), /// Not on this thread: its home is another one, or this is not one of /// the scheduler's threads (`Shared::queue` puts it in the shared /// queue if it has no home). Elsewhere, } /// Slots in a thread's [`SendCache`]. const SEND_CACHE_SLOTS: usize = 64; /// The cells of the actors this thread sent to last, by pid (ADR 0028). /// Finding a receiver in the actor table takes its read lock and clones /// the cell's `Arc`: two atomic writes to lines every sender shares, 15% of /// `tests/bench/fanin.lse`'s user time on 22 threads. A hit writes nothing /// shared. /// /// A pid is cached on its second miss in a row in its slot: a thread that /// sends to many actors in turn (a ring of 1,000) would otherwise evict an /// entry on every send, which made `tests/bench/messages.lse` 4% slower /// than with no cache. /// /// A cached cell may outlive its actor: its inbox is closed then, so a /// send to it is refused, as one to a pid no longer in the table is. Pids /// are never reused. At most `SEND_CACHE_SLOTS` cells per thread stay /// alive this way, until evicted or the thread stops. pub(super) struct SendCache { /// The scheduler the cells belong to (pids are its own). owner: usize, slots: [Slot; SEND_CACHE_SLOTS], } /// A cell found by [`SendCache::get`]. pub(super) enum Lookup { /// Kept alive by the cache until this thread's next lookup. Cached(*const Cell), /// Not cached (yet). Found(Arc), } struct Slot { cell: Option<(i64, Arc)>, /// The last pid that missed here. missed: i64, } const EMPTY_SLOT: Slot = Slot { cell: None, missed: 0, }; impl SendCache { /// `pid`'s cell; `None` if `pid` is not in the table. pub(super) fn get(&mut self, sched: &Shared, pid: i64) -> Option { let owner = sched as *const Shared as usize; if self.owner != owner { self.clear(); self.owner = owner; } let slot = &mut self.slots[pid as usize % SEND_CACHE_SLOTS]; if let Some((p, cell)) = &slot.cell && *p == pid { return Some(Lookup::Cached(Arc::as_ptr(cell))); } let cell = sched.cell(pid)?; if slot.missed != pid { slot.missed = pid; return Some(Lookup::Found(cell)); } let ptr = Arc::as_ptr(&cell); slot.cell = Some((pid, cell)); Some(Lookup::Cached(ptr)) } pub(super) fn clear(&mut self) { self.slots = [EMPTY_SLOT; SEND_CACHE_SLOTS]; } } thread_local! { /// This scheduler thread's run queue and index. Only touched briefly /// (never held across a fiber switch). pub(super) static LOCAL: RefCell> = const { RefCell::new(None) }; /// The call arguments after the sixth (`Ctx::xargs`) of the actors /// this thread runs: written by a caller, copied by the callee before /// it can suspend. pub(super) static XARGS: std::cell::UnsafeCell<[Value; crate::abi::XARGS]> = const { std::cell::UnsafeCell::new([UNIT; crate::abi::XARGS]) }; /// Read and written only within one send, which never suspends. pub(super) static SEND_CACHE: RefCell = const { RefCell::new(SendCache { owner: 0, slots: [EMPTY_SLOT; SEND_CACHE_SLOTS], }) }; /// Times this thread found the shared queue holding actors /// ([`shared_turn`]). static SHARED_SEEN: std::cell::Cell = const { std::cell::Cell::new(0) }; /// Set while this thread runs an actor's slice (see [`place_here`]). pub(super) static IN_SLICE: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// Push to this thread's queue if it is one of `sched`'s threads. #[inline(never)] pub(super) fn push_local(sched: &Shared, pid: i64) -> bool { LOCAL.with(|l| match &*l.borrow() { Some(local) if local.owner == sched as *const Shared as usize => { local.queue.push(pid); true } _ => false, }) } /// Queue `pid`, whose home thread is `home`, here if this is that thread /// (or it has none yet): during a slice, in the next slot (an occupant /// moves to the back of the queue), else at the back of the queue. Not /// inlined (see `Fiber`). #[inline(never)] pub(super) fn place_here(sched: &Shared, pid: i64, home: usize) -> Placed { LOCAL.with(|l| match &mut *l.borrow_mut() { Some(local) if local.owner == sched as *const Shared as usize && (home == local.index || home == super::NO_HOME) => { if IN_SLICE.get() && sched.threads() > 1 { match local.next.replace(pid) { None => Placed::Next, Some(displaced) => { local.queue.push(displaced); Placed::Queued(true) } } } else { local.queue.push(pid); Placed::Queued(IN_SLICE.get() || local.queue.len() > 1) } } _ => Placed::Elsewhere, }) } /// One time in this many that a thread finds actors in the shared queue, /// it takes them before its own (`find_work`). Tokio's figure: rare enough /// to keep each thread's queue in order, often enough that an actor /// queued there waits for a few dozen slices at most. pub(super) const SHARED_TURN: u32 = 61; /// Whether it is the shared queue's turn ([`SHARED_TURN`]). Called on the /// scheduler thread's own stack only. pub(super) fn shared_turn() -> bool { let seen = SHARED_SEEN.get().wrapping_add(1); SHARED_SEEN.set(seen); seen.is_multiple_of(SHARED_TURN) } /// The next actor for this thread from its own work: its next slot (at /// most [`NEXT_STREAK`] in a row), the actors other threads queued for it /// (moved behind its own), its queue, then the shared queue. But one time /// in [`SHARED_TURN`] that the shared queue holds actors, it comes first: /// actors queued from outside the scheduler with no home yet land there, /// and a thread whose own work never runs out would never run them. pub(super) fn local_work(sched: &Shared, index: usize) -> Option { LOCAL.with(|l| { let mut l = l.borrow_mut(); let local = l.as_mut()?; if !sched.injector.is_empty() && shared_turn() && let Steal::Success(pid) = sched.injector.steal_batch_and_pop(&local.queue) { return Some(pid); } if let Some(pid) = local.next.take() { if local.streak < NEXT_STREAK { local.streak += 1; super::stat!(Next); return Some(pid); } local.queue.push(pid); } local.streak = 0; let inbound = sched.inbound(index); while !inbound.is_empty() { if let Steal::Empty = inbound.steal_batch(&local.queue) { break; } } if let Some(pid) = local.queue.pop() { return Some(pid); } loop { match sched.injector.steal_batch_and_pop(&local.queue) { Steal::Success(pid) => return Some(pid), Steal::Retry => continue, Steal::Empty => return None, } } }) } /// Steal from another thread's queues, starting at a random one (half of /// what it holds, `Shared::stealable`). pub(super) fn steal(sched: &Shared, index: usize) -> Option { let threads = sched.threads(); LOCAL.with(|l| { let mut l = l.borrow_mut(); let local = l.as_mut()?; let start = local.random() % threads; for k in 0..threads { let victim = (start + k) % threads; if victim == index || !sched.stealable(victim) { continue; } loop { let stolen = match sched.stealer(victim).len() { 0 => sched.inbound(victim).steal_batch_and_pop(&local.queue), _ => sched.stealer(victim).steal_batch_and_pop(&local.queue), }; match stolen { Steal::Success(pid) => return Some(pid), Steal::Retry => continue, Steal::Empty => break, } } } None }) } impl Local { /// A cheap random number (xorshift), to pick the first thread to steal /// from: threads starting at the same victim would contend for it. fn random(&mut self) -> usize { let mut x = self.seed; x ^= x << 13; x ^= x >> 7; x ^= x << 17; self.seed = x; x as usize } } /// This thread's index among `sched`'s threads, as a new actor's home /// (none off the scheduler's threads). Not inlined (see `Fiber`). #[inline(never)] pub(super) fn spawner_home(sched: &Shared) -> usize { LOCAL.with(|l| match &*l.borrow() { Some(local) if local.owner == sched as *const Shared as usize => local.index, _ => super::NO_HOME, }) } /// This thread's index among `sched`'s threads (0 for other threads). /// Not inlined, like every thread-local access on an actor's fiber (see /// `Fiber`). #[inline(never)] pub(super) fn local_index(sched: &Shared) -> usize { LOCAL.with(|l| match &*l.borrow() { Some(local) if local.owner == sched as *const Shared as usize => local.index, _ => 0, }) }