From e5d1616030d231e8f4ff9619bc07c4447cf6fc88 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 14 Oct 2026 13:59:32 +0300 Subject: [PATCH] Take a commit left to the scheduler in before its next check, and bound a commit's passes The scheduler review's work packet: the inbox's and the work loop's fixes, and race tests that catch a lost wake. Take a commit left to the scheduler thread in before its next check, and bound a commit's passes: Four defects in the commit inbox (scheduler/inbox.rs) and the scheduler thread's loop, which broke the inbox's bound on a commit's wait and Metal's prompt commit: - A commit left to the scheduler thread during the round that took an earlier one in waited for the thread's next check (the program's code) or host step: the thread looked at the inbox once before each piece of work, not again after that round. The thread's way through its work is now `scheduler/left.rs`'s `work_through`, which makes rounds for as long as the inbox holds commits before each piece, generic so that it is tested without a device. - A committing thread passed again for as long as other threads' commits or wakes kept arriving during its passes, so one commit() was unbounded. Its look again now makes at most one pass (`inbox::AGAIN`); what is left to that pass with no other passer counted is answered as unattended, and `Scheduler::commit` wakes the scheduler thread for it (the wake's code moves into `Inbox::wake`, which `Scheduler::wake` and the tests' model share). - Checks always ran before host steps, and rounds between pieces add checks, so a step (and its queue) could wait behind checks found after it. Work now runs in the order rounds found it, a round's checks before its steps. - A pass cleared the nudge with a plain store, so the memory model gave no happens-before from a waker's change to the pass that took its nudge in. It is now a swap, which synchronizes with the waker's store it reads. Docs made true again: the inbox's and the scheduler's wait bounds, SubmissionCheck's and add_submission_handler's "a commit meanwhile still submits", the stall in texture/storage_form.rs (also after a commit left to another thread's pass), and WorkCounts::queue_submissions (the first work rides in the batch's call). RUNTIME_VERSION 1188; the runtime-sources pin follows in its own commit. Verified on msi-laptop (Linux, Rust 1.98.1), before the rebase onto fleet/round: clippy -p metal2vulkan-runtime --all-targets --all-features clean; rustdoc of the crate clean; nextest tests::inbox, tests::left and tests::scheduler 24 of 24. Each new deterministic test fails without its fix: with `if` for `while` the left commit runs after the first check ([TakenIn(1), Ran(Check, 1), TakenIn(2)...]); with checks always first a later round's check runs before an earlier round's steps; with the committer unbounded it makes 5 passes for 4 commits left to it, against 2. A paced stress (4 threads, 6 commits a ms in all, 80 us passes, release) made up to 4 passes in one commit() on the base (0.1-12% of commits over 2), and at most 2 with this change. Make the inbox's race tests catch a lost wake, and print the paths they took: The racing-commits test stopped its model scheduler thread right after the committers ended, and the stop's own notify would make the thread pass for a commit whose wake was lost, so the test could not see one. It now waits (up to its 30 s bound) for the thread to have passed every commit before it stops it, as the wakers' test does for every raise, through a shared `soon`. Both tests print how often the races took the paths they cover (commits left to another thread and left unattended; wakes left to a pass under way), as evidence that those paths ran. Test-only: the runtime sources the pin covers are unchanged. Verified on msi-laptop: tests::inbox and tests::left pass (see the landing note for counts). Versions: RUNTIME_VERSION 1196 -> 1197. RUNTIME_VERSION moves: when a commit's work is taken in and how many passes it makes change. crates/metal2vulkan-validation/runtime-sources.sha256 holds 581e5e5522ddfb5c61d4b949e7b7b01e210925bff898241bcd517ef6fdee40f2, the hash of this tree's runtime inputs (runtime-pin.py, which reproduces build.rs's). Version numbers quoted above are the values the work's branch built with. Each part's Verified lines name the tree it ran at. --- .../src/command_buffer/checks.rs | 9 +- .../src/command_buffer/mod.rs | 13 +- .../src/scheduler/inbox.rs | 109 ++++-- .../src/scheduler/left.rs | 109 ++++++ .../metal2vulkan-runtime/src/scheduler/mod.rs | 189 +++++----- .../metal2vulkan-runtime/src/tests/inbox.rs | 353 +++++++++++++++--- crates/metal2vulkan-runtime/src/tests/left.rs | 133 +++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 1 + .../src/texture/storage_form.rs | 5 +- .../metal2vulkan-runtime/src/work_counts.rs | 6 +- .../runtime-sources.sha256 | 2 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- 12 files changed, 734 insertions(+), 197 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/scheduler/left.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/left.rs diff --git a/crates/metal2vulkan-runtime/src/command_buffer/checks.rs b/crates/metal2vulkan-runtime/src/command_buffer/checks.rs index 1c3185b61..016dea9f6 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/checks.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/checks.rs @@ -51,9 +51,12 @@ use std::sync::Arc; /// whose memory was taken away, as Metal fails it). /// /// It runs with no lock of the runtime's held, and holds back the scheduler thread's submissions -/// while it runs (a commit meanwhile still submits its own ready batches): it must not wait for -/// GPU work, a command buffer or a handler, and should be quick. It may call the runtime -/// otherwise. +/// while it runs. A commit made meanwhile has its ready batches submitted, by itself or by the +/// pass of another commit's thread it finds under way; where that pass is the last that thread +/// makes for others, which leaves what it is left to the scheduler's thread +/// (`scheduler/inbox.rs`), they wait for this check to end, unless a later commit takes them in +/// first. It must not wait for GPU work, a command buffer or a handler, and should be quick. It +/// may call the runtime otherwise. pub type SubmissionCheck = Arc) -> Option + Send + Sync>; /// The `MTLCommandBufferError` code a submission whose check panicked fails with: `Internal`. diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index afe837c42..8b3a0c250 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -1318,11 +1318,14 @@ impl CommandBuffer { /// submission or host step that fails, a lost device); they are dropped with it. A command /// buffer committed as failed ([`commit_failed`](Self::commit_failed)) submits its batches /// and runs them. - /// - **Keep it short.** It holds back its command buffer's scheduling, `commit` where the - /// commit submits, and on the scheduler thread the device's other submissions (a commit - /// meanwhile still submits its own ready batches). A wait in it for a command buffer, or - /// for a slot of a full queue, that has not happened yet is refused (`WaitWouldDeadlock` of - /// [`DeadlockCause::SubmissionHandler`]); it must not wait for GPU work otherwise. + /// - **Keep it short.** It holds back its command buffer's scheduling, `commit` where a + /// commit's thread runs it, and on the scheduler thread the device's other submissions, + /// among them those of a commit left to the pass that submitted this command buffer, which + /// the thread may take in only after its handlers (`scheduler/inbox.rs`). A commit made + /// while it runs that finds no pass under way submits its own ready batches. A wait in it + /// for a command buffer, or for a slot of a full queue, that has not happened yet is refused + /// (`WaitWouldDeadlock` of [`DeadlockCause::SubmissionHandler`]); it must not wait for GPU + /// work otherwise. /// /// Refused once the command buffer is committed (`Invalid`, `Problem::HandlerAfterCommit`), /// as [`add_scheduled_handler`](Self::add_scheduled_handler) is. diff --git a/crates/metal2vulkan-runtime/src/scheduler/inbox.rs b/crates/metal2vulkan-runtime/src/scheduler/inbox.rs index 596aa0bd3..d15cf8e7a 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/inbox.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/inbox.rs @@ -21,13 +21,23 @@ //! a commit is either seen by a passer's look or finds no passer, and passes itself. The lock's //! other holders (a wake, a decode count, the thread's look for work) make no pass and are not //! counted: a commit that finds only one of them waits for its short hold, and then passes. +//! - **A committing thread passes once for the others** ([`Inbox::commit`]). Its look again makes +//! at most one pass ([`AGAIN`]): its own commit's, where it found the lock held for no pass, or +//! else one for what other threads left to its pass. Where that leaves the inbox asked (a +//! commit, or a nudge, left to the pass meanwhile) with no other passer counted, it answers so +//! ([`Outcome::unattended`]), and its caller wakes the thread that makes passes itself (the +//! scheduler's), as for a nudge that finds no passer: so a commit returns after at most two +//! passes, and never passes on for the commits other threads keep leaving it. One so left waits +//! for that wake, or, where the scheduler's thread is running a check or a host step, for the +//! end of that piece of work, unless another commit takes it in first. //! - **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 -//! some, rather than pass on for the commits that keep coming while that work waits, and looks -//! at the inbox itself ([`Inbox::holds_commits`]) before each piece of that work and before it -//! sleeps. A commit is left to it only while it holds the lock for a pass, so one waits at most -//! for that pass and the submission handlers the thread runs right after it, never for a wake. +//! some, and before each piece of that work, passes again for as long as the inbox holds +//! commits ([`Inbox::holds_commits`], `scheduler/left.rs`), and looks before it sleeps. A commit +//! left to it, while it holds the lock for a pass, so waits for that pass, the submission +//! handlers the thread runs right after it, and the pass that takes it in; never for a wake or +//! the thread's work. //! - **Who runs the after-work.** A pass's thread lets go, outside the lock, of what its passes //! submitted (the holds, the submission handlers) in submission order, as the scheduler does //! for its own: a commit handed off runs its submission handlers on that thread. @@ -36,12 +46,28 @@ //! Where a passer is counted, the waker leaves it a nudge and returns, as a commit does: the //! passer looks again for it once done, by the same fences, and each pass takes it in first. //! The completion thread so never waits for a pass's submissions before it finishes the batches -//! it saw complete, whose completed handlers wait for it. +//! it saw complete, whose completed handlers wait for it. A pass takes the nudge in by a +//! sequentially consistent swap, which reads the waker's store where it takes that nudge, and +//! so sees what the waker changed before it. use crate::device::lock; use std::sync::atomic::{fence, AtomicBool, AtomicUsize, Ordering}; use std::sync::{Mutex, TryLockError}; +/// The passes a committing thread's look again makes at most ([`Inbox::commit`]). +pub(crate) const AGAIN: usize = 1; + +/// What became of a commit ([`Inbox::commit`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Outcome { + /// It was left to another thread's pass. + pub(crate) left: bool, + /// The committing thread stopped looking again at [`AGAIN`] passes with the inbox asked and + /// no other passer counted: the caller wakes the thread that makes passes itself, which takes + /// in what it holds. + pub(crate) unattended: bool, +} + /// A state `S` that passes work on under its lock, and the commits `C` waiting to be taken in. pub(crate) struct Inbox { state: Mutex, @@ -92,17 +118,37 @@ impl Inbox { } /// Whether a passer is counted. - pub(crate) fn passing(&self) -> bool { + fn passing(&self) -> bool { self.passers.load(Ordering::SeqCst) > 0 } + /// Wake for a pass: [`nudge`](Self::nudge), and where that finds no passer, `mark` the state + /// under the lock, which then only a short hold or a passer counted since (whose pass, made + /// after the nudge, reads the change) may have. Whether it marked the state, for the caller to + /// wake the thread that makes passes itself: 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; + } + let mut state = match self.state.try_lock() { + Ok(state) => state, + Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), + // A pass counted since: it took the nudge in, after the change. + Err(TryLockError::WouldBlock) if self.passing() => return false, + Err(TryLockError::WouldBlock) => lock(&self.state), + }; + mark(&mut state); + true + } + /// Commit `commit`: where the lock is free, make the pass on this thread, `pass` taking in /// what the inbox held and `commit` after it, in commit order; where another thread holds it, - /// leave `commit` to that thread's pass. Then look at the inbox again ([`look_again`]). Whether - /// `commit` was left to another thread. + /// leave `commit` to that thread's pass. Then look at the inbox again ([`look_again`]), making + /// at most [`AGAIN`] passes. Whether `commit` was left to another thread, and whether the + /// inbox was left unattended (the module docs). /// /// [`look_again`]: Self::look_again - pub(crate) fn commit(&self, commit: C, mut pass: impl FnMut(&mut S, Vec)) -> bool { + pub(crate) fn commit(&self, commit: C, mut pass: impl FnMut(&mut S, Vec)) -> Outcome { let mut pass = |state: &mut S, commits: Vec| { pass(state, commits); true @@ -128,8 +174,11 @@ impl Inbox { } }; self.passers.fetch_sub(1, Ordering::SeqCst); - let passed = self.look_again(&mut pass); - left && !passed + let looked = self.look_again(AGAIN, &mut pass); + Outcome { + left: left && !looked.passed, + unattended: looked.unattended, + } } /// A pass by a thread that waits for the lock (the scheduler's own), `pass` taking in what the @@ -145,21 +194,27 @@ impl Inbox { drop(state); self.passers.fetch_sub(1, Ordering::SeqCst); if again { - self.look_again(&mut pass); + self.look_again(usize::MAX, &mut pass); } } /// After a passer is counted out: while the inbox holds a commit or a nudge and no other /// passer is counted, take the lock and pass for it (waiting only for a holder that makes no - /// pass), until a pass answers not to look again. Whether this made a pass that took commits - /// in. - fn look_again(&self, pass: &mut impl FnMut(&mut S, Vec) -> bool) -> bool { - let mut passed = false; + /// pass), until a pass answers not to look again, or `passes` passes were made. Whether this + /// made a pass that took commits in, and whether it stopped at `passes` with the inbox still + /// asked and no other passer counted. + fn look_again(&self, passes: usize, pass: &mut impl FnMut(&mut S, Vec) -> bool) -> Looked { + let mut looked = Looked::default(); + let mut made = 0; loop { fence(Ordering::SeqCst); let asked = self.posted.load(Ordering::SeqCst) || self.nudged.load(Ordering::SeqCst); if !asked || self.passers.load(Ordering::SeqCst) > 0 { - return passed; + return looked; + } + if made == passes { + looked.unattended = true; + return looked; } self.passers.fetch_add(1, Ordering::SeqCst); let mut state = match self.state.try_lock() { @@ -173,21 +228,24 @@ impl Inbox { // A short hold that makes no pass. Err(TryLockError::WouldBlock) => lock(&self.state), }; + made += 1; let commits = self.take(); - passed |= !commits.is_empty(); + looked.passed |= !commits.is_empty(); let again = pass(&mut state, commits); drop(state); self.passers.fetch_sub(1, Ordering::SeqCst); if !again { - return passed; + return looked; } } } /// The commits in the inbox, in commit order, taken out, and its nudge with them; called under - /// the state's lock, before the pass reads anything. + /// the state's lock, before the pass reads anything. The nudge is taken by a swap: where it + /// reads a waker's store, it synchronizes with it, so the pass reads what the waker changed + /// before its nudge; where it reads none, any later store of one stays for a later look. fn take(&self) -> Vec { - self.nudged.store(false, Ordering::SeqCst); + self.nudged.swap(false, Ordering::SeqCst); if !self.posted.load(Ordering::SeqCst) { return Vec::new(); } @@ -196,3 +254,12 @@ impl Inbox { commits.drain(..).collect() } } + +/// What a look again came to ([`Inbox::look_again`]). +#[derive(Default)] +struct Looked { + /// A pass of it took commits in. + passed: bool, + /// It stopped at its passes with the inbox asked and no other passer counted. + unattended: bool, +} diff --git a/crates/metal2vulkan-runtime/src/scheduler/left.rs b/crates/metal2vulkan-runtime/src/scheduler/left.rs new file mode 100644 index 000000000..26718a337 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/scheduler/left.rs @@ -0,0 +1,109 @@ +//! What the scheduler's passes leave its thread to do without the lock (a batch's submission +//! checks, a batch's host step), and the thread's way through it once woken ([`work_through`]). +//! +//! - **Commits first.** Before each piece of work, the thread makes rounds for as long as the +//! inbox holds commits ([`Inbox::holds_commits`]): a commit left to the thread while a round's +//! pass held the lock (`inbox.rs`) is taken in by the next round, never after a piece of work, +//! which runs the program's code (a check) or records (a step). Those rounds end at the first +//! that leaves the inbox without one; while commits keep coming during each of the thread's +//! passes, its work waits for them. +//! - **In the order found.** The work runs in the order the thread's rounds found it, a round's +//! checks before its steps: a piece waits for the work found before it, never for work a later +//! round found, which the rounds between pieces add. + +use super::inbox::Inbox; +use std::collections::VecDeque; + +/// A kind of work the thread does without its lock, in the order a round's finds run in. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Kind { + /// A batch's submission checks (`command_buffer/checks.rs`). + Check, + /// A batch's host step. + Step, +} + +/// The work the thread's passes left it, oldest first, each piece with its kind. +pub(crate) struct Left { + work: VecDeque<(Kind, W)>, + /// How many of `work`, from the front, rounds before the current one found. + ordered: usize, +} + +impl Default for Left { + fn default() -> Left { + Left { + work: VecDeque::new(), + ordered: 0, + } + } +} + +impl Left { + pub(crate) fn is_empty(&self) -> bool { + self.work.is_empty() + } + + /// Leave `work` of `kind`, found by the current round. + pub(crate) fn push(&mut self, kind: Kind, work: W) { + self.work.push_back((kind, work)); + } + + /// Whether a piece of `kind` that `same` picks is left. + pub(crate) fn holds(&self, kind: Kind, same: impl Fn(&W) -> bool) -> bool { + self.work + .iter() + .any(|(left, work)| *left == kind && same(work)) + } + + /// The current round ended: its finds go after the earlier rounds', its checks before its + /// steps, each kind in the order found. + fn end_round(&mut self) { + let found = &mut self.work.make_contiguous()[self.ordered..]; + found.sort_by_key(|(kind, _)| *kind); + self.ordered = self.work.len(); + } + + /// The oldest piece, taken out. + fn pop(&mut self) -> Option<(Kind, W)> { + let work = self.work.pop_front()?; + self.ordered = self.ordered.saturating_sub(1); + Some(work) + } +} + +/// The thread's way through its work once woken: a `round` (a pass of its own, looking at the inbox +/// again while it leaves the thread no work, and what it lets go of, `scheduler/mod.rs`), which adds +/// what it leaves to a [`Left`]; then, while work is left, rounds for as long as `inbox` holds +/// commits, and the oldest piece, which `run` runs (the module docs). `round` and `run` answer +/// false once the process is exiting, and this then answers `None`; else whether a piece ran. +pub(crate) fn work_through( + inbox: &Inbox, + mut round: impl FnMut(&mut Left) -> bool, + mut run: impl FnMut(Kind, W) -> bool, +) -> Option { + let mut left = Left::default(); + if !round(&mut left) { + return None; + } + left.end_round(); + let mut ran = false; + while !left.is_empty() { + // A commit left to this thread meanwhile goes before the next piece of work, as does one + // left to it during the round that took that one in. + while inbox.holds_commits() { + if !round(&mut left) { + return None; + } + left.end_round(); + } + let Some((kind, work)) = left.pop() else { + break; + }; + if !run(kind, work) { + return None; + } + ran = true; + } + Some(ran) +} diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index 21b881a37..59de3d501 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -14,8 +14,11 @@ //! what is ready in a pass of its own, as the commit would once it had the lock. The order sees //! every commit in commit order, and every batch is planned as it is submitted, as before. This //! thread stops looking at the inbox again at a pass that leaves it a check or a host step, and -//! looks at it before each one it runs and before it sleeps: a commit left to it waits for the -//! pass under way and the submission handlers that pass leaves, never for a wake. +//! before each one it runs passes again for as long as the inbox holds commits, and looks at it +//! before it sleeps ([`left`]): a commit left to it waits for the pass under way, the submission +//! handlers that pass leaves, and the pass that takes it in, never for a wake or a check or a +//! step. A committing thread passes at most once for what others left it; what is left to that +//! pass it hands to this thread with a wake ([`inbox::Outcome::unattended`]). //! //! - **The order** ([`Order`]). Each logical queue's batches wait in commit order; the head //! committed first among those ready goes next. A batch is ready once every event it waits for @@ -76,6 +79,7 @@ pub(super) mod binary; pub(super) mod inbox; +pub(super) mod left; pub(super) mod order; use super::command_buffer::gate::Hold; @@ -92,10 +96,11 @@ use super::tracker::{self, Footprint, Tracker}; use ash::vk; use binary::{BinarySignals, Needs}; use inbox::Inbox; +use left::{work_through, Kind, Left}; use order::{Behind, Order}; -use std::collections::{BTreeMap, VecDeque}; +use std::collections::BTreeMap; use std::sync::atomic::{fence, AtomicBool, Ordering}; -use std::sync::{Arc, Condvar, Mutex, TryLockError}; +use std::sync::{Arc, Condvar, Mutex}; use std::thread::JoinHandle; use std::time::Duration; @@ -244,12 +249,16 @@ impl Scheduler { batches, }; let (mut passed, mut left) = (Passed::default(), Left::default()); - let handed_off = (shared.inbox).commit(committed, |state, commits| { + let outcome = (shared.inbox).commit(committed, |state, commits| { pass(state, commits, (&mut passed, &mut left), shared, false); }); - if handed_off { + if outcome.left { buffer.device().shared().counts.commit_handed_off(); } + // What other threads left to this thread's last pass goes to the scheduler's thread. + if outcome.unattended { + self.wake(); + } let Passed { spent, settled, @@ -322,26 +331,16 @@ impl Scheduler { .is_some_and(|handle| handle.thread().id() == std::thread::current().id()) } - /// Look for work again: an event's value rose, or a batch completed. Where a pass is under - /// way, it passes again once done ([`Inbox::nudge`]), 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: the waker never waits for a pass's - /// submissions. + /// Look for work again: an event's value rose, a batch completed, or a commit's thread left + /// what other threads committed to the thread ([`inbox::Outcome::unattended`]). 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. pub(crate) fn wake(&self) { - let inbox = &self.shared.inbox; - if inbox.nudge() { - return; + if (self.shared.inbox).wake(|state| state.dirty = true) { + self.shared.wake.notify_all(); } - let mut state = match inbox.state().try_lock() { - Ok(state) => state, - Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), - // A pass counted since: it took the nudge in, after the change. - Err(TryLockError::WouldBlock) if inbox.passing() => return, - Err(TryLockError::WouldBlock) => lock(inbox.state()), - }; - state.dirty = true; - drop(state); - self.shared.wake.notify_all(); } /// Batches completed, their queues' completed values and their event signals published: look @@ -401,48 +400,38 @@ fn run(shared: &SchedulerShared) { // The pass takes the lock again, counted as a passer from before (`inbox.rs`): a commit // that finds it taken leaves its batches to this thread. drop(state); - let mut left = Left::default(); - if !round(shared, &mut left) { - return; + match work_through(&shared.inbox, |left| round(shared, left), run_work) { + None => return, + Some(false) => {} + // What the work did may let batches go. + Some(true) => lock(shared.inbox.state()).dirty = true, } - if left.is_empty() { - continue; - } - loop { - // A commit left to this thread meanwhile goes before the next piece of work. - if shared.inbox.holds_commits() && !round(shared, &mut left) { - return; - } - // The submission checks, then the host steps, without the lock (a check runs the - // program's code; a step records, and may make what a dispatch makes), each a - // section; once the process is exiting the thread ends at the next. - let (work, step) = match left.checks.pop_front() { - Some(check) => (check, false), - None => match left.steps.pop_front() { - Some(step) => (step, true), - None => break, - }, - }; - let Some(busy) = exit_guard::enter() else { - return; - }; - let (buffer, index) = &work; - if step { - buffer.host_step(*index); - for &call in exit_guard::HOST_STEP { - exit_guard::called(call); - } - } else { - buffer.run_checks(*index); - } - drop(busy); - // Out of the section: it may be the command buffer's last reference. - drop(work); - } - lock(shared.inbox.state()).dirty = true; } } +/// Run one piece of work the thread's passes left it, without the lock (a check runs the program's +/// code; a step records, and may make what a dispatch makes), a section of the exit guard; false, +/// with nothing run, once the process is exiting. +fn run_work(kind: Kind, work: Work) -> bool { + let Some(busy) = exit_guard::enter() else { + return false; + }; + let (buffer, index) = &work; + match kind { + Kind::Step => { + buffer.host_step(*index); + for &call in exit_guard::HOST_STEP { + exit_guard::called(call); + } + } + Kind::Check => buffer.run_checks(*index), + } + drop(busy); + // Out of the section: it may be the command buffer's last reference. + drop(work); + true +} + /// One round of the thread's: a pass, looking at the inbox again while the passes leave the /// thread no work ([`Inbox::pass`]), what they leave added to `left`; then, without the lock, /// what they let go of: the storage forms settled, the submission handlers run (on this thread, @@ -450,7 +439,7 @@ fn run(shared: &SchedulerShared) { /// more, their command buffers staying `Committed`), the holds dropped (the last reference to a /// command buffer may be among them, and with it its device, whose drop stops this thread). /// False once the process is exiting. -fn round(shared: &SchedulerShared, left: &mut Left) -> bool { +fn round(shared: &SchedulerShared, left: &mut Left) -> bool { let mut passed = Passed::default(); (shared.inbox).pass(|state, commits| { pass(state, commits, (&mut passed, &mut *left), shared, true); @@ -482,20 +471,6 @@ struct Passed { exiting: bool, } -/// What passes leave the scheduler's thread to run without the lock before the batches go: the -/// submission checks, then the host steps ([`submit_ready`]'s outputs). -#[derive(Default)] -struct Left { - steps: Steps, - checks: Steps, -} - -impl Left { - fn is_empty(&self) -> bool { - self.steps.is_empty() && self.checks.is_empty() - } -} - /// A pass: take `commits` into the order, in commit order, then submit what is ready /// ([`submit_ready`]) into `passed` and `left`. A pass on a thread other than the scheduler's /// (`own` false) was the thread's but for what it leaves it: the thread looks again only for @@ -504,7 +479,7 @@ impl Left { fn pass( state: &mut State, commits: Vec, - (passed, left): (&mut Passed, &mut Left), + (passed, left): (&mut Passed, &mut Left), shared: &SchedulerShared, own: bool, ) { @@ -535,7 +510,7 @@ fn pass( let exiting = submit_ready( state, (&mut passed.spent, &mut passed.settled), - (&mut left.steps, &mut left.checks), + left, &mut passed.handlers, &shared.gated, ) @@ -562,9 +537,9 @@ struct Spent { /// learn of it (`exit_guard`). A batch's events are let go of before its command buffer /// (`gate`), whose holds go to `spent`, for the caller to drop without the lock, as do the logs /// a command buffer's first submission ended (`replay.rs`). A batch whose -/// host step may run now goes to `steps` (once), for the caller to record without the lock; -/// `gated` says whether one still waits at its gate. A batch whose submission checks may run -/// now goes to `checks` (once), for the caller to run without the lock. A command buffer whose +/// host step may run now goes to `left` as a step (once), for the caller to record without the +/// lock; `gated` says whether one still waits at its gate. A batch whose submission checks may run +/// now goes to `left` as a check (once), for the caller to run without the lock. A command buffer whose /// last batch was submitted, or that failed, and on which a fetched target's storage form rides /// (`texture/storage_form.rs`) is settled and goes to `settled`, for the caller to announce /// without the lock ([`settle`]). A command buffer whose last batch was submitted with @@ -573,7 +548,7 @@ struct Spent { fn submit_ready( state: &mut State, (spent, settled): (&mut Spent, &mut Settled), - (steps, checks): (&mut Steps, &mut Steps), + left: &mut Left, handlers: &mut Handlers, gated: &AtomicBool, ) -> Result<(), Exiting> { @@ -595,8 +570,8 @@ fn submit_ready( .filter(|&sequence| is_behind(&state.order, &state.binary, &mut memo, sequence)) .collect(), }; - let waiting = gate_heads(state, &behind, steps, gated); - let landing = check_heads(state, &behind, checks, gated); + let waiting = gate_heads(state, &behind, left, gated); + let landing = check_heads(state, &behind, left, gated); let binary = &state.binary; let decodes = &state.decodes; let untracked_decodes = state.untracked_decodes; @@ -723,17 +698,22 @@ fn run_submission_handlers(handlers: Handlers) { } } -/// Batches for the thread to work on without its lock: each command buffer with the batch's -/// index. -type Steps = VecDeque<(Hold, usize)>; +/// A batch for the thread to work on without its lock: its command buffer with the batch's index. +type Work = (Hold, usize); /// Look at each line's head of a command buffer with a submission check that is otherwise /// ready (its binary semaphores' signals submitted, its events' values reached, its host step /// recorded, not `behind` an earlier commit) and waits for its checks: once every value it waits /// for was reached on the device or by the host, not only by a submitted GPU signal (or the device -/// is lost), it goes to `checks`, unless there already. `gated` is set before the events are read -/// again, as [`Scheduler::completions`] says. Whether a head still waits for a GPU signal to land. -fn check_heads(state: &mut State, behind: &[u64], checks: &mut Steps, gated: &AtomicBool) -> bool { +/// is lost), it goes to `left` as a check, unless there already. `gated` is set before the events +/// are read again, as [`Scheduler::completions`] says. Whether a head still waits for a GPU signal +/// to land. +fn check_heads( + state: &mut State, + behind: &[u64], + left: &mut Left, + gated: &AtomicBool, +) -> bool { let State { order, binary, .. } = state; let mut landing = false; for held in order.heads_mut(behind) { @@ -741,9 +721,9 @@ fn check_heads(state: &mut State, behind: &[u64], checks: &mut Steps, gated: &At || !binary.ready(&held.binary_needs) || (held.segments && held.buffer.needs_host_step(held.index)) || !held.buffer.needs_check(held.index) - || checks - .iter() - .any(|(buffer, index)| buffer.same(&held.buffer) && *index == held.index) + || left.holds(Kind::Check, |(buffer, index)| { + buffer.same(&held.buffer) && *index == held.index + }) { continue; } @@ -759,7 +739,7 @@ fn check_heads(state: &mut State, behind: &[u64], checks: &mut Steps, gated: &At } Some(_) => {} } - checks.push_back((held.buffer.hold(), held.index)); + left.push(Kind::Check, (held.buffer.hold(), held.index)); } landing } @@ -767,10 +747,15 @@ fn check_heads(state: &mut State, behind: &[u64], checks: &mut Steps, gated: &At /// Look at each line's head that is otherwise ready (not `behind` an earlier commit either, /// its gate then covers that commit's work) and needs a host step: its gate is taken (the queues' /// submitted values, the first time), and once every `VkQueue`'s completed value reached it (or the -/// device is lost), its step goes to `steps`, unless there already. `gated` is set before the +/// device is lost), its step goes to `left`, unless there already. `gated` is set before the /// completed values are read, as [`Scheduler::completions`] says. Whether a head still waits at its /// gate. -fn gate_heads(state: &mut State, behind: &[u64], steps: &mut Steps, gated: &AtomicBool) -> bool { +fn gate_heads( + state: &mut State, + behind: &[u64], + left: &mut Left, + gated: &AtomicBool, +) -> bool { let State { order, values, @@ -783,9 +768,9 @@ fn gate_heads(state: &mut State, behind: &[u64], steps: &mut Steps, gated: &Atom || !binary.ready(&held.binary_needs) || event_waits(held).is_none() || !held.buffer.needs_host_step(held.index) - || steps - .iter() - .any(|(buffer, index)| buffer.same(&held.buffer) && *index == held.index) + || left.holds(Kind::Step, |(buffer, index)| { + buffer.same(&held.buffer) && *index == held.index + }) { continue; } @@ -796,7 +781,7 @@ fn gate_heads(state: &mut State, behind: &[u64], steps: &mut Steps, gated: &Atom continue; } if !waits.gpu { - steps.push_back((held.buffer.hold(), held.index)); + left.push(Kind::Step, (held.buffer.hold(), held.index)); continue; } let gate = held.gate.get_or_insert_with(|| values.clone()); @@ -811,7 +796,7 @@ fn gate_heads(state: &mut State, behind: &[u64], steps: &mut Steps, gated: &Atom .zip(gate.iter()) .all(|(queue, &value)| queue.completed_value() >= value); if reached { - steps.push_back((held.buffer.hold(), held.index)); + left.push(Kind::Step, (held.buffer.hold(), held.index)); } else { waiting = true; } diff --git a/crates/metal2vulkan-runtime/src/tests/inbox.rs b/crates/metal2vulkan-runtime/src/tests/inbox.rs index 7d7ba23cb..1a6161880 100644 --- a/crates/metal2vulkan-runtime/src/tests/inbox.rs +++ b/crates/metal2vulkan-runtime/src/tests/inbox.rs @@ -1,15 +1,18 @@ //! `scheduler/inbox.rs`: a commit that finds a pass under way on another thread returns at once //! and its commit goes next, in commit order; one that finds the lock held for no pass passes //! itself; the scheduler's pass looks again for a commit left to it until a pass answers it has -//! work of its own first; and 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; and a nudge finding a pass under way returns at once and is passed for once that -//! pass ends. +//! work of its own first; a committing thread passes once for what others left it, and leaves the +//! rest to the thread its caller wakes; commits from many threads racing passes, ones that stop +//! looking again, wakes 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 and is passed for +//! once that pass ends; and wakers racing passes and commits have every change they made read by +//! a pass. use crate::device::lock; -use crate::scheduler::inbox::Inbox; +use crate::scheduler::inbox::{Inbox, Outcome, AGAIN}; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc; -use std::sync::Arc; +use std::sync::{Arc, Condvar}; use std::thread; use std::time::{Duration, Instant}; @@ -25,6 +28,19 @@ fn take_in(log: &mut Vec, commits: Vec) { log.extend(commits); } +/// Commit `commit` from another thread while this one holds `inbox`'s lock for a pass: what +/// became of it. It is left to this thread's pass, so it makes none itself. +pub(super) fn commit_elsewhere(inbox: &Inbox, commit: C) -> Outcome { + thread::scope(|scope| { + let committer = scope.spawn(|| { + inbox.commit(commit, |_, _| { + panic!("a commit that found a pass under way passed itself") + }) + }); + committer.join().unwrap() + }) +} + #[test] 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())); @@ -51,7 +67,7 @@ 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.commit(commit, take_in)).unwrap(); + done.send(inbox.commit(commit, take_in).left).unwrap(); } }) }; @@ -64,9 +80,10 @@ fn a_commit_finding_a_pass_under_way_returns_at_once_and_goes_next_in_commit_ord committer.join().unwrap(); assert!(inbox.holds_commits()); release.send(()).unwrap(); - assert!( - !passer.join().unwrap(), - "the passer's own commit was its own" + assert_eq!( + passer.join().unwrap(), + Outcome::default(), + "the passer's own commit was its own, and it passed for the others" ); // The passer took them in once its pass ended, in commit order, with no pass asked for. assert_eq!(*lock(inbox.state()), [0, 1, 2, 3]); @@ -88,7 +105,11 @@ fn a_commit_finding_the_lock_held_for_no_pass_passes_itself() { thread::yield_now(); } drop(held); - assert!(!committer.join().unwrap(), "it passed its commit itself"); + assert_eq!( + committer.join().unwrap(), + Outcome::default(), + "it passed its commit itself" + ); assert_eq!(*lock(inbox.state()), [7]); assert!(!inbox.holds_commits()); } @@ -117,7 +138,7 @@ fn the_scheduler_s_pass_looks_again_until_a_pass_answers_it_has_work_first() { }) }; in_pass.recv_timeout(WAIT).unwrap(); - assert!(inbox.commit(1, take_in), "left to the pass under way"); + assert!(inbox.commit(1, take_in).left, "left to the pass under way"); release.send(()).unwrap(); let passes = scheduler.join().unwrap(); if again { @@ -140,62 +161,199 @@ fn the_scheduler_s_pass_looks_again_until_a_pass_answers_it_has_work_first() { } } +/// A committing thread makes its own pass and [`AGAIN`] more for what other threads left it while +/// it passed, however many they leave it meanwhile: the last one left waits in the inbox, which it +/// answers was left unattended, for its caller to wake the thread that makes passes itself. #[test] -fn commits_racing_passes_and_short_holds_are_all_passed_each_thread_s_in_its_order() { +fn a_committing_thread_passes_once_for_the_others_and_leaves_the_rest_to_a_wake() { + let inbox = Log::new(Vec::new()); + let mut passes = 0; + let outcome = inbox.commit(0, |log, commits| { + take_in(log, commits); + passes += 1; + // While each of its passes is under way, another thread's commit is left to it. + if passes <= 4 { + assert!(commit_elsewhere(&inbox, passes).left); + } + }); + assert_eq!( + passes as usize, + 1 + AGAIN, + "its own pass and {AGAIN} for the others'" + ); + assert_eq!( + outcome, + Outcome { + left: false, + unattended: true + } + ); + assert_eq!(*lock(inbox.state()), [0, 1]); + assert!( + inbox.holds_commits(), + "the last one left waits for the thread its caller wakes" + ); + inbox.pass(|log, commits| { + take_in(log, commits); + true + }); + assert_eq!(*lock(inbox.state()), [0, 1, 2]); + assert!(!inbox.holds_commits()); +} + +/// 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. +#[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. +struct Model { + inbox: Inbox, + woken: Condvar, +} + +impl Model { + fn new(wakers: usize) -> Model { + Model { + inbox: Inbox::new(Seen { + values: vec![0; wakers], + ..Seen::default() + }), + woken: Condvar::new(), + } + } + + /// `Scheduler::commit`'s: commit, and wake the thread where the inbox was left unattended. + fn commit(&self, commit: u32, pass: impl FnMut(&mut Seen, Vec)) -> Outcome { + let outcome = self.inbox.commit(commit, pass); + if outcome.unattended { + self.wake(); + } + outcome + } + + /// `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(); + 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. + fn run(&self, mut pass: impl FnMut(&mut Seen, Vec), again: impl Fn(u64) -> bool) { + let asked = |seen: &Seen| seen.dirty || 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(); + } + if !asked(&seen) { + return; + } + drop(seen); + self.inbox.pass(|seen, commits| { + seen.dirty = false; + pass(seen, commits); + passes += 1; + again(passes) + }); + } + } + + fn stop(&self) { + lock(self.inbox.state()).stop = true; + self.woken.notify_all(); + } +} + +/// A pass that holds the lock a while, so that commits and wakes find it under way. +fn slow(seen: &mut Seen, commits: Vec) { + for _ in 0..200 { + std::hint::spin_loop(); + } + seen.log.extend(commits); +} + +/// Whether `done` holds of the model's state within [`WAIT`], read every millisecond. +fn soon(model: &Model, done: impl Fn(&Seen) -> bool) -> bool { + let until = Instant::now() + WAIT; + while !done(&lock(model.inbox.state())) { + if Instant::now() > until { + return false; + } + thread::sleep(Duration::from_millis(1)); + } + true +} + +/// Commits from several threads race the scheduler thread's passes, which answer in turn that +/// they have work first, and short holds: each is passed once, each thread's in its order, by a +/// pass made for it or by the thread its committer woke, with no pass made for them at the end. +#[test] +fn commits_racing_passes_wakes_and_short_holds_are_all_passed_each_thread_s_in_its_order() { const THREADS: u32 = 4; const COMMITS: u32 = 2000; - let inbox = Arc::new(Log::new(Vec::new())); - // A pass that holds the lock a while, so that commits find it under way. - let slow = |log: &mut Vec, commits: Vec| { - for _ in 0..200 { - std::hint::spin_loop(); - } - log.extend(commits); - }; - let committers: Vec<_> = (0..THREADS) - .map(|index| { - let inbox = Arc::clone(&inbox); - thread::spawn(move || { - (0..COMMITS) - .filter(|&commit| inbox.commit(index * COMMITS + commit, slow)) - .count() + let model = Model::new(0); + let all = (THREADS * COMMITS) as usize; + let (left, unattended, passed_all) = thread::scope(|scope| { + // The scheduler's thread: every other pass answers it has work of its own first. + let scheduler = scope.spawn(|| model.run(slow, |pass| pass % 2 == 0)); + let committers: Vec<_> = (0..THREADS) + .map(|index| { + let model = &model; + scope.spawn(move || { + let outcomes: Vec = (0..COMMITS) + .map(|commit| model.commit(index * COMMITS + commit, slow)) + .collect(); + let count = |what: fn(&Outcome) -> bool| { + outcomes.iter().filter(|outcome| what(outcome)).count() + }; + (count(|o| o.left), count(|o| o.unattended)) + }) }) - }) - .collect(); - // The scheduler's thread: passes of its own, every other one answering it has work first, - // which the thread's next pass follows, as its own look before it sleeps would; the last one - // looks again. - let scheduler = { - let inbox = Arc::clone(&inbox); - thread::spawn(move || { - for round in 0..COMMITS { - inbox.pass(|log, commits| { - slow(log, commits); - round % 2 == 0 || round + 1 == COMMITS - }); - thread::yield_now(); - } - }) - }; - // A wake, a decode count: short holds that make no pass. - let marker = { - let inbox = Arc::clone(&inbox); - thread::spawn(move || { + .collect(); + // A decode count: short holds that make no pass. + let marker = scope.spawn(|| { for _ in 0..COMMITS { - drop(lock(inbox.state())); + drop(lock(model.inbox.state())); thread::yield_now(); } - }) - }; - let left: usize = committers.into_iter().map(|c| c.join().unwrap()).sum(); - scheduler.join().unwrap(); - marker.join().unwrap(); - // No pass made for them at the end: every commit was passed by then. - assert!(!inbox.holds_commits(), "{left} left to other threads"); - let log = lock(inbox.state()); - assert_eq!(log.len(), (THREADS * COMMITS) as usize, "each once"); + }); + let counts: Vec<(usize, usize)> = (committers.into_iter()) + .map(|committer| committer.join().unwrap()) + .collect(); + marker.join().unwrap(); + // The thread passes for nothing on its own: a commit left unattended waits for its wake. + let passed_all = soon(&model, |seen| seen.log.len() == all); + model.stop(); + scheduler.join().unwrap(); + let (left, unattended) = (counts.into_iter()).fold((0, 0), |(l, u), (left, unattended)| { + (l + left, u + unattended) + }); + (left, unattended, passed_all) + }); + let seen = lock(model.inbox.state()); + assert!( + passed_all, + "{} of {all} passed ({left} left to other threads, {unattended} left unattended)", + seen.log.len() + ); + eprintln!("INBOX-RACE commits: {left} left to other threads, {unattended} left unattended"); + assert!(!model.inbox.holds_commits()); + assert_eq!(seen.log.len(), all, "each once"); for index in 0..THREADS { - let own: Vec = (log.iter().copied()) + let own: Vec = (seen.log.iter().copied()) .filter(|commit| commit / COMMITS == index) .collect(); let ordered: Vec = (index * COMMITS..(index + 1) * COMMITS).collect(); @@ -245,3 +403,78 @@ fn a_nudge_finding_a_pass_under_way_is_passed_for_once_it_ends() { }); assert!(!inbox.nudged(), "the next pass took it in"); } + +/// Wakers each raise a value of their own and wake for a pass (an event's value rising, a batch +/// completing), racing the scheduler thread's passes, committing threads' passes and their wakes: +/// once they are done, a pass read every waker's last value, made for its wake, with no pass made +/// for it at the end. A nudge taken in by a pass is read with what its waker changed before it. +#[test] +fn wakers_racing_passes_and_commits_have_every_change_read_by_a_pass() { + const WAKERS: usize = 3; + const RAISES: u64 = 3000; + const THREADS: u32 = 2; + const COMMITS: u32 = 2000; + let model = Model::new(WAKERS); + let values: Vec = (0..WAKERS).map(|_| AtomicU64::new(0)).collect(); + let read = |seen: &mut Seen, commits: Vec| { + for _ in 0..100 { + std::hint::spin_loop(); + } + seen.log.extend(commits); + // Raised with no ordering of their own: only the wake orders a raise before a pass. + for (seen, value) in seen.values.iter_mut().zip(&values) { + *seen = value.load(Ordering::Relaxed); + } + }; + let (read_all, left) = thread::scope(|scope| { + // Every third pass answers it has work of its own first. + let scheduler = scope.spawn(|| model.run(read, |pass| pass % 3 != 0)); + let committers: Vec<_> = (0..THREADS) + .map(|index| { + let model = &model; + scope.spawn(move || { + for commit in 0..COMMITS { + model.commit(index * COMMITS + commit, read); + } + }) + }) + .collect(); + let wakers: Vec<_> = (0..WAKERS) + .map(|waker| { + let (model, value) = (&model, &values[waker]); + scope.spawn(move || { + let mut left = 0; + for raise in 1..=RAISES { + value.store(raise, Ordering::Relaxed); + left += u64::from(model.wake()); + if raise % 8 == 0 { + thread::yield_now(); + } + } + left + }) + }) + .collect(); + for thread in committers { + thread.join().unwrap(); + } + let left: u64 = (wakers.into_iter()) + .map(|thread| thread.join().unwrap()) + .sum(); + // The last raises' wakes were passed for; the thread passes on its own for nothing. + let read_all = soon(&model, |seen| seen.values == [RAISES; WAKERS]); + model.stop(); + scheduler.join().unwrap(); + (read_all, left) + }); + let seen = lock(model.inbox.state()); + let wakes = RAISES * WAKERS as u64; + eprintln!("INBOX-RACE wakes: {left} of {wakes} left to a pass under way"); + assert!( + read_all, + "a wake was lost: the passes read {:?} of {RAISES}", + seen.values + ); + assert_eq!(seen.log.len(), (THREADS * COMMITS) as usize, "each once"); + assert!(!model.inbox.holds_commits() && !model.inbox.nudged()); +} diff --git a/crates/metal2vulkan-runtime/src/tests/left.rs b/crates/metal2vulkan-runtime/src/tests/left.rs new file mode 100644 index 000000000..2222b2f37 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/left.rs @@ -0,0 +1,133 @@ +//! `scheduler/left.rs`: the scheduler thread's way through the work its passes leave it. A commit +//! left to the thread during any round goes before its next piece of work, also one left during +//! the round that took an earlier one in; the work runs in the order the rounds found it, a +//! round's checks before its steps; and the exit ends it. + +use super::inbox::commit_elsewhere; +use crate::device::lock; +use crate::scheduler::inbox::Inbox; +use crate::scheduler::left::{work_through, Kind, Left}; + +/// What happened, in order: a commit taken in by a pass, a piece of work run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Event { + TakenIn(u32), + Ran(Kind, u32), +} + +use Event::{Ran, TakenIn}; +use Kind::{Check, Step}; + +type Log = Inbox, u32>; + +/// Run [`work_through`] over `inbox`, each round a pass of the thread's that takes the commits +/// in, `finds` adding what the round of its number leaves and answering whether another thread +/// commits while its pass is under way (left to it); each pass answers it has work first while +/// work is left, as the thread's do. Whether a piece ran. +fn work(inbox: &Log, mut finds: impl FnMut(u32, &mut Left) -> bool) -> Option { + let (mut rounds, mut commits) = (0, 0); + work_through( + inbox, + |left| { + rounds += 1; + inbox.pass(|log, taken| { + log.extend(taken.into_iter().map(TakenIn)); + if finds(rounds, left) { + commits += 1; + assert!(commit_elsewhere(inbox, commits).left); + } + left.is_empty() + }); + true + }, + |kind, work| { + lock(inbox.state()).push(Ran(kind, work)); + true + }, + ) +} + +/// The first round leaves two checks, and a commit is left to it; so is another to the round +/// that takes that one in: the thread takes both in before it runs a check, not the second after +/// the first check. +#[test] +fn a_commit_left_to_the_thread_during_any_round_goes_before_its_next_piece_of_work() { + let inbox = Log::new(Vec::new()); + let ran = work(&inbox, |round, left| { + if round == 1 { + left.push(Check, 1); + left.push(Check, 2); + } + round <= 2 + }); + assert_eq!(ran, Some(true)); + assert_eq!( + *lock(inbox.state()), + [TakenIn(1), TakenIn(2), Ran(Check, 1), Ran(Check, 2)] + ); + assert!(!inbox.holds_commits()); +} + +/// The first round finds steps and checks, a commit left to it; the round that takes it in finds +/// a check and a step. The first round's work runs first, its checks before its steps, then the +/// second's: a step waits for no check found after it. +#[test] +fn work_runs_in_the_order_the_rounds_found_it_a_round_s_checks_before_its_steps() { + let inbox = Log::new(Vec::new()); + let ran = work(&inbox, |round, left| { + match round { + 1 => { + left.push(Step, 1); + left.push(Check, 2); + left.push(Step, 3); + left.push(Check, 4); + } + 2 => { + left.push(Step, 5); + left.push(Check, 6); + } + _ => {} + } + round == 1 + }); + assert_eq!(ran, Some(true)); + assert_eq!( + *lock(inbox.state()), + [ + TakenIn(1), + Ran(Check, 2), + Ran(Check, 4), + Ran(Step, 1), + Ran(Step, 3), + Ran(Check, 6), + Ran(Step, 5), + ] + ); +} + +/// A round that leaves nothing ends it with nothing run; a round or a piece of work that finds the +/// process exiting ends it at once. +#[test] +fn nothing_left_or_the_exit_ends_it() { + let inbox = Log::new(Vec::new()); + assert_eq!(work(&inbox, |_, _| false), Some(false)); + assert_eq!( + work_through(&inbox, |_: &mut Left| false, |_, _| true), + None + ); + let mut ran = Vec::new(); + let exiting = work_through( + &inbox, + |left| { + left.push(Check, 1); + left.push(Check, 2); + true + }, + |kind, work| { + ran.push((kind, work)); + false + }, + ); + assert_eq!(exiting, None); + assert_eq!(ran, [(Check, 1)]); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 5d9513eb0..998d7f87d 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -69,6 +69,7 @@ mod indirect_command_buffer; mod interop; mod keeper; mod kept_barriers; +mod left; mod linear_attachment; mod linear_plan; mod making; diff --git a/crates/metal2vulkan-runtime/src/texture/storage_form.rs b/crates/metal2vulkan-runtime/src/texture/storage_form.rs index 7dfc58cd0..aafa153b2 100644 --- a/crates/metal2vulkan-runtime/src/texture/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/texture/storage_form.rs @@ -61,8 +61,9 @@ //! `switching`, up only during a switch. Counting the uncommitted command buffers adds one //! atomic add to a slot's taking and one subtraction to its commit (or its drop uncommitted), //! under its queue's lock. The stall: once per texture, the next command buffer made after a -//! checked commit that took a switch waits until the scheduler's thread ran its check and -//! submitted it. +//! commit that took a switch and did not submit it itself waits until it is submitted: a +//! checked commit's, until the scheduler's thread ran its check and submitted it; one left to +//! another thread's pass (`scheduler/inbox.rs`), until that thread's next pass submitted it. use super::{texture_aspects, Image, ImageObjects, Owner, Storage, Texture, TextureShared}; use crate::degradation::Degradation; diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index b1993b2b3..575976283 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -790,8 +790,10 @@ pub struct WorkCounts { /// copy through the GPU, a clear of a live buffer, a neutral's making. pub internal_submissions: u64, /// `vkQueueSubmit` and `vkQueueBindSparse` calls the runtime made on the device's queues once - /// it was made: every batch's, its new resources' first work's apart (`texture/first_move.rs`), - /// internal and staging submissions, sparse binds, and fences submitted with no work. Each is a + /// it was made: every batch's (its new resources' first work rides in the same call, in a + /// `VkSubmitInfo` of its own before the batch's, `texture/first_move.rs`), internal and + /// staging submissions (an internal submission's first work likewise), sparse binds, and + /// fences submitted with no work. Each is a /// submission of its own to the driver; Mesa's drivers merge the `VkSubmitInfo`s of one call /// where no signal lies between a command and a later one, and no further (`vk_queue.c`). pub queue_submissions: u64, diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 25b44b509..1c9706b6e 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -e9ed22eb2280cb6f1a7ea8811e3f4b2c2a32bcc5aca217dc670864b84f357848 +581e5e5522ddfb5c61d4b949e7b7b01e210925bff898241bcd517ef6fdee40f2 diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 89a8df730..6ad76507e 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 399; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1196; +pub const RUNTIME_VERSION: u32 = 1197; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles