diff --git a/crates/metal2vulkan-runtime/src/scheduler/inbox.rs b/crates/metal2vulkan-runtime/src/scheduler/inbox.rs index 2a89d2271..190910570 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/inbox.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/inbox.rs @@ -11,14 +11,17 @@ //! returns: the scheduler's thread takes it in at its next pass. The inbox keeps commit order, //! and every pass takes it in before anything else: so the order sees commits in commit order, //! and the batches go to the `VkQueue`s, and are planned, in the order a pass picks them. -//! - **Nothing left behind.** The passer is counted while it makes a pass (`passers`). Once done -//! and counted out, it looks at the inbox again after a sequentially consistent fence, and -//! makes another pass for what it holds (a thread about to block wakes the scheduler's thread -//! for it instead: [`Inbox::pass_once`]). A commit puts its own in before the same fence and its -//! look at the count: whichever of the two fences comes first, the later look sees the other's -//! write, so a commit is either seen by the thread's look or finds no passer. One that finds no -//! passer marks the state under the lock, which then only a short hold has (a wake, a decode -//! count, the thread's look for work), for its caller to wake the thread, which takes it in. +//! - **Nothing left behind.** The passer is counted while it makes a pass (`passers`), from before +//! it takes the lock until after it lets go of it. Once done and counted out, it looks at the +//! inbox again after a sequentially consistent fence, and makes another pass for what it holds +//! (a thread about to block wakes the scheduler's thread for it instead: [`Inbox::pass_once`]). +//! A commit puts its own in before the same fence and its look at the count: whichever of the +//! two fences comes first, the later look sees the other's write, so a commit is either seen by +//! the thread's look or finds no passer. One that finds no passer has its caller wake the +//! thread, which takes it in, and takes no lock of the state's to do so: a pass counted after +//! its look may take that lock first and hold it across a `vkQueueSubmit` that waits for a +//! `VkQueue` another holds. The thread sleeps under a lock of its own, which no pass takes +//! (`scheduler/mod.rs`), and reads the inbox again under it before it sleeps. //! - **The scheduler's thread looks again until its passes leave it work** ([`Inbox::pass`]). //! Its passes may leave it work to do without the lock first (a submission check, a host step), //! which the batches behind it wait for: it stops looking again at the first pass that leaves @@ -35,9 +38,8 @@ //! none, so two such threads never both pass, and it looks again for nothing once counted out //! (it is going to sleep). What was left to it meanwhile it hands to the scheduler's thread //! instead, by the same fence and look its own `look_again` would make, and a wake -//! ([`Inbox::wake`]). The scheduler's thread is never gated: its [`pass`](Inbox::pass) counts -//! in whatever is counted, and waits for the lock while such a pass holds it, as a short hold -//! makes it wait. +//! ([`Inbox::passed_over`]). The scheduler's thread is never gated: its [`pass`](Inbox::pass) +//! counts in whatever is counted, and waits for the lock while such a pass holds it. //! - **A committing thread may pass once for its own commit** ([`Inbox::post_quietly`], //! [`Inbox::pass_once_then`]). `CommandBuffer::commit_and_submit` posts its commit with no mark //! and no wake, then passes once as a thread about to block does, where no passer is counted; @@ -57,7 +59,7 @@ use crate::device::lock; use std::sync::atomic::{fence, AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Mutex, TryLockError}; +use std::sync::Mutex; /// The commits the inbox holds from its making without growing: more than a frame commits (the /// consumer's guest commits about 45 command buffers a frame, the `frame_costs` lanes 41 to 108 @@ -111,8 +113,7 @@ impl Inbox { /// Ask for a pass: what a pass reads changed. Where a passer is counted, it looks again once /// done and passes for this, as for a commit, and this answers true. Else false: the caller - /// wakes the thread that makes passes itself, under the lock, which only a short hold or a - /// passer counted since (whose pass, made after this, reads the change) may have. + /// wakes the thread that makes passes itself, with no lock of the state's (the module docs). pub(crate) fn nudge(&self) -> bool { self.nudged.store(true, Ordering::SeqCst); fence(Ordering::SeqCst); @@ -131,9 +132,9 @@ impl Inbox { /// pass takes the commits in. /// /// It never looks again: the caller is about to sleep, so what was posted or nudged during - /// its pass goes to the thread that makes passes instead, which the caller - /// [`wake`](Self::wake)s after the sequentially consistent fence this leaves behind - /// ([`passed_over`](Self::passed_over) answers what is left). + /// its pass goes to the thread that makes passes instead, which the caller wakes after the + /// sequentially consistent fence this leaves behind ([`passed_over`](Self::passed_over) + /// answers what is left). pub(crate) fn pass_once(&self, pass: impl FnOnce(&mut S, &mut Vec)) -> bool { if !self.holds_commits() { return false; @@ -201,23 +202,13 @@ impl Inbox { /// [`look_again`](Self::look_again) would make, for a caller that sleeps instead of passing /// again. One posted or nudged during that pass put its write in before its own fence and /// its look at the count, which found a passer: whichever fence comes first, the later look - /// sees the other's write, so it is seen here or its own caller found no passer and marked - /// the state itself. + /// sees the other's write, so it is seen here or its own caller found no passer and woke the + /// thread itself. pub(crate) fn passed_over(&self) -> bool { fence(Ordering::SeqCst); self.posted.load(Ordering::SeqCst) || self.nudged.load(Ordering::SeqCst) } - /// Wake for a pass: [`nudge`](Self::nudge), and where that finds no passer, `mark` the state - /// under the lock ([`mark`](Self::mark)). Whether it marked the state, for the caller to wake - /// the thread that makes passes: the waker never waits for a pass's submissions. - pub(crate) fn wake(&self, mark: impl FnOnce(&mut S)) -> bool { - if self.nudge() { - return false; - } - self.mark(mark) - } - /// Post `commit`, after every commit posted before it, for the caller's own pass to take in /// ([`pass_once_then`](Self::pass_once_then)), with no mark and no wake: where a passer is /// counted then, its pass takes the commit in, or the thread it wakes once counted out @@ -232,35 +223,16 @@ impl Inbox { } /// Post `commit`, after every commit posted before it, for the thread that makes passes to - /// take in; where no passer is counted, `mark` the state under the lock ([`mark`](Self::mark)). - /// Whether it marked the state, for the caller to wake the thread: a commit never makes a - /// pass, nor waits for one (the module docs). - pub(crate) fn post(&self, commit: C, mark: impl FnOnce(&mut S)) -> bool { + /// take in. Whether no passer was counted, for the caller to wake the thread, with no lock of + /// the state's: a commit never makes a pass, nor waits for one (the module docs). + pub(crate) fn post(&self, commit: C) -> bool { { let mut commits = lock(&self.commits); commits.push(commit); self.posted.store(true, Ordering::SeqCst); } fence(Ordering::SeqCst); - if self.passing() { - return false; - } - self.mark(mark) - } - - /// After a write and a sequentially consistent fence that found no passer counted: `mark` the - /// state under the lock, which then only a short hold or a passer counted since (whose pass, - /// made after the write, reads it) may have; true where it marked it. - fn mark(&self, mark: impl FnOnce(&mut S)) -> bool { - let mut state = match self.state.try_lock() { - Ok(state) => state, - Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), - // A pass counted since: it takes the write in. - Err(TryLockError::WouldBlock) if self.passing() => return false, - Err(TryLockError::WouldBlock) => lock(&self.state), - }; - mark(&mut state); - true + !self.passing() } /// A pass by the scheduler's thread, never gated (the module docs), `pass` taking in what the inbox diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index 44a078b22..9481e4c98 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -6,9 +6,10 @@ //! pass and submits nothing, so no driver call holds it. This thread takes them in, in commit //! order, at its next pass, and submits what is ready. The commit wakes the thread where it //! sleeps, once a sleep: the waker that finds it asleep marks it awake as it notifies it, under -//! the lock, so a commit made before the thread ran finds it awake and makes no system call -//! ([`State::mark`]). Where it is making a pass, the thread looks at the inbox again once its -//! pass ends. The +//! the thread's own lock for its sleep ([`Sleep`]), so a commit made before the thread ran finds +//! it awake and makes no system call ([`Sleep::mark`]). No pass takes that lock, so a commit +//! never waits for the scheduler's lock, which a pass holds across its submissions. Where it is +//! making a pass, the thread looks at the inbox again once its pass ends. The //! order sees every commit in commit order, and every batch is planned as it is submitted. This //! thread stops looking at the inbox again at a pass that leaves it a check or a host step to //! hand over, and before each one it runs passes again for as long as the inbox holds commits, @@ -143,7 +144,8 @@ //! no completion turn and no waker between, and it observes the values itself //! (`EventShared::value`, which waits for what it reads), then checks and submits. Every other //! waker (a commit, a host signal, a finished decode, a lost device, a stop) signals the nudge, -//! under the lock, where the thread waits so; a completion turn needs not, as the thread's own +//! under the lock of the thread's sleep ([`Sleep`]), where the thread waits so; a completion +//! turn needs not, as the thread's own //! wait sees the signal the turn saw. Not where the driver's wait for any of several objects //! loses a signal that lands while it registers a later one //! (`RuntimeDriverDefect::WaitForAnyObjectLosesASignal`, `driver_defects.rs`; MoltenVK's): @@ -202,7 +204,7 @@ use metal2vulkan::error::RuntimeDriverDefect; use order::{Behind, Order}; use std::collections::{BTreeMap, BTreeSet}; use std::sync::atomic::{fence, AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Condvar, Mutex, OnceLock}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; @@ -244,14 +246,14 @@ impl Nudge { .semaphore(self.semaphore) .value(value); // SAFETY: the device's semaphore, live while its scheduler runs; `value` is above the - // semaphore's (the values rise under the scheduler's lock). + // semaphore's (the values rise under the lock of the thread's sleep, [`Sleep`]). let signalled = unsafe { self.functions.get().signal_semaphore(&info) }; exit_guard::called(exit_guard::Call::SignalSemaphore); signalled.is_ok() } } -/// How the thread slept as a waker marked the state ([`State::mark`]). +/// How the thread slept as a waker woke it ([`Sleep::mark`]). #[derive(Clone, Copy, PartialEq, Eq)] enum Asleep { /// It made a pass, was about to look again, or a waker before woke it: no wake needed. @@ -394,6 +396,9 @@ pub(crate) struct Scheduler { struct SchedulerShared { /// The state, under the lock a pass holds, with the commits a pass under way takes in. inbox: Inbox, + /// How the thread sleeps, under a lock of its own, which no pass takes ([`Sleep`]). + sleep: Mutex, + /// The thread's sleep on its condition variable, under `sleep`'s lock. wake: Condvar, /// What heads wait for from the GPU: the completion turns wake the thread once one is met. awaits: Awaits, @@ -493,9 +498,18 @@ impl SchedulerShared { } } - /// A waker marked the state for the thread, which makes no pass: wake it where it sleeps - /// (`asleep`, read under the lock the mark was made under; one that sleeps later reads the - /// mark first), counted as `woken`; else the notify, a system call, is spared. + /// Wake the thread, which makes no pass, for what the caller wrote before (a commit posted, a + /// nudge, the state marked under its lock), signalling `nudge` where the thread waits for the + /// GPU: under the lock of its sleep alone ([`Sleep`]), which no pass holds, so the waker never + /// waits for a pass's submissions. + fn wake_thread(&self, woken: Woken, nudge: Option<&Nudge>) { + let asleep = lock(&self.sleep).mark(nudge); + self.woken(woken, asleep); + } + + /// A waker found the thread making no pass: wake it where it sleeps (`asleep`, read under the + /// lock of its sleep; one that sleeps later reads what the waker wrote first), counted as + /// `woken`; else the notify, a system call, is spared. fn woken(&self, woken: Woken, asleep: Asleep) { match asleep { // The thread alone waits on it. @@ -554,16 +568,9 @@ pub(crate) struct State { pub(crate) waited: Vec>, /// The binary semaphore signals the device's command buffers committed and submitted. binary: BinarySignals, - /// A commit or a host signal came since the thread last looked. + /// A host signal marked the state since the thread last looked (a commit and a nudge are + /// the inbox's, `inbox.rs`). dirty: bool, - /// The thread sleeps on its condition variable and no waker notified it yet: a waker - /// notifies it only then, and clears this as it does ([`State::mark`]). - asleep: bool, - /// The thread waits for the GPU, and for the nudge to reach this value: a waker signals it - /// to that value under the lock, instead of notifying (the module docs). - on_gpu: Option, - /// The nudge semaphore's value: the last a waker signalled it to. - nudge_value: u64, stopping: bool, /// The textures whose decoded twins have CPU decodes queued or running, each with how many /// (`texture/twin_decode.rs`): a batch whose footprint names one waits for them. @@ -599,15 +606,34 @@ impl State { self.handler_tickets += 1; ticket } +} - /// A waker's mark (the module docs): look for work again, and how the thread sleeps. Where it - /// waits for the GPU, `nudge` is signalled to the value it waits for, here, under the lock; +/// How the scheduler's thread sleeps, under a lock of its own, which no pass takes: a waker that +/// finds no pass under way wakes the thread through it alone ([`SchedulerShared::wake_thread`]), +/// having written what it asks for first (a commit or a nudge in the inbox, or the state marked +/// under the scheduler's lock), so it never waits for a pass's submissions. The thread takes this +/// lock under the scheduler's as it goes to sleep, reads the inbox again, and lets go of the +/// scheduler's lock before it sleeps: a waker's write is read there, or the waker finds it asleep. +#[derive(Default)] +struct Sleep { + /// The thread sleeps on its condition variable and no waker notified it yet: a waker + /// notifies it only then, and clears this as it does ([`Sleep::mark`]). + asleep: bool, + /// The thread waits for the GPU, and for the nudge to reach this value: a waker signals it + /// to that value under this lock, instead of notifying (the module docs). + on_gpu: Option, + /// The nudge semaphore's value: the last a waker signalled it to. + nudge_value: u64, +} + +impl Sleep { + /// A waker's wake (the module docs), for what it wrote before: how the thread sleeps. Where it + /// waits for the GPU, `nudge` is signalled to the value it waits for, here, under this lock; /// none is given for a completion turn's wake, whose signal the thread's own wait sees. Where - /// it sleeps on its condition variable, it is marked awake here, for this waker to notify: - /// it then holds `dirty` and will pass, so a later waker before it ran notifies nothing (as + /// it sleeps on its condition variable, it is marked awake here, for this waker to notify: it + /// then passes for what the waker wrote, so a later waker before it ran notifies nothing (as /// the nudge, once signalled, is not signalled again). fn mark(&mut self, nudge: Option<&Nudge>) -> Asleep { - self.dirty = true; if self.asleep { self.asleep = false; return Asleep::OnCondvar; @@ -733,9 +759,6 @@ impl Scheduler { waited: vec![vec![0; queues + 2]; queues], binary: BinarySignals::default(), dirty: false, - asleep: false, - on_gpu: None, - nudge_value: 0, stopping: false, decodes: BTreeMap::new(), untracked_decodes: 0, @@ -746,6 +769,7 @@ impl Scheduler { group: Group::default(), grouped: Vec::new(), }), + sleep: Mutex::new(Sleep::default()), wake: Condvar::new(), awaits: Awaits::default(), sleeps: AtomicU64::new(0), @@ -828,12 +852,8 @@ impl Scheduler { shared.inbox.post_quietly(committed); return; } - let mut asleep = Asleep::No; - let marked = (shared.inbox).post(committed, |state| { - asleep = state.mark(shared.nudge.get()); - }); - if marked { - shared.woken(Woken::Commit, asleep); + if shared.inbox.post(committed) { + shared.wake_thread(Woken::Commit, shared.nudge.get()); } } @@ -960,8 +980,8 @@ impl Scheduler { let shared = Arc::downgrade(&self.shared); move || { if let Some(shared) = shared.upgrade() { - let asleep = lock(shared.inbox.state()).mark(shared.nudge.get()); - shared.woken(Woken::Host, asleep); + lock(shared.inbox.state()).dirty = true; + shared.wake_thread(Woken::Host, shared.nudge.get()); } } } @@ -1000,9 +1020,9 @@ impl Scheduler { if !tracked { state.untracked_decodes -= 1; } - let asleep = state.mark(self.shared.nudge.get()); + state.dirty = true; drop(state); - self.shared.woken(Woken::Host, asleep); + (self.shared).wake_thread(Woken::Host, self.shared.nudge.get()); } /// Whether this thread is the scheduler's (a submission check runs on it). @@ -1024,9 +1044,8 @@ impl Scheduler { /// Look for work again: an event's value rose, a pipeline was made, a rebind encoded a /// command buffer again, or the device was lost (each a host signal). Where a pass is under /// way, it passes again once done, and wakes the thread for a step or a check that finds; - /// else the thread is woken here, under the lock, which then only a short hold or a pass made - /// after this one's change has ([`Inbox::wake`]): the waker never waits for a pass's - /// submissions. + /// else the thread is woken here, under the lock of its sleep alone + /// ([`SchedulerShared::wake_thread`]): the waker never waits for a pass's submissions. pub(crate) fn wake(&self) { self.wake_for(Woken::Host); } @@ -1038,12 +1057,8 @@ impl Scheduler { /// [`wake_for`](Self::wake_for), signalling `nudge` where the thread waits for the GPU. fn wake_with(&self, woken: Woken, nudge: Option<&Nudge>) { - let mut asleep = Asleep::No; - let marked = (self.shared.inbox).wake(|state| { - asleep = state.mark(nudge); - }); - if marked { - self.shared.woken(woken, asleep); + if !self.shared.inbox.nudge() { + self.shared.wake_thread(woken, nudge); } } @@ -1111,11 +1126,8 @@ impl Scheduler { /// Ask the thread to end, and wait for it unless this is the thread. The device is being /// dropped, so nothing is held: every held command buffer holds its device. pub(crate) fn stop(&self) { - { - let mut state = lock(self.shared.inbox.state()); - state.stopping = true; - state.mark(self.shared.nudge.get()); - } + lock(self.shared.inbox.state()).stopping = true; + lock(&self.shared.sleep).mark(self.shared.nudge.get()); self.shared.wake.notify_all(); self.shared.steps.stop(); let mut thread = lock(&self.thread); @@ -1192,29 +1204,42 @@ fn run(shared: &Arc) { && bound.is_none() && stalls.is_none(); let slice = bound.map_or(slice, |left| left.min(slice)); + let on_gpu = shared.nudge.get().filter(|_| shared.gpu_waits(&mut gpu)); + // The lock of the sleep ([`Sleep`]), under the scheduler's: a waker that found no + // pass under way wrote what it asks for before it took it, so its commit or nudge is + // read here, or it finds the thread asleep and wakes it. + let mut sleep = lock(&shared.sleep); + if shared.inbox.holds_commits() || shared.inbox.nudged() { + continue; + } shared.sleeps.fetch_add(1, Ordering::Relaxed); - if let Some(nudge) = shared.nudge.get().filter(|_| shared.gpu_waits(&mut gpu)) { - state = wait_for_gpu(shared, state, nudge, &mut gpu, (slice, short)); + if let Some(nudge) = on_gpu { + state = wait_for_gpu(shared, (state, sleep), nudge, &mut gpu, (slice, short)); continue; } - state.asleep = true; - if idle { - state = shared - .wake - .wait(state) - .unwrap_or_else(std::sync::PoisonError::into_inner); - state.asleep = false; - continue; - } - let (woke, waited) = shared - .wake - .wait_timeout(state, slice) - .unwrap_or_else(std::sync::PoisonError::into_inner); - state = woke; - state.asleep = false; - if waited.timed_out() && !short { + sleep.asleep = true; + // A waker that marks the state under the scheduler's lock takes it once this lets + // go of it, and then the sleep's, which the wait lets go of. + drop(state); + let timed_out = match idle { + true => { + sleep = (shared.wake.wait(sleep)) + .unwrap_or_else(std::sync::PoisonError::into_inner); + false + } + false => { + let (woke, waited) = (shared.wake.wait_timeout(sleep, slice)) + .unwrap_or_else(std::sync::PoisonError::into_inner); + sleep = woke; + waited.timed_out() + } + }; + sleep.asleep = false; + drop(sleep); + if timed_out && !short { shared.wakings[Woken::Slice as usize].fetch_add(1, Ordering::Relaxed); } + state = lock(shared.inbox.state()); } if state.stopping { return; @@ -1238,19 +1263,20 @@ fn run(shared: &Arc) { /// Sleep on the GPU (the module docs): for any of `gpu`'s semaphores to reach its value, or the /// nudge its next, at most `slice` ([`WAIT_SLICE`], or less to a head's bound, or, where `short`, -/// the idle's length before a driver's stall is taken, whose end is no slice's), without the lock -/// `state` holds, which comes back taken. Where a value landed, its events observe their counters, -/// and the state is marked for a pass. +/// the idle's length before a driver's stall is taken, whose end is no slice's), without the locks +/// `state` and `sleep` hold, the scheduler's coming back taken. Where a value landed, its events +/// observe their counters, and the state is marked for a pass. fn wait_for_gpu<'a>( shared: &'a SchedulerShared, - mut state: std::sync::MutexGuard<'a, State>, + (state, mut sleep): (MutexGuard<'a, State>, MutexGuard<'a, Sleep>), nudge: &Nudge, gpu: &mut GpuWait, (slice, short): (Duration, bool), -) -> std::sync::MutexGuard<'a, State> { +) -> MutexGuard<'a, State> { shared.gpu_waits.fetch_add(1, Ordering::Relaxed); - let target = state.nudge_value + 1; - state.on_gpu = Some(target); + let target = sleep.nudge_value + 1; + sleep.on_gpu = Some(target); + drop(sleep); drop(state); gpu.semaphores.push(nudge.semaphore); gpu.values.push(target); @@ -1279,13 +1305,13 @@ fn wait_for_gpu<'a>( let mut state = lock(shared.inbox.state()); // Whether a waker signalled the nudge (taking `on_gpu`); where none did, the next wait waits // for the same value. - let by_waker = state.on_gpu.take().is_none(); + let by_waker = lock(&shared.sleep).on_gpu.take().is_none(); match waited { Some(Ok(())) if !by_waker => { shared.wakings[Woken::Completion as usize].fetch_add(1, Ordering::Relaxed); state.dirty = true; } - // Nudged: the waker counted the waking and marked the state. + // Nudged: the waker counted the waking, and the next look reads what it wrote. Some(Ok(())) => {} Some(Err(vk::Result::TIMEOUT)) if !short => { shared.wakings[Woken::Slice as usize].fetch_add(1, Ordering::Relaxed); diff --git a/crates/metal2vulkan-runtime/src/scheduler/steps.rs b/crates/metal2vulkan-runtime/src/scheduler/steps.rs index 6a412ec52..6ac057360 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/steps.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/steps.rs @@ -146,13 +146,15 @@ fn record(shared: &SchedulerShared, work: Work) -> bool { buffer.device().shared().counts.host_step_recorded(took); buffer.end_step(); drop(busy); - { + let stopping = { let mut state = lock(shared.inbox.state()); if !state.stopping { - let asleep = state.mark(shared.nudge.get()); - drop(state); - shared.woken(Woken::Host, asleep); + state.dirty = true; } + state.stopping + }; + if !stopping { + shared.wake_thread(Woken::Host, shared.nudge.get()); } // Out of the section: it may be the command buffer's last reference. drop(work); diff --git a/crates/metal2vulkan-runtime/src/tests/inbox.rs b/crates/metal2vulkan-runtime/src/tests/inbox.rs index c150756a9..d6724a4e6 100644 --- a/crates/metal2vulkan-runtime/src/tests/inbox.rs +++ b/crates/metal2vulkan-runtime/src/tests/inbox.rs @@ -2,8 +2,9 @@ //! passer is counted, and never where one is, so two threads never both pass; what is left to such //! a pass it reads back for the scheduler's thread instead of passing again; and a commit posts //! and returns at once, whether or not a pass is under way, -//! and its commit goes next, in commit order; one that finds no pass under way marks the state for -//! the thread's wake, waiting only for a short hold; the scheduler's pass looks again for a commit +//! and its commit goes next, in commit order; one that finds no pass under way returns at once +//! while the state's lock is held, for its caller to wake the thread under the lock of its sleep, +//! which no pass takes; the scheduler's pass looks again for a commit //! left to it until a pass answers it has work of its own first; commits from many threads racing //! passes, ones that stop looking again, and short holds are all passed, each thread's in its //! order, with no pass made for them at the end; a nudge finding a pass under way returns at once @@ -14,7 +15,7 @@ use crate::device::lock; use crate::scheduler::inbox::{Inbox, ROOM}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc; -use std::sync::{Arc, Condvar}; +use std::sync::{Arc, Condvar, Mutex}; use std::thread; use std::time::{Duration, Instant}; @@ -32,17 +33,13 @@ fn take_in(log: &mut Vec, commits: &mut Vec) -> bool { } /// Post `commit` from another thread while this one makes a pass: it is left to this thread's -/// pass, which looks again for it, so the committer marks nothing. +/// pass, which looks again for it, so the committer wakes nothing. pub(super) fn commit_elsewhere(inbox: &Inbox, commit: C) { thread::scope(|scope| { - let committer = scope.spawn(|| { - inbox.post(commit, |_| { - panic!("a commit that found a pass under way marked the state") - }) - }); + let committer = scope.spawn(|| inbox.post(commit)); assert!( !committer.join().unwrap(), - "a commit that found a pass under way marked the state" + "a commit that found a pass under way woke the thread" ); }); } @@ -77,8 +74,8 @@ fn held_pass(inbox: &Arc) -> (thread::JoinHandle, mpsc::Sender<()>) { fn a_commit_finding_a_pass_under_way_returns_at_once_and_goes_next_in_commit_order() { let inbox = Arc::new(Log::new(Vec::new())); assert!( - inbox.post(0, |_| {}), - "no pass under way: it marked the state" + inbox.post(0), + "no pass under way: its caller wakes the thread" ); let (passer, release) = held_pass(&inbox); let (done, returned) = mpsc::channel(); @@ -86,16 +83,15 @@ fn a_commit_finding_a_pass_under_way_returns_at_once_and_goes_next_in_commit_ord let inbox = Arc::clone(&inbox); thread::spawn(move || { for commit in 1..=3 { - done.send(inbox.post(commit, |_| panic!("marked under a pass"))) - .unwrap(); + done.send(inbox.post(commit)).unwrap(); } }) }; for commit in 1..=3 { - let marked = returned.recv_timeout(WAIT).unwrap_or_else(|_| { + let wakes = returned.recv_timeout(WAIT).unwrap_or_else(|_| { panic!("commit {commit} waited for the pass under way instead of returning") }); - assert!(!marked, "commit {commit} was left to the pass under way"); + assert!(!wakes, "commit {commit} was left to the pass under way"); } committer.join().unwrap(); assert!(inbox.holds_commits()); @@ -106,31 +102,34 @@ fn a_commit_finding_a_pass_under_way_returns_at_once_and_goes_next_in_commit_ord assert!(!inbox.holds_commits()); } -/// A commit that finds no pass under way makes none either: it marks the state under the lock, -/// waiting only for a short hold, and the thread's next pass takes it in. +/// A commit that finds no pass under way makes none either, and takes no lock of the state's: it +/// returns at once while that lock is held, as a pass counted after its look may hold it across a +/// `vkQueueSubmit` that waits for a held `VkQueue`, for its caller to wake the thread; the +/// thread's next pass takes it in. #[test] -fn a_commit_finding_no_pass_marks_the_state_for_the_thread_s_wake() { - let inbox = Arc::new(Inbox::<(Vec, bool), u32>::new((Vec::new(), false))); +fn a_commit_finding_no_pass_returns_while_the_lock_is_held() { + let inbox = Arc::new(Log::new(Vec::new())); let held = lock(inbox.state()); + let (done, returned) = mpsc::channel(); let committer = { let inbox = Arc::clone(&inbox); - thread::spawn(move || inbox.post(7, |(_, marked)| *marked = true)) + thread::spawn(move || done.send(inbox.post(7)).unwrap()) }; - // It posted, found no passer, and waits for the short hold to mark the state. - let until = Instant::now() + WAIT; - while !inbox.holds_commits() { - assert!(Instant::now() < until, "the commit never posted"); - thread::yield_now(); - } + let wakes = returned.recv_timeout(WAIT); drop(held); - assert!(committer.join().unwrap(), "it marked the state"); - assert_eq!(*lock(inbox.state()), (Vec::new(), true), "and made no pass"); + committer.join().unwrap(); + assert_eq!( + wakes, + Ok(true), + "the commit waited for the lock, or found a pass under way" + ); + assert!(lock(inbox.state()).is_empty(), "and made no pass"); assert!(inbox.holds_commits()); - inbox.pass(|(log, _), commits| { + inbox.pass(|log, commits| { log.append(commits); false }); - assert_eq!(lock(inbox.state()).0, [7]); + assert_eq!(*lock(inbox.state()), [7]); assert!(!inbox.holds_commits()); } @@ -143,7 +142,7 @@ fn a_new_inbox_holds_room_commits_without_growing() { let room = inbox.room(); assert!(room >= ROOM, "a new inbox has room for {room}"); for commit in 0..ROOM as u32 { - inbox.post(commit, |_| {}); + inbox.post(commit); } assert_eq!(inbox.room(), room, "{ROOM} commits grew the inbox"); } @@ -156,7 +155,7 @@ fn a_new_inbox_holds_room_commits_without_growing() { fn a_pass_leaves_the_inbox_room_for_twice_the_commits_it_took_in() { let inbox = Log::new(Vec::new()); for commit in 0..5 { - inbox.post(commit, |_| {}); + inbox.post(commit); } inbox.pass(|log, commits| { log.append(commits); @@ -215,18 +214,21 @@ fn the_scheduler_s_pass_looks_again_until_a_pass_answers_it_has_work_first() { } /// The state of [`Model`]'s passes: the commits in the order they took them in, each waker's -/// value as the last pass read it, and a wake's mark. +/// value as the last pass read it, and the stop. #[derive(Default)] struct Seen { log: Vec, values: Vec, - dirty: bool, stop: bool, } -/// The scheduler's thread and its wakes over an inbox, as `scheduler/mod.rs` makes them. +/// The scheduler's thread and its wakes over an inbox, as `scheduler/mod.rs` makes them: it sleeps +/// under a lock of its own, which no pass takes, and a commit or a nudge that finds no pass under +/// way wakes it through that lock alone. struct Model { inbox: Inbox, + /// Whether the thread sleeps, under the lock of its sleep. + asleep: Mutex, woken: Condvar, } @@ -237,15 +239,16 @@ impl Model { values: vec![0; wakers], ..Seen::default() }), + asleep: Mutex::new(false), woken: Condvar::new(), } } - /// `Scheduler::commit`'s: post, and wake the thread where it marked the state. Whether it + /// `Scheduler::commit`'s: post, and wake the thread where no pass was under way. Whether it /// was left to a pass under way. fn commit(&self, commit: u32) -> bool { - if self.inbox.post(commit, |seen| seen.dirty = true) { - self.woken.notify_all(); + if self.inbox.post(commit) { + self.wake_thread(); return false; } true @@ -253,31 +256,51 @@ impl Model { /// `Scheduler::wake`'s: whether it was left to a pass under way. fn wake(&self) -> bool { - if self.inbox.wake(|seen| seen.dirty = true) { - self.woken.notify_all(); + if !self.inbox.nudge() { + self.wake_thread(); return false; } true } - /// The thread's loop: it waits for a wake's mark, a commit or a nudge left to it, with no - /// timed look, then passes, its passes answering `again` of their count whether to look again - /// (false: it has work of its own first, done at once, after which it looks at the inbox - /// again). Once stopped, it ends when it has nothing to pass for. + /// `SchedulerShared::wake_thread`'s: under the lock of the sleep alone, notify the thread + /// where it sleeps, marking it awake. + fn wake_thread(&self) { + let mut asleep = lock(&self.asleep); + if *asleep { + *asleep = false; + self.woken.notify_one(); + } + } + + /// The thread's loop: it waits for a commit or a nudge left to it, with no timed look, then + /// passes, its passes answering `again` of their count whether to look again (false: it has + /// work of its own first, done at once, after which it looks at the inbox again). It reads the + /// inbox again under the lock of its sleep before it sleeps, and lets go of the state's lock + /// then. Once stopped, it ends when it has nothing to pass for. fn run(&self, mut pass: impl FnMut(&mut Seen, &mut Vec), again: impl Fn(u64) -> bool) { - let asked = |seen: &Seen| seen.dirty || self.inbox.holds_commits() || self.inbox.nudged(); + let asked = || self.inbox.holds_commits() || self.inbox.nudged(); let mut passes = 0; loop { let mut seen = lock(self.inbox.state()); - while !asked(&seen) && !seen.stop { - seen = self.woken.wait(seen).unwrap(); + while !asked() && !seen.stop { + let mut asleep = lock(&self.asleep); + if asked() { + continue; + } + *asleep = true; + drop(seen); + while *asleep { + asleep = self.woken.wait(asleep).unwrap(); + } + drop(asleep); + seen = lock(self.inbox.state()); } - if !asked(&seen) { + if !asked() { return; } drop(seen); self.inbox.pass(|seen, commits| { - seen.dirty = false; pass(seen, commits); passes += 1; again(passes) @@ -287,7 +310,7 @@ impl Model { fn stop(&self) { lock(self.inbox.state()).stop = true; - self.woken.notify_all(); + self.wake_thread(); } } @@ -375,7 +398,7 @@ fn commits_racing_passes_and_short_holds_are_all_passed_each_thread_s_in_its_ord #[test] fn a_nudge_finding_a_pass_under_way_is_passed_for_once_it_ends() { let inbox = Arc::new(Log::new(Vec::new())); - assert!(inbox.post(0, |_| {})); + assert!(inbox.post(0)); let (passer, release) = held_pass(&inbox); assert!(inbox.nudge(), "the nudge was left to the pass under way"); release.send(()).unwrap(); @@ -481,7 +504,7 @@ fn a_thread_about_to_block_passes_once_for_the_commits_the_inbox_holds() { "it passed for an empty inbox" ); for commit in 0..3 { - inbox.post(commit, |_| {}); + inbox.post(commit); } let mut passes = 0; assert!(inbox.pass_once(|log, commits| { @@ -525,10 +548,10 @@ fn a_thread_about_to_block_never_passes_while_a_passer_is_counted() { #[test] fn a_commit_left_to_a_blocking_thread_s_pass_is_read_back_for_the_scheduler() { let inbox = Arc::new(Log::new(Vec::new())); - inbox.post(0, |_| {}); + inbox.post(0); assert!(inbox.pass_once(|log, commits| { take_in(log, commits); - // Posted while this pass is counted: its committer marks nothing and leaves it here. + // Posted while this pass is counted: its committer wakes nothing and leaves it here. commit_elsewhere(&inbox, 1); })); assert_eq!(*lock(inbox.state()), [0]); @@ -546,11 +569,11 @@ fn a_commit_left_to_a_blocking_thread_s_pass_is_read_back_for_the_scheduler() { } /// A nudge left to such a pass is read back the same way: a waker that found the pass counted -/// marked nothing, and the pass takes none afterwards. +/// woke nothing, and the pass takes none afterwards. #[test] fn a_nudge_left_to_a_blocking_thread_s_pass_is_read_back_for_the_scheduler() { let inbox = Arc::new(Log::new(Vec::new())); - inbox.post(0, |_| {}); + inbox.post(0); assert!(inbox.pass_once(|log, commits| { take_in(log, commits); assert!(inbox.nudge(), "the waker found no passer counted"); diff --git a/crates/metal2vulkan-runtime/src/tests/scheduler_wakes.rs b/crates/metal2vulkan-runtime/src/tests/scheduler_wakes.rs index 719f37689..81fb7a47f 100644 --- a/crates/metal2vulkan-runtime/src/tests/scheduler_wakes.rs +++ b/crates/metal2vulkan-runtime/src/tests/scheduler_wakes.rs @@ -1,5 +1,5 @@ //! A waker wakes the scheduler's thread once a sleep (`scheduler/mod.rs`, "Handed to the thread"; -//! `State::mark`): the first marks it awake as it notifies it, so a commit made before the thread +//! `Sleep::mark`): the first marks it awake as it notifies it, so a commit made before the thread //! ran makes no system call, and no commit's wake is lost for it. //! //! - **Once a sleep.** The notifies counted as wakings by a commit, a completion or a host signal