From 4ef6cbad82a9f2a6d65153cdd02f73ac71768cfd Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 9 Nov 2026 00:25:37 -0800 Subject: [PATCH] Scheduler: an owed completion turn goes before the thread's submission handlers What. A command buffer that needs no GPU work is taken with no submission and, where its VkQueue has no work in flight and no turn is under way, its completion turn is owed to the thread that took it (Completion::turn_owed). The scheduler's thread made that turn at the end of its round, after the round's submission handlers; a committing thread's pass (Scheduler::submit_at_commit) made it after its handlers and its check. Both now make it before them: round makes the owed turn after settling the storage-form switches and before Turns::run, and the committing thread makes it after each pass, before AtCommit::let_go. Why. A submission handler that waits for the completed handler of such a command buffer of another queue, taken in the same pass, waited for a turn that only its own return let the thread make. This is the Iris Xe red of runtime_lane::host_memory::a_deallocator_returns_whatever_thread_submits_past_its_completion under CompletionPolicy::Exact: its `after` is an empty command buffer, and where the fill before it on its queue had completed by the time the pass took it, `after` read Scheduled for the whole 60 s that `holding`'s submission handler waited ("1 kernel submissions ... in 2 passes", every held head count 0). Its completed handler then ran once that handler gave up. Reproduced on lavapipe under load at 961902036: 4 failures in 240 runs of the test, four loops beside two parallel runs of the runtime lane. Metal delivers a command buffer's completion to another queue's handler that waits for it (the probe cross_queue_handler_waits, 30 of 30, as in ad451a5334). Test. tests::unsubmitted::an_empty_command_buffer_completes_while_another_queue_s_submission_handler_waits_for_it, under Exact and Grouped. With every queue idle, an opener holds the scheduler's thread in its submission handler while an empty command buffer with a completed handler (first queue) and a command buffer whose submission handler waits for that completed handler (second queue) are committed, so one pass takes both. It also checks that all three were taken with no submission. Without the fix the handler waits the whole SETTLE and the test fails. Docs: the scheduler's module docs and round, submit_at_commit, the completion module's "No GPU work" entry, add_submission_handler ("Keep it short") and the runtime README's handler entry. (cherry picked from commit fcc20eec92e10a652bf81f38648086cdf6eb7452) --- crates/metal2vulkan-runtime/README.md | 4 +- .../src/command_buffer/completion.rs | 6 +- .../src/command_buffer/mod.rs | 7 +- .../metal2vulkan-runtime/src/scheduler/mod.rs | 35 +++++--- .../src/tests/unsubmitted.rs | 90 ++++++++++++++++++- 5 files changed, 122 insertions(+), 20 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index cf7b7e76d..2b1617ed8 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -458,7 +458,9 @@ Calls Metal does not have, for a consumer that emulates a Metal device: the conformance case `event-wait-behind-a-running-signal`). - `CommandBuffer::add_submission_handler` is called when the runtime takes the command buffer's last batch for its queue (submits it, or holds it for one kernel submission with later ones; - what another queue's command buffers had held then goes to the driver before it runs); + what another queue's command buffers had held then goes to the driver before it runs, and the + completion of one that needs no GPU work, taken with no submission behind no work in flight, + never waits for it); `add_executed_commands_handler` each time an execution's indirect records are read. - `CommandBuffer::add_completion_seen_handler` is called once the command buffer completed, its status, error and GPU times final, on the runtime's thread that saw it complete (its queue's diff --git a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs index a3f705e69..e5904627e 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs @@ -107,8 +107,10 @@ //! that finishes the batch before it, by the waiter that saw that one complete. Where its queue //! reached that value already and no turn is under way, no waiter is woken for it: the thread //! that took it makes the turn itself once it holds no lock ([`Completion::turn_owed`]), the -//! scheduler's or a thread about to block for a command buffer, which runs only plain -//! transitions (`CommandBufferShared::finish_here`). A turn takes every queue's batches seen +//! scheduler's, a committing thread's or a thread about to block for a command buffer, which +//! runs only plain transitions (`CommandBufferShared::finish_here`), and makes it before it +//! runs a submission handler or check: one that waited for that completion would otherwise +//! wait for its own return. A turn takes every queue's batches seen //! reached, so the one turn at a time on the device keeps every order above. Counted: //! `WorkCounts::completion_turns_where_taken`. //! - **Published once a host wait returned for it** ([`seen`]). The host sees a batch's writes once diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index d49f64b7c..d82ccd9f4 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -2683,8 +2683,11 @@ impl CommandBuffer { /// work otherwise. What the runtime took before it runs is never held back by it for /// another command queue: batches held for one kernel submission go to the driver before /// the scheduler thread runs a handler of a command buffer of another queue than theirs, as - /// Metal schedules a queue's command buffers whatever another queue's handler does. Those of - /// its own queue may wait for it, as Metal runs one queue's handlers one at a time. + /// Metal schedules a queue's command buffers whatever another queue's handler does; and a + /// command buffer taken with no submission (it needs no GPU work) whose `VkQueue` has no + /// work in flight has its completion turn made before the thread that took it runs a + /// handler, so its completion never waits for one. Those of its own queue may wait for it, + /// as Metal runs one queue's handlers one at a time. /// /// 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/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index 34a001dbd..409cc568d 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -88,7 +88,10 @@ //! submission handlers once it submitted its last batch, or held it in a group (below), in //! submission order among the command buffers its passes took so, once it let go of the lock //! and before it lets go of the command buffers, before its next pass, which they hold back. -//! The command buffer's transition to `Scheduled` waits for them. +//! The command buffer's transition to `Scheduled` waits for them. They hold back no completion +//! of what the passes took: a command buffer taken with no submission whose `VkQueue` has no +//! work in flight, whose completion turn is this thread's (`Completion::turn_owed`), is +//! finished before they run. //! - **Host steps**. A batch that executes commands the GPU may write //! (`CommandBufferShared::needs_host_step`) is held, once otherwise ready, until every //! `VkQueue` completed what was submitted to it by then (its gate, a snapshot of the queues' @@ -950,8 +953,9 @@ impl Scheduler { /// meanwhile, goes to the thread, which it wakes ([`Woken::Host`]); else, where it submitted /// alone a batch that may wait in a group ([`Plain::alone`]), it wakes the thread as that /// batch's hand-off would have ([`Woken::Commit`], the module docs). Where a passer is counted, - /// that pass takes the commit in. Then it makes the completion turn a command buffer that needs - /// no GPU work left it (`Completion::turn_owed`). + /// that pass takes the commit in. After each pass, before its submission handlers and its + /// check, it makes the completion turn a command buffer that needs no GPU work left it + /// (`Completion::turn_owed`), so neither waits for that completion. /// /// It runs the program's code only in the submission checks of the heads it checks and the /// submission handlers of the batches it submitted: a scheduled handler is run on its queue's @@ -972,6 +976,10 @@ impl Scheduler { submitted += pass.submitted; alone += pass.alone; let left_over = pass.left_over; + // The completion turn a command buffer the pass took with no submission left + // this thread, before the handlers and the check, as the scheduler's thread + // makes it before its handlers ([`round`]). + device.shared().completion.turn_owed(); let Some(check) = pass.let_go(&shared.turns, device) else { return (submitted, alone, checked, left_over); }; @@ -996,7 +1004,6 @@ impl Scheduler { } else if alone > 0 { self.wake_for(Woken::Commit); } - device.shared().completion.turn_owed(); } /// What makes the thread look for work again from any thread: a pipeline a held batch's @@ -1376,12 +1383,12 @@ fn run_work(shared: &Arc, kind: Kind, work: Work) -> bool { /// thread no work and none stopped at [`PASS_SUBMISSIONS`] ([`Inbox::pass`]; such a pass marked /// the state for the next round), what they leave added to `left` and what they let go of to /// `passed` (empty, kept from round to round); then, without the lock, what they let go of: the -/// switches of storage forms settled ended and the submission handlers run (on this thread, -/// before its next pass; neither once the process is exiting, as the thread then runs nothing -/// 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. +/// switches of storage forms settled ended, the completion turn a command buffer they took with +/// no submission left this thread made (`Completion::turn_owed`), and the submission handlers +/// run (on this thread, before its next pass; none of these once the process is exiting, as the +/// thread then runs nothing 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, passed: &mut Passed) -> bool { (shared.inbox).pass(|state, commits| { shared.passes.fetch_add(1, Ordering::Relaxed); @@ -1398,13 +1405,15 @@ fn round(shared: &SchedulerShared, left: &mut Left, passed: &mut Passed) - } } else { settle(&mut passed.settled); - shared.turns.run(&mut passed.handlers, &mut passed.turns); // A command buffer that needs no GPU work, taken with no submission behind no work in - // flight, is finished by this thread, after its submission handlers and holding no lock - // (`Completion::turn_owed`). Every command buffer the passes took is in `spent`. + // flight, is finished by this thread, holding no lock (`Completion::turn_owed`), before + // it runs a submission handler: a handler that waits for its completion (another + // queue's, as Metal delivers) would otherwise wait for its own return. Every command + // buffer the passes took is in `spent`. if let Some(buffer) = passed.spent.first() { buffer.device().shared().completion.turn_owed(); } + shared.turns.run(&mut passed.handlers, &mut passed.turns); } passed.spent.clear(); !passed.exiting diff --git a/crates/metal2vulkan-runtime/src/tests/unsubmitted.rs b/crates/metal2vulkan-runtime/src/tests/unsubmitted.rs index 0f4f59f91..c59c9622e 100644 --- a/crates/metal2vulkan-runtime/src/tests/unsubmitted.rs +++ b/crates/metal2vulkan-runtime/src/tests/unsubmitted.rs @@ -6,7 +6,8 @@ //! (`Completion::turn_owed`, `WorkCounts::completion_turns_where_taken`). One that signals an //! event is submitted as before. Behind a batch the scheduler holds in its group //! (`command_buffer/group.rs`), it goes in the group's submission instead, as any batch behind a -//! group held does. +//! group held does. The thread that took it makes that turn before it runs a submission handler, +//! so a handler of another queue's command buffer may wait for its completion. //! //! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. @@ -17,7 +18,7 @@ use crate::{ ResourceOptions, }; use metal2vulkan::device::{CompletionPolicy, DevicePolicy}; -use std::sync::{Arc, Mutex}; +use std::sync::{mpsc, Arc, Mutex}; /// The command buffers of each kind. const ROUNDS: u64 = 40; @@ -250,6 +251,91 @@ fn completes_behind(completion: CompletionPolicy) { ); } +/// An empty command buffer completes while a submission handler of another queue's command +/// buffer, taken in the same pass of the scheduler's thread, waits for its completed handler: the +/// thread makes the completion turn the empty one left it, its queue idle, before it runs the +/// pass's submission handlers (`scheduler/mod.rs`, `round`), as Metal delivers a command buffer's +/// completion to another queue's handler that waits for it +/// (`CommandBuffer::add_submission_handler`). `opener`, whose own submission handler holds that +/// thread until both are committed, puts the two in one pass. +#[test] +fn an_empty_command_buffer_completes_while_another_queue_s_submission_handler_waits_for_it() { + for completion in [CompletionPolicy::Exact, CompletionPolicy::Grouped] { + completes_past_a_handler(completion); + } +} + +/// [`an_empty_command_buffer_completes_while_another_queue_s_submission_handler_waits_for_it`] +/// under `completion`. +fn completes_past_a_handler(completion: CompletionPolicy) { + let device = device_with(completion); + let (first, second) = ( + device.new_command_queue().unwrap(), + device.new_command_queue().unwrap(), + ); + // The device's first work done and every queue idle, so the empty command buffer is taken + // behind no work in flight. + for queue in [&first, &second] { + let idle = queue.command_buffer().unwrap(); + idle.commit().unwrap(); + idle.wait_until_completed().unwrap(); + } + let before = device.work_counts(); + let opener = second.command_buffer().unwrap(); + let (opened, open) = mpsc::channel::<()>(); + let (release, released) = mpsc::channel::<()>(); + opener + .add_submission_handler(Box::new(move |_: &CommandBuffer| { + opened.send(()).unwrap(); + released.recv_timeout(SETTLE).unwrap(); + })) + .unwrap(); + opener.commit().unwrap(); + open.recv_timeout(SETTLE) + .expect("the opener's submission handler ran"); + let empty = first.command_buffer().unwrap(); + let (ran, empty_ran) = mpsc::channel::<()>(); + empty + .add_completed_handler(Box::new(move |_: &CommandBuffer| { + // The receiver is gone where the handler below stopped waiting. + let _ = ran.send(()); + })) + .unwrap(); + empty.commit().unwrap(); + let holding = second.command_buffer().unwrap(); + let (sender, receiver) = mpsc::channel(); + holding + .add_submission_handler(Box::new(move |_: &CommandBuffer| { + sender.send(empty_ran.recv_timeout(SETTLE)).unwrap(); + })) + .unwrap(); + holding.commit().unwrap(); + release.send(()).unwrap(); + let waited = receiver + .recv_timeout(2 * SETTLE) + .expect("the holding command buffer's submission handler ran"); + assert_eq!( + waited, + Ok(()), + "{completion:?}: the empty command buffer's completed handler never reached the other \ + queue's submission handler waiting for it" + ); + for command_buffer in [&opener, &empty, &holding] { + command_buffer.wait_until_completed().unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + } + let after = device.work_counts(); + let unsubmitted = after.command_buffers_unsubmitted - before.command_buffers_unsubmitted; + println!( + "{completion:?}: unsubmitted {unsubmitted}, turns where taken {}", + after.completion_turns_where_taken - before.completion_turns_where_taken + ); + assert_eq!( + unsubmitted, 3, + "{completion:?}: the three empty command buffers were not all taken with no submission" + ); +} + /// A command buffer whose only command signals an event is submitted: the signal is the GPU's, /// in its queue's order. #[test]