From 47174c4775955dfb0ef9af749e2e283d0ecba7b3 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 8 Nov 2026 00:56:51 -0800 Subject: [PATCH] Hold the queue-switch check's round's queues through its gate's signal The queue-switch check (queue_switch_check.rs) submits each round's two batches, each waiting for a gate timeline, then signals the gate from the host. Each submission was a use of its queue of its own, so between the two the queue's lock was free while the first batch waited there for the gate. A wait for a queue to idle under its lock taken in that window never ended: Device::drain_queues (a completion turn's, after a failed wait, and a recovery's) or a submission check's idle after a refused call waited for the first batch, which waited for the gate, which the check signals only after its second submission, which waited for that lock. In a control round (both batches on one VkQueue) that is the whole cycle; in an alternation round the same follows where the other queue's pending work waits for work behind the gated batch. The check runs on each device made with a cache holding no verdict, at its first command queue, so beside the device tests' marked losses, whose devices are not lost and whose queue waits wait for the work: tests::device_recovery::work_that_completed_before_a_failed_wait_ completes hung on the RTX 5080 (more than 960 s), and a_loss_holds_the_hang_s_queue_until_the_recovery hung there 2 of 9 runs, and again for 943 s in a development round. lavapipe has one VkQueue, and MoltenVK four families of one VkQueue each: no two VkQueues of one family, so neither runs it. A round now takes the lock of each of its VkQueues, in index order, before its first submission and lets them go once it signalled the gate (QueueUses::use_queues_kept, new, and its Together, through which each submission is made as QueueUses::use_queue_kept makes it; QueueSlot::with and with_counted now go through a SlotHold, the lock held, which the use of several queues holds for each). No other thread takes one of the round's queues while a batch there waits for the gate, so every submission on a VkQueue whose lock is free completes with no more work of the host's. The module docs of queue_switch_check.rs and Device::drain_queues' doc say so. The device's loader word is still taken inside a queue's lock. Test: tests::device_recovery::a_drain_beside_the_queue_switch_check_s_ round_completes holds the check between the two submissions of a round on one VkQueue (a test-only hold, QueueSwitch::between), starts a drain on another thread, lets the check go 200 ms later and asks the drain to complete within 60 s. It skips a device that runs no check. Verified (potluck jobs and RTX 5080 entries, the change built off development a8239b35cb; rebased here onto 233275b457 with no conflict): - The negative control (scratch commit 64dea87e34: each of the round's submissions its own use again, the test's hold kept), RTX 5080, entry holds-holds-recovery-fix-1-233656: the new test hung 2 of 2 runs; each thread's stack at 30 s shows the drain's thread in vkQueueWaitIdle (Device::drain_queues, under the queue's lock) and the check's thread blocked on that queue's lock in its second submission (queue_switch_check.rs, QueueUses::use_queue_kept). - The change, RTX 5080, the same entry: the new test 60 of 60 runs, four at once (3.3 to 4.5 s each); then the six device_recovery tests, four copies of each at once, nine rounds, 216 runs, no hang (180 s bound per run): a_loss_holds_the_hang_s_queue_until_the_recovery and work_that_completed_before_a_failed_wait_completes 36 of 36 each. 27 of 36 runs of each_recovery_announces_its_own_wait failed with MadeBeforeRecovery, the race development fixed apart (ab8651ae38, not in that build's base). Under 24 processes at once each run took 34 to 67 s. - Apple M3 Max (MoltenVK, the relayed queues' marks through the new SlotHold path), m3-max-7419: the runtime's relay_facts, device_recovery, queue_share, teardown_threads, submit_check, submit_stalls, loader_word and exit_guard tests, 101 of 101; the new test skips there (m3-max-7433: "the device runs no queue-switch check"). - Plain clippy (all targets, all features), m3-max-7382: clean. - Not run before this commit: the change rebased here (its build and clippy run as a job of their own, reported with the tip), and the timing of the program's submissions beside the check's rounds, queued as a timing entry. (cherry picked from commit 254ce9c116f1ced2206dd5c4b63f13e8eabb1c0d) --- crates/metal2vulkan-runtime/src/device/mod.rs | 85 +++++++--- .../metal2vulkan-runtime/src/device/relay.rs | 133 +++++++++++---- .../metal2vulkan-runtime/src/queue_share.rs | 6 + .../src/queue_switch_check.rs | 157 ++++++++++-------- .../src/tests/device_recovery.rs | 38 +++++ 5 files changed, 299 insertions(+), 120 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 315115074..1c24f4c3b 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -1021,12 +1021,7 @@ impl QueueSlot { /// signalling calls are not counted, so its place in its driver's period is forgotten /// (`submit_stalls.rs`). pub(super) fn with(&self, f: impl FnOnce(vk::Queue) -> R) -> R { - let mut held = lock(&self.raw); - held.1.forget(); - self.stall_due.store(false, Ordering::Relaxed); - // SAFETY: the queue lives while its slot does. - unsafe { self.word.restore() }; - f(held.0) + self.hold().with(f) } /// `f` with the queue and its place in its driver's period, under its lock, its loader word @@ -1038,21 +1033,22 @@ impl QueueSlot { caller: submit_stalls::Caller, f: impl FnOnce(vk::Queue, &mut submit_stalls::Period) -> R, ) -> (R, Option) { + self.hold().with_counted(caller, f) + } + + /// The queue's lock, held until the hold drops, the wait for it timed: each use under it is + /// made through the hold ([`SlotHold::with`], [`SlotHold::with_counted`]). A caller that + /// holds several queues at once (`QueueUses::use_queues_kept`) takes their locks in index + /// order. + pub(super) fn hold(&self) -> SlotHold<'_> { let asked = gpu_time::host_nanos(); - let mut held = lock(&self.raw); - let behind = match caller { - submit_stalls::Caller::Work => { - let waited = gpu_time::host_nanos().saturating_sub(asked); - held.1.entered(waited) - } - submit_stalls::Caller::Empty => None, - }; - // SAFETY: the queue lives while its slot does. - unsafe { self.word.restore() }; - let (queue, period) = &mut *held; - let used = f(*queue, period); - self.stall_due.store(period.may_be_due(), Ordering::Relaxed); - (used, behind) + let raw = lock(&self.raw); + let waited = gpu_time::host_nanos().saturating_sub(asked); + SlotHold { + slot: self, + raw, + waited, + } } /// `f` with the queue's place in its driver's period alone, under the queue's lock. @@ -1108,6 +1104,50 @@ impl QueueSlot { } } +/// A hold of a [`QueueSlot`]'s lock ([`QueueSlot::hold`]), let go as it drops. +pub(super) struct SlotHold<'a> { + slot: &'a QueueSlot, + raw: MutexGuard<'a, (vk::Queue, submit_stalls::Period)>, + /// How long the hold waited for the lock, in nanoseconds: the first counted use's wait + /// (`Period::entered`), 0 for the later ones. + waited: u64, +} + +impl SlotHold<'_> { + /// [`QueueSlot::with`], under this hold. + pub(super) fn with(&mut self, f: impl FnOnce(vk::Queue) -> R) -> R { + self.raw.1.forget(); + self.slot.stall_due.store(false, Ordering::Relaxed); + // SAFETY: the queue lives while its slot does. + unsafe { self.slot.word.restore() }; + f(self.raw.0) + } + + /// [`QueueSlot::with_counted`], under this hold. + pub(super) fn with_counted( + &mut self, + caller: submit_stalls::Caller, + f: impl FnOnce(vk::Queue, &mut submit_stalls::Period) -> R, + ) -> (R, Option) { + let behind = match caller { + submit_stalls::Caller::Work => { + let waited = self.waited; + self.waited = 0; + self.raw.1.entered(waited) + } + submit_stalls::Caller::Empty => None, + }; + // SAFETY: the queue lives while its slot does. + unsafe { self.slot.word.restore() }; + let (queue, period) = &mut *self.raw; + let used = f(*queue, period); + self.slot + .stall_due + .store(period.may_be_due(), Ordering::Relaxed); + (used, behind) + } +} + #[cfg(debug_assertions)] thread_local! { /// The locks this thread took of what its draws share with draws on other threads (builds @@ -1330,7 +1370,10 @@ impl Device { /// `vkQueueWaitIdle` commits an empty Metal command buffer to the queue and waits for it, /// lost or not, and Metal completes a queue's command buffers in order, so the earlier /// ones' handlers have run when it returns. Another driver's returns at once on a lost - /// device, and waits for the work on a device that is not. + /// device, and waits for the work on a device that is not: work that completes with no more + /// work of the host's, since none of the runtime's waits on a queue whose lock is free for a + /// signal the host has yet to make (the queue-switch check holds its round's queues until it + /// signalled the round's gate, `queue_switch_check.rs`). pub(super) fn drain_queues(&self) { let Some(_busy) = exit_guard::enter() else { return; diff --git a/crates/metal2vulkan-runtime/src/device/relay.rs b/crates/metal2vulkan-runtime/src/device/relay.rs index 0dd17cbdd..f15ddbf3a 100644 --- a/crates/metal2vulkan-runtime/src/device/relay.rs +++ b/crates/metal2vulkan-runtime/src/device/relay.rs @@ -49,8 +49,8 @@ //! the device is lost), and a device whose instance lacks `VK_EXT_debug_utils` (the same). use super::functions::Functions; -use super::lock; use super::submit_stalls::{Caller, Uses}; +use super::{lock, SlotHold}; use crate::exit_guard::{self, Call}; use crate::loader_word::LoaderWord; use ash::vk::{self, Handle}; @@ -567,33 +567,44 @@ impl<'a> QueueUses<'a> { keep: bool, f: impl FnOnce(vk::Queue) -> R, ) -> (R, Option>) { - let queues: &'a [super::QueueSlot] = self.queues; - let slot = &queues[queue]; - let flights = slot.flights.get(); - let parking = self.parking.filter(|_| matches!(by, By::Program)); - let checks = matches!(by, By::Checks); - if flights.is_none() && parking.is_none() { - let used = match uses { - Uses::Unknown => slot.with(f), - Uses::OneSignalling => { - let (used, behind) = slot.with_counted(Caller::Work, |vk_queue, period| { - let entered = crate::gpu_time::host_nanos(); - let used = f(vk_queue); - let end = crate::gpu_time::host_nanos(); - if period.called(Caller::Work, end.saturating_sub(entered), end) { - self.counts.submit_stall_on_work(); - } - used - }); - if let Some(waited) = behind { - self.counts.submit_behind_idle_stall(waited); - } - used - } - }; - return (used, None); - } - let fence = flights.and_then(|flights| { + let fence = self.mark_fence(queue); + let mut hold = self.queues[queue].hold(); + self.use_held(&mut hold, (queue, by), (uses, keep), fence, f) + } + + /// [`use_queue_kept`](Self::use_queue_kept) for each use `f` makes through the [`Together`] + /// it is given, each `by`'s, with each of `queues` (each once, in index order) under its lock + /// from before `f` begins until after it returns: no other use of those queues comes between + /// two of `f`'s, nor between its last and what it does after it. The queue-switch check + /// submits each round so, its batches waiting for a gate it then signals from the host + /// (`queue_switch_check.rs`). + pub(crate) fn use_queues_kept( + &self, + queues: &[usize], + by: By, + f: impl FnOnce(&mut Together<'_, 'a>) -> T, + ) -> T { + debug_assert!( + queues.windows(2).all(|pair| pair[0] < pair[1]), + "the queues are held each once, in index order" + ); + let queue_slots: &'a [super::QueueSlot] = self.queues; + let holds = (queues.iter()) + .map(|&queue| (queue, queue_slots[queue].hold())) + .collect(); + f(&mut Together { + uses: self, + by, + holds, + }) + } + + /// The fence of the relay's mark after a use of `queue`, where its failures are relayed + /// (none elsewhere, or once the process is exiting), taken before the use takes the queue's + /// lock: the marks before it whose fences are signaled go back first. + fn mark_fence(&self, queue: usize) -> Option { + let flights = self.queues[queue].flights.get(); + flights.and_then(|flights| { exit_guard::enter().and_then(|_busy| { let raw = self.functions.get(); let mut done = flights.done_marks(); @@ -613,8 +624,46 @@ impl<'a> QueueUses<'a> { // SAFETY: the device's fences, inside a section. unsafe { self.fences.take(raw) }.ok() }) - }); - slot.with(|vk_queue| { + }) + } + + /// [`use_queue_kept`](Self::use_queue_kept) of `queue`, `by`'s, under `hold`, the queue's + /// lock, `fence` the relay's mark's ([`mark_fence`](Self::mark_fence)). + fn use_held( + &self, + hold: &mut SlotHold<'_>, + (queue, by): (usize, By), + (uses, keep): (Uses, bool), + fence: Option, + f: impl FnOnce(vk::Queue) -> R, + ) -> (R, Option>) { + let queues: &'a [super::QueueSlot] = self.queues; + let slot = &queues[queue]; + let flights = slot.flights.get(); + let parking = self.parking.filter(|_| matches!(by, By::Program)); + let checks = matches!(by, By::Checks); + if flights.is_none() && parking.is_none() { + let used = match uses { + Uses::Unknown => hold.with(f), + Uses::OneSignalling => { + let (used, behind) = hold.with_counted(Caller::Work, |vk_queue, period| { + let entered = crate::gpu_time::host_nanos(); + let used = f(vk_queue); + let end = crate::gpu_time::host_nanos(); + if period.called(Caller::Work, end.saturating_sub(entered), end) { + self.counts.submit_stall_on_work(); + } + used + }); + if let Some(waited) = behind { + self.counts.submit_behind_idle_stall(waited); + } + used + } + }; + return (used, None); + } + hold.with(|vk_queue| { // Taken before `f` submits: a block that goes meanwhile waits for the mark. let mark = parking.and_then(|parking| { let _busy = exit_guard::enter()?; @@ -682,6 +731,30 @@ impl<'a> QueueUses<'a> { } } +/// The queues a use of several holds, each under its lock ([`QueueUses::use_queues_kept`]). +pub(crate) struct Together<'u, 'a> { + uses: &'u QueueUses<'a>, + by: By, + holds: Vec<(usize, SlotHold<'a>)>, +} + +impl<'a> Together<'_, 'a> { + /// [`QueueUses::use_queue_kept`] of `queue`, one of the queues held, under its hold. + pub(crate) fn use_queue_kept( + &mut self, + queue: usize, + uses: Uses, + keep: bool, + f: impl FnOnce(vk::Queue) -> R, + ) -> (R, Option>) { + let fence = self.uses.mark_fence(queue); + let (_, hold) = (self.holds.iter_mut()) + .find(|(held, _)| *held == queue) + .expect("a use of a queue the use of several holds"); + (self.uses).use_held(hold, (queue, self.by.clone()), (uses, keep), fence, f) + } +} + /// The relay's mark after a use of a queue, kept for the use's caller /// ([`QueueUses::use_queue_kept`]): while it lives, no other use takes it from the log or resets /// its fence, so the caller may wait for it. Let go as it drops, for the next use to take. diff --git a/crates/metal2vulkan-runtime/src/queue_share.rs b/crates/metal2vulkan-runtime/src/queue_share.rs index bf847a8c0..f4a7ab634 100644 --- a/crates/metal2vulkan-runtime/src/queue_share.rs +++ b/crates/metal2vulkan-runtime/src/queue_share.rs @@ -370,6 +370,10 @@ pub(crate) struct QueueSwitch { /// (`tests/teardown_threads.rs`). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) held: crate::freed_memory::held::Held, + /// The crate's device tests' hold of the check between the two submissions of a round on one + /// `VkQueue`, its queue's lock held (`tests/device_recovery.rs`). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) between: crate::freed_memory::held::Held, /// The crate's device tests' timings of the check's last two steps, in nanoseconds: the /// release of its Vulkan objects, and the drop of its shares of the device's parts. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -399,6 +403,8 @@ impl QueueSwitch { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] held: Default::default(), #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + between: Default::default(), + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] last_steps: Default::default(), #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] fences_waited: AtomicU64::new(0), diff --git a/crates/metal2vulkan-runtime/src/queue_switch_check.rs b/crates/metal2vulkan-runtime/src/queue_switch_check.rs index d6f5e3be4..806560299 100644 --- a/crates/metal2vulkan-runtime/src/queue_switch_check.rs +++ b/crates/metal2vulkan-runtime/src/queue_switch_check.rs @@ -41,6 +41,15 @@ //! wait of at most [`WAIT_SLICE`], and the releases. Once the process is exiting it ends, //! unrecorded, and leaves its objects to the process's end. A submission refused still opens its //! round's gate, so no batch submitted waits for good. +//! - **Its queues held to the gate.** A round takes the lock of each of its `VkQueue`s, in index +//! order, before its first submission, and lets them go once it signalled the gate +//! (`QueueUses::use_queues_kept`): no other thread takes one of them while a batch there waits +//! for the gate, so every submission on a `VkQueue` whose lock is free completes with no more +//! work of the host's. A wait for a queue to idle under its lock (`Device::drain_queues`, after +//! a failed wait; a submission check's after a refused call) then waits for work that completes. +//! Were a round's queue let go between its submissions, such a wait taken meanwhile would wait +//! under that lock for the round's first batch, which waits for the gate, which the check +//! signals only after its next submission, which waits for that lock. //! - **Holding nothing of the device.** The check holds only the parts of the device it works //! with ([`Parts`]), never a handle: a check that held one for its run would hold the device's //! last once the program dropped its own while the check ran (the first moments of a device @@ -488,8 +497,8 @@ impl Objects { // completes, after the timelines are signalled. It signals each fence as the batch's // Metal command buffer completes, as the submission checks' own fences end their steps; // where the queue's failures are not relayed (an adopted device, whose instance has no - // relay), no mark follows them. Taken with no queue's lock held: each batch's submission - // takes its queue's lock and then the word, and lets both go. + // relay), no mark follows them. Taken inside the round's queues' locks, as each batch's + // submission takes the word inside its queue's, and kept once they go. let hold = parts.overwritten(); let (submitted, refused, step, marks) = match self.submit(parts, batches, gate, hold) { Some(answer) => answer, @@ -517,10 +526,12 @@ impl Objects { } /// Submit `batches`, each alone on its `VkQueue`, in order until one is refused, then signal - /// the gate to `gate` from the host, inside one section: how many were submitted, the - /// refusal, the hold of the device's loader word the signal was made under where the round is - /// held (`hold`, each batch then signalling its fence of the check's own), and the relay's - /// marks after the batches, kept; `None` where the process is exiting. + /// the gate to `gate` from the host, inside one section, with each of the round's `VkQueue`s + /// under its lock from before the first submission until after the signal (the module docs): + /// how many were submitted, the refusal, the hold of the device's loader word the signal was + /// made under where the round is held (`hold`, each batch then signalling its fence of the + /// check's own), and the relay's marks after the batches, kept; `None` where the process is + /// exiting. fn submit<'p>( &self, parts: &'p Parts, @@ -531,70 +542,78 @@ impl Objects { let _busy = exit_guard::enter()?; let raw = parts.vk(); let uses = parts.queue_uses(); - let mut submitted = 0; - let mut refused = None; - let mut marks = Vec::new(); - for (batch, &own) in batches.iter().zip(&self.fences) { - let fence = match hold { - true => own, - false => vk::Fence::null(), - }; - let buffers = [batch.buffer]; - let waits = [batch.wait.0]; - let wait_values = [batch.wait.1]; - let stages = [vk::PipelineStageFlags::ALL_COMMANDS]; - let signals = [batch.signal.0]; - let signal_values = [batch.signal.1]; - let mut values = vk::TimelineSemaphoreSubmitInfo::default() - .wait_semaphore_values(&wait_values) - .signal_semaphore_values(&signal_values); - let submit = vk::SubmitInfo::default() - .wait_semaphores(&waits) - .wait_dst_stage_mask(&stages) - .command_buffers(&buffers) - .signal_semaphores(&signals) - .push_next(&mut values); - // SAFETY: the queue is used under its lock, inside a section; the command buffer is - // recorded, ended and in no other submission; each timeline's signals rise in the order - // they run (each lane's batches run in its queue's order); the gate's wait is signalled - // below; the fence, where there is one, is unsignaled (made so, or reset once the round - // before signalled it) and in no pending submission. The device's loader word is held - // across the call and the relay's mark after it (MoltenVK names the device as it logs - // each, `loader_word.rs`), taken inside the queue's lock. None of the round's batches - // runs before the gate's signal, which the caller makes under the word where it was - // found overwritten, so none completes while the word is let go between them, nor does - // the mark after it, which is kept, for the round to wait for. - let ((held, made), mark) = uses.use_queue_kept( - batch.queue, - By::Runtime, - Uses::OneSignalling, - true, - |queue| unsafe { - let held = parts.loader_word.held(); - parts.counts.queue_submitted(1, 1); - (held, raw.queue_submit(queue, &[submit], fence)) - }, - ); - drop(held); - marks.extend(mark); - exit_guard::called(Call::QueueSubmit); - if let Err(error) = made { - refused = Some(error); - break; + let mut queues: Vec = batches.iter().map(|batch| batch.queue).collect(); + queues.sort_unstable(); + queues.dedup(); + let submitted = uses.use_queues_kept(&queues, By::Runtime, |held| { + let mut submitted = 0; + let mut refused = None; + let mut marks = Vec::new(); + for (batch, &own) in batches.iter().zip(&self.fences) { + // The crate's device tests' hold of a round on one `VkQueue` between its two + // submissions (`tests::device_recovery`). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + if !std::ptr::eq(batch, &batches[0]) && batch.queue == batches[0].queue { + parts.switch.between.pass(); + } + let fence = match hold { + true => own, + false => vk::Fence::null(), + }; + let buffers = [batch.buffer]; + let waits = [batch.wait.0]; + let wait_values = [batch.wait.1]; + let stages = [vk::PipelineStageFlags::ALL_COMMANDS]; + let signals = [batch.signal.0]; + let signal_values = [batch.signal.1]; + let mut values = vk::TimelineSemaphoreSubmitInfo::default() + .wait_semaphore_values(&wait_values) + .signal_semaphore_values(&signal_values); + let submit = vk::SubmitInfo::default() + .wait_semaphores(&waits) + .wait_dst_stage_mask(&stages) + .command_buffers(&buffers) + .signal_semaphores(&signals) + .push_next(&mut values); + // SAFETY: the queue is used under its lock, inside a section; the command buffer + // is recorded, ended and in no other submission; each timeline's signals rise in + // the order they run (each lane's batches run in its queue's order); the gate's + // wait is signalled below, before the queue's lock goes; the fence, where there + // is one, is unsignaled (made so, or reset once the round before signalled it) and + // in no pending submission. The device's loader word is held across the call and + // the relay's mark after it (MoltenVK names the device as it logs each, + // `loader_word.rs`), taken inside the queue's lock. None of the round's batches + // runs before the gate's signal, which is made under the word where it was found + // overwritten, so none completes while the word is let go between them, nor does + // the mark after it, which is kept, for the round to wait for. + let ((word, made), mark) = + held.use_queue_kept(batch.queue, Uses::OneSignalling, true, |queue| unsafe { + let word = parts.loader_word.held(); + parts.counts.queue_submitted(1, 1); + (word, raw.queue_submit(queue, &[submit], fence)) + }); + drop(word); + marks.extend(mark); + exit_guard::called(Call::QueueSubmit); + if let Err(error) = made { + refused = Some(error); + break; + } + submitted += 1; } - submitted += 1; - } - let signal = vk::SemaphoreSignalInfo::default() - .semaphore(self.gate) - .value(gate); - let step = match hold { - true => parts.step_held(), - false => None, - }; - // SAFETY: the gate's value rises with each signal, its only signaller the host. - let signalled = unsafe { raw.signal_semaphore(&signal) }; - exit_guard::called(Call::SignalSemaphore); - Some((submitted, refused.or(signalled.err()), step, marks)) + let signal = vk::SemaphoreSignalInfo::default() + .semaphore(self.gate) + .value(gate); + let step = match hold { + true => parts.step_held(), + false => None, + }; + // SAFETY: the gate's value rises with each signal, its only signaller the host. + let signalled = unsafe { raw.signal_semaphore(&signal) }; + exit_guard::called(Call::SignalSemaphore); + (submitted, refused.or(signalled.err()), step, marks) + }); + Some(submitted) } /// Wait for each `VkQueue`'s timeline to reach its value of `done`, a slice at a time, each a diff --git a/crates/metal2vulkan-runtime/src/tests/device_recovery.rs b/crates/metal2vulkan-runtime/src/tests/device_recovery.rs index 2e81185b1..e00986ded 100644 --- a/crates/metal2vulkan-runtime/src/tests/device_recovery.rs +++ b/crates/metal2vulkan-runtime/src/tests/device_recovery.rs @@ -274,6 +274,44 @@ fn work_that_completed_before_a_failed_wait_completes() { assert_eq!(device.work_counts().device_recoveries, 1); } +/// A failed wait's drain of the device's queues (`Device::drain_queues`), taken while the +/// device's queue-switch check is between the two submissions of a round on one `VkQueue` +/// (`queue_switch_check.rs`), completes once the round goes on: the round holds its queue's lock +/// until it signalled its gate, so the drain never waits under that lock for the round's first +/// batch, held at the gate, while the check waits for that lock to make its second submission. +#[test] +fn a_drain_beside_the_queue_switch_check_s_round_completes() { + let scratch = Scratch::new(); + let device = device(&scratch.0); + let switch = Arc::clone(&device.shared().queue_switch); + if switch.verdict() != crate::queue_share::Verdict::Pending { + println!( + "SKIPPED {}: the device runs no queue-switch check", + device.name() + ); + return; + } + switch.between.hold(); + // The device's first command queue starts its check. + let queue = device.new_command_queue().unwrap(); + switch.between.until_waiting(1, WAIT); + let (drained, drain) = std::sync::mpsc::channel(); + let draining = device.clone(); + std::thread::spawn(move || { + draining.drain_queues(); + let _ = drained.send(()); + }); + // The drain reaches the round's `VkQueue` meanwhile. + std::thread::sleep(Duration::from_millis(200)); + switch.between.release(); + let answer = drain.recv_timeout(WAIT); + drop(queue); + assert!( + answer.is_ok(), + "the drain did not complete in {WAIT:?} once the check's round went on" + ); +} + /// The threads that call the device while it recovers ([`each_recovery_announces_its_own_wait`]). const WAITERS: usize = 3;