From 0a35c20f4b5dc21b4945ca4e5be230304d4f9633 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 21 Nov 2026 09:46:47 -0800 Subject: [PATCH] Runtime: a command buffer that signals an event waits for room too, in any segment A segment that signals an event sends its group at once, so a command buffer that signals went to the VkQueue whenever no group was held, or when the group held would take it: a queue whose every command buffer signals kept all of it on the VkQueue, and another queue's later work could not pass it. The lavapipe run of the harness's two-queue row showed it: with each of A's command buffers signalling, 0 held for room (job m3-max-64136). Now a head that signals in any segment waits unstaged for room (WorkState::waits_for_room): with no group held, until its queue has room for it; behind a group held, though the group would take it. Its signal is staged only then, and as a waiter takes a staged signal as submitted, a wait for it waits with it: no waiter is submitted ahead of its signal. Covered: work then a signal at the tail (one segment), a wait at the head (no split: command.rs Building::wait splits only a segment with commands or signals), and a signal after a wait that follows work (a later segment). A partly staged command buffer's later signal still goes at once: one command buffer at most. The fence's held-updater scan no longer needs the other queue to hold a group, and the completion wake stays on while a queue's head is held for room. Tests: A's every command buffer signals at its tail (work, then the signal), or after a wait that follows its work; B1 runs after A1 and A2 as behind unsignalled work, A3 to A5 held for room. The two_queues helper takes whether A holds a group and how many it holds for room. --- crates/metal2vulkan-runtime/README.md | 7 ++- crates/metal2vulkan-runtime/src/submit.rs | 62 +++++++++++++------ .../metal2vulkan-runtime/src/tests/command.rs | 61 +++++++++++++++--- .../metal2vulkan-runtime/src/tests/fence.rs | 2 +- 4 files changed, 101 insertions(+), 31 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index f8e0b93e4..bba5c55cc 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -1713,9 +1713,10 @@ made, with no lock, and never rewritten for layouts. is to wait for one of them (`wait_until_completed`, or `CommandQueue::send_now`, the hint for a wait the runtime does not see), or at teardown. Waiting for a place in the queue sends nothing. A segment that signals an event ends its group, which goes - at once as it is staged, and so does a presenting command buffer's last (see "Presenting"); one - held for room is staged once there is room, so a signal of its waits with it, while a presenting - one has its queue go at once, through to it. The + at once as it is staged, and so does a presenting command buffer's last (see "Presenting"); so a + command buffer that signals an event, in any segment, is staged only once its queue has room for + it, as one held for room behind it is, and a wait for its signal waits with it, while a + presenting one has its queue go at once, through to it. The driver runs a submission's command buffers as one kernel job, which a job timeout ends as a whole (Linux's amdgpu ends a job past its timeout and resets the ring), so a group is bounded by its expected GPU run: a queue's expected run follows its command buffers' diff --git a/crates/metal2vulkan-runtime/src/submit.rs b/crates/metal2vulkan-runtime/src/submit.rs index 8c61a6ddf..bda2a0d91 100644 --- a/crates/metal2vulkan-runtime/src/submit.rs +++ b/crates/metal2vulkan-runtime/src/submit.rs @@ -24,7 +24,9 @@ //! `vkQueueSubmit2` each, only the last signalling. At most [`UNSEEN_JOINS`] command buffers join //! a group while none of the queue's retires, so command buffers that turn long all at once join //! no more than that many on the estimate of the short ones before them. A segment that -//! signals an event ends its group, which goes at once; one that waits on a semaphore leads a new +//! signals an event ends its group, which goes at once, so a command buffer that signals waits +//! unstaged until its queue has room for it ([`WorkState::waits_for_room`]): a signal staged is +//! one its waiters take as submitted. One that waits on a semaphore leads a new //! group, the one held going first. A group is one submission with one signal of the progress //! semaphore, which the completion thread follows in commit order. A command buffer that takes no //! submission of its own (one with nothing for the GPU that no copy-in waits for, or one ended @@ -191,7 +193,8 @@ pub(crate) struct Work { /// lost: a staging call asleep for it looks again ([`Work::stage`]). Signalled only while one /// sleeps ([`WorkState::span_sleepers`]). spans: Condvar, - /// A queue holds a group: the completion thread wakes the thread as submissions complete. + /// A queue holds a group, or a command buffer for room: the completion thread wakes the + /// thread as submissions complete. keeping: AtomicBool, /// Bytes of textures and blocks released while an upload held them, since the last /// submission that left no upload unsent: they count against [`UPLOAD_BYTES`]. A texture's @@ -594,7 +597,8 @@ impl Work { self.wake(); } - /// Submissions completed: where a queue holds a group, it may go. + /// Submissions completed: where a queue holds a group or a command buffer for room, it may + /// go. pub(crate) fn completed(&self) { if self.keeping.load(Ordering::SeqCst) { self.poke(); @@ -1520,21 +1524,35 @@ impl WorkState { /// Whether the head of `fifo` waits in its list, not staged, for room: committed, with /// commands or a copy-in for the GPU, its first segment not yet staged, behind a group held - /// that neither takes it ([`Batch::takes`]), nor conflicts with it, nor goes - /// ([`Fifo::goes`]). The command buffers behind it wait with it. + /// that does not go ([`Fifo::goes`]) nor conflict with it, and that does not take it + /// ([`Batch::takes`]) or would go at its signal. With no group held, one that signals an event + /// in any segment, which would send its group at once, waits where its queue has no room for + /// it. The command buffers behind it wait with it. fn waits_for_room(&self, fifo: &Fifo, busy: bool) -> bool { - let (Some(head), Some(group)) = (fifo.entries.front(), &fifo.group) else { + let Some(head) = fifo.entries.front() else { return false; }; let (Some(pending), None) = (&head.pending, head.error) else { return false; }; let empty = pending.gpu.is_empty() && !self.changes.captured.waits_for(pending.seq); - pending.next == 0 - && !empty - && !group.leans.conflicts(&pending.gpu.segments[0].overs) - && !group.takes(fifo.queue.expected_run(), fifo.queue.retired()) - && !fifo.goes(self.stop, busy) + if pending.next != 0 || empty { + return false; + } + let segments = &pending.gpu.segments; + let signals = (segments.iter()).any(|segment| !segment.signals.is_empty()); + let (segment, run) = (&segments[0], fifo.queue.expected_run()); + match &fifo.group { + Some(group) => { + !group.leans.conflicts(&segment.overs) + && (signals || !group.takes(run, fifo.queue.retired())) + && !fifo.goes(self.stop, busy) + } + None => { + let room = room(&fifo.in_flight, run.unwrap_or(u64::MAX)); + signals && !(self.stop || busy || fifo.send_through >= head.place || room) + } + } } /// The first command buffer not yet scheduled of the FIFO at `index`, whose head waits for @@ -1578,16 +1596,18 @@ impl WorkState { } let before = head.held.unwrap_or(u64::MAX); let updates = |pending: &Pending| pending.gpu.fences.updates_for(waiter); - (self.fifos.iter().enumerate()).find_map(|(other, fifo)| { - let group = fifo.group.as_ref().filter(|_| other != index)?; + let mut others = (self.fifos.iter().enumerate()).filter(|&(other, _)| other != index); + others.find_map(|(other, fifo)| { let held = (fifo.entries.iter()) .map_while(|entry| entry.held.filter(|&at| at < before).map(|_| entry)) .filter(|entry| entry.pending.as_ref().is_some_and(updates)) .last() .map(|entry| entry.place); - let grouped = (group.finished.iter()).any(|(_, pending, _)| updates(pending)) - || (group.partial && fifo.head().is_some_and(updates)); - held.or(grouped.then_some(group.first)) + let grouped = (fifo.group.as_ref()).filter(|group| { + (group.finished.iter()).any(|(_, pending, _)| updates(pending)) + || (group.partial && fifo.head().is_some_and(updates)) + }); + held.or(grouped.map(|group| group.first)) .map(|place| (other, place)) }) } @@ -1755,7 +1775,8 @@ impl WorkState { { counters.event_hold(now.saturating_sub(since)); } - // An event's signal goes at once: nothing waits on it behind a held group. So does a + // An event's signal goes at once, staged only with room: nothing waits on it behind a held + // group, as a waiter takes a signal staged as submitted. So does a // presenting command buffer's signal of the consumer's semaphore, which its present waits on // once the command buffer is scheduled. let signals = !staged.signals.is_empty(); @@ -2114,7 +2135,12 @@ fn pass<'a>(core: &'a Core, mut state: MutexGuard<'a, WorkState>) -> MutexGuard< state = work.lock(); } } - if state.fifos.iter().all(|fifo| fifo.group.is_none()) { + let holds = |fifo: &Fifo| { + fifo.entries + .front() + .is_some_and(|entry| entry.held.is_some()) + }; + if (state.fifos.iter()).all(|fifo| fifo.group.is_none() && !holds(fifo)) { work.keeping.store(false, Ordering::SeqCst); } if !joined.is_empty() || !ended.is_empty() { diff --git a/crates/metal2vulkan-runtime/src/tests/command.rs b/crates/metal2vulkan-runtime/src/tests/command.rs index aa81b4057..a1d66d511 100644 --- a/crates/metal2vulkan-runtime/src/tests/command.rs +++ b/crates/metal2vulkan-runtime/src/tests/command.rs @@ -1835,13 +1835,15 @@ pub(crate) mod on_device { /// the cursor with its number, 1 to 5 for A's and 6 for B's, so the log names the command /// buffer that ran just before each (0 for none). `encode(number, command_buffer, after)` /// encodes before (`after` false) and after that copy and fill. A's held work is checked - /// before `body` runs and B commits: A1 and A2 submitted, A3 in a group held, A4 and A5 held - /// for room, not yet in a group, each scheduled with its scheduled handler run - /// (`Metrics::held_for_room`). B's is staged, or held for an event's value, before the gate - /// opens. Returns the log of A1 to B1 once each completed. + /// before `body` runs and B commits: A1 and A2 submitted, the rest each scheduled with its + /// scheduled handler run, `held` saying whether A holds a group and how many A holds for room, + /// not yet in a group (`Metrics::held_for_room`): A3 in a group and A4 and A5 for room, or, + /// where A3 signals an event, A3 to A5 for room. B's is staged, or held for an event's value, + /// before the gate opens. Returns the log of A1 to B1 once each completed. pub(crate) fn two_queues( name: &str, device: &Device, + held: (bool, u64), encode: impl Fn(u32, &CommandBuffer, bool), body: impl FnOnce(&CommandQueue, &[CommandBuffer]), ) -> Vec { @@ -1875,17 +1877,18 @@ pub(crate) mod on_device { command_buffer.commit().expect("a commit"); command_buffer }; + let (group, held_for_room) = held; let held = device.counters().metrics().held_for_room; let a_work: Vec = (1..=5).map(|number| logged(&a, number)).collect(); within(name, || scheduled.load(Ordering::SeqCst) == 5); let statuses: Vec<_> = a_work.iter().map(CommandBuffer::status).collect(); assert_eq!( (statuses, device.core().work.in_flight(a_work[0].queue())), - (vec![CommandBufferStatus::Scheduled; 5], (2, true)), + (vec![CommandBufferStatus::Scheduled; 5], (2, group)), "{name}: A's held work, each scheduled" ); let counted = device.counters().metrics().held_for_room - held; - assert_eq!(counted, 2, "{name}: A4 and A5 held for room"); + assert_eq!(counted, held_for_room, "{name}: A's held for room"); body(&a, &a_work); let b_work = logged(&b, 6); within(name, || { @@ -1907,7 +1910,7 @@ pub(crate) mod on_device { #[test] fn every_device_runs_a_queues_command_buffer_ahead_of_another_queues_backlog() { each_device("command_two_queues", |name, _, device| { - let log = two_queues(name, &device, |_, _, _| {}, |_, _| {}); + let log = two_queues(name, &device, (true, 2), |_, _, _| {}, |_, _| {}); assert_eq!(log, [0, 1, 6, 3, 4, 2], "{name}: the one run before each"); }); } @@ -1922,7 +1925,7 @@ pub(crate) mod on_device { let work = &device.core().work; within(name, || work.in_flight(a_work[0].queue()) == (4, true)); }; - let log = two_queues(name, &device, |_, _, _| {}, body); + let log = two_queues(name, &device, (true, 2), |_, _, _| {}, body); assert_eq!(log, [0, 1, 2, 3, 6, 4], "{name}: the one run before each"); }); } @@ -1946,11 +1949,51 @@ pub(crate) mod on_device { } .expect("an event's signal or wait") }; - let log = two_queues(name, &device, encode, |_, _| {}); + let log = two_queues(name, &device, (true, 2), encode, |_, _| {}); assert_eq!(log, [0, 1, 2, 3, 4, 5], "{name}: the one run before each"); }); } + /// A queue whose every command buffer signals an event keeps on the `VkQueue` only what it + /// has room for too: A1 to A5 each signal a shared event's value, their number, and A3 to A5, + /// whose signals would each send a group at once, wait for room unstaged, so B1 runs after A1 + /// and A2 as it does behind work that signals nothing. + #[test] + fn every_device_runs_a_queues_command_buffer_ahead_of_another_queues_signals() { + each_device("command_two_queues_signals", |name, _, device| { + let event = shared_event(&device); + let encode = |number: u32, command_buffer: &CommandBuffer, after: bool| { + if number <= 5 && after { + let signal = + command_buffer.encode_signal_event(event.as_event(), number.into()); + signal.expect("an event's signal"); + } + }; + let log = two_queues(name, &device, (false, 3), encode, |_, _| {}); + assert_eq!(log, [0, 1, 6, 3, 4, 2], "{name}: the one run before each"); + }); + } + + /// So does one whose signal is in a later segment: each of A1 to A5 waits after its work for + /// a value another event already holds, which ends its first segment (`encodeWaitForEvent` + /// splits a segment with commands), then signals; A3 to A5 wait for room whole. + #[test] + fn every_device_holds_for_room_a_command_buffer_whose_signal_follows_a_wait() { + each_device("command_two_queues_split_signals", |name, _, device| { + let (gate, event) = (shared_event(&device), shared_event(&device)); + let encode = |number: u32, command_buffer: &CommandBuffer, after: bool| { + if number <= 5 && after { + (command_buffer.encode_wait_for_event(gate.as_event(), 0)).expect("a wait"); + let signal = + command_buffer.encode_signal_event(event.as_event(), number.into()); + signal.expect("an event's signal"); + } + }; + let log = two_queues(name, &device, (false, 3), encode, |_, _| {}); + assert_eq!(log, [0, 1, 6, 3, 4, 2], "{name}: the one run before each"); + }); + } + /// A commit's wait for the submission lock is counted: one made while another thread holds /// the lock counts at least the time from the start of its count to the lock's release, here /// 20 ms or more. No clock of the test's bounds it from above. diff --git a/crates/metal2vulkan-runtime/src/tests/fence.rs b/crates/metal2vulkan-runtime/src/tests/fence.rs index 16cea98a2..8169f252c 100644 --- a/crates/metal2vulkan-runtime/src/tests/fence.rs +++ b/crates/metal2vulkan-runtime/src/tests/fence.rs @@ -334,7 +334,7 @@ mod on_device { blit.end_encoding(); } }; - let log = two_queues(name, &device, encode, |_, _| {}); + let log = two_queues(name, &device, (true, 2), encode, |_, _| {}); assert_eq!(log, [0, 1, 2, 3, 6, 4], "{name}: the one run before each"); }); }