From a0d2d2efddcddcb166e6bdd7d2bc0618d6e9ae40 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 2 Dec 2026 23:15:09 -0800 Subject: [PATCH] rt: a failed wake of the completion thread is owed to the next wake, and a failed host wait is made again vkSignalSemaphore fails only for want of memory or with VK_ERROR_UNKNOWN, never with a loss. The wake ignored the failure and marked the thread woken, under a comment that said a failure is a loss. The thread stayed in its GPU wait with nothing to end it, and every later flight-only wake returned early, because the thread already waited for the progress semaphore. With work in flight, a listener or an end then waited for the front batch to complete. That is a deadlock where that batch waits on a host signal the listener would give. The form (the planner's ruling, which withdrew its "next wait is bounded" form, a record the wait in progress cannot read): - A failed signal leaves the wake owed. The thread stays marked waiting on the GPU, and the next wake from any thread signals again at a higher value, flight-only wakes included. The thread clears the debt as it next reads the state. - There is no polling: tests/event_values.rs's thread-does-not-spin assertion holds as before. - The limit, stated in the code: a failed wake that no later wake follows waits for the wait's other semaphores. vkWaitSemaphores (the dma-bufs import's bind wait before vkDestroyBuffer) and vkDeviceWaitIdle ignored every failure under a comment that named loss alone. Both now go through complete::wait_through: - success, a loss the call reports, or a loss the runtime has seen ends the wait; - an out-of-memory or unknown result, which says nothing of what is pending, is called again 100 ms (LOSS_POLL) later. So a lasting out-of-memory result on a live device waits, and no buffer whose bind may still be pending is destroyed. On a lost device, vkDeviceWaitIdle returns success or VK_ERROR_DEVICE_LOST in finite time (Lost Device), so a teardown does not spin on a dead device. The two tests of the previous commit, failed_waits.rs, turn green here through the same seams (fail_wakes, fail_waits). --- crates/metal2vulkan-runtime/src/complete.rs | 56 +++++++++++++++++++-- crates/metal2vulkan-runtime/src/device.rs | 31 ++++++------ crates/metal2vulkan-runtime/src/import.rs | 15 ++++-- crates/metal2vulkan-runtime/src/memory.rs | 2 +- 4 files changed, 77 insertions(+), 27 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/complete.rs b/crates/metal2vulkan-runtime/src/complete.rs index 36f9c16c9..3741bd63b 100644 --- a/crates/metal2vulkan-runtime/src/complete.rs +++ b/crates/metal2vulkan-runtime/src/complete.rs @@ -40,9 +40,37 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; use std::time::{Duration, Instant}; -/// How long [`Done::wait`] waits on the GPU at a time before it checks for a loss. +/// How long [`Done::wait`] waits on the GPU at a time before it checks for a loss, and how long +/// [`wait_through`] pauses after a failed call before it calls again. const LOSS_POLL: Duration = Duration::from_millis(100); +/// Calls `wait`, a host wait on what the GPU has pending, again until it succeeds or the device +/// is lost: a loss it reports, or one the runtime has seen, leaves nothing pending (Lost Device: +/// "a return value of VK_ERROR_DEVICE_LOST is equivalent to VK_SUCCESS"), while a failure for want +/// of memory, or `VK_ERROR_UNKNOWN`, says nothing of what is pending, so the next call comes +/// [`LOSS_POLL`] later. A failure that lasts on a live device waits as long as it lasts. +pub(crate) fn wait_through(core: &Core, mut wait: impl FnMut() -> Result<(), vk::Result>) { + loop { + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + let failed = (core.fail_waits) + .try_update(Ordering::Relaxed, Ordering::Relaxed, |left| { + left.checked_sub(1) + }) + .is_ok(); + #[cfg(not(all(test, any(m2v_gpu, m2v_cpu_icd))))] + let failed = false; + let result = match failed { + true => Err(vk::Result::ERROR_OUT_OF_HOST_MEMORY), + false => wait(), + }; + match result { + Ok(()) | Err(vk::Result::ERROR_DEVICE_LOST) => return, + Err(_) if core.work.lock().lost() => return, + Err(_) => std::thread::sleep(LOSS_POLL), + } + } +} + /// The completion side: what the completion thread has to do, and its two timeline semaphores. pub(crate) struct Done { state: Mutex, @@ -73,6 +101,9 @@ struct DoneState { waiting: Waiting, /// The wake semaphore's last value. woken: u64, + /// A wake whose signal failed, which the next wake delivers ([`Done::wake`]); cleared as the + /// thread next reads the state. + owed: bool, stop: bool, lost: bool, /// For the device tests: the values the completion thread's last GPU wait waits for, in its @@ -191,6 +222,7 @@ impl Done { fire: Vec::new(), waiting: Waiting::Not, woken: 0, + owed: false, stop: false, lost: false, #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -330,16 +362,28 @@ impl Done { } /// Wakes the completion thread where it waits. With `flight_only` (the change is only more - /// work in flight), a thread that already waits for the progress semaphore is left to wait. + /// work in flight), a thread that already waits for the progress semaphore is left to wait, + /// unless a wake is owed. + /// + /// `vkSignalSemaphore` fails only for want of memory or with `VK_ERROR_UNKNOWN`, never with a + /// loss. A wake whose signal fails leaves the thread in its wait and is owed: the thread stays + /// marked waiting on the GPU, so the next wake from any thread, flight-only ones included, + /// signals again at a higher value, which the thread's wait also meets. The limit: a failed + /// wake that no later wake follows waits for the wait's other semaphores. Where nothing is in + /// flight, those are signals of batches that completed; where something is, a listener or an + /// end waits for the front batch, a deadlock only where that batch waits on a host signal the + /// listener or the end's handlers would give. fn wake(&self, state: &mut DoneState, core: &Core, flight_only: bool) { match state.waiting { Waiting::Not => return, - Waiting::Gpu { progress: true } if flight_only => return, + Waiting::Gpu { progress: true } if flight_only && !state.owed => return, Waiting::Host => self.changed.notify_one(), Waiting::Gpu { .. } => { state.woken += 1; - // A failure is a loss, which the thread's wait then reports. - let _ = self.signal_wake(core, state.woken); + state.owed = self.signal_wake(core, state.woken).is_err(); + if state.owed { + return; + } } } state.waiting = Waiting::Not; @@ -947,6 +991,8 @@ pub(crate) fn run(core: Arc) { core.counters.event_read(crate::counters::event_step::WAKE); state = done.lock(); state.waiting = Waiting::Not; + // The round reads every change, an owed wake's among them. + state.owed = false; match result { Err(vk::Result::TIMEOUT) | Ok(()) => {} Err(result) => { diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs index 1fa86e6ea..0ed3bb851 100644 --- a/crates/metal2vulkan-runtime/src/device.rs +++ b/crates/metal2vulkan-runtime/src/device.rs @@ -1847,24 +1847,21 @@ impl Core { } /// Waits for the device to go idle. A lost device does so at once. + /// + /// `vkDeviceWaitIdle` fails with `VK_ERROR_DEVICE_LOST`, after which nothing is pending, or for + /// want of memory or with `VK_ERROR_UNKNOWN`, which say nothing of what is pending: the wait is + /// then made again ([`complete::wait_through`]) until it succeeds or the device is lost. A + /// lasting out-of-memory result on a live device so waits, and nothing the device may still + /// use is destroyed after it. pub(crate) fn wait_idle(&self) { - // `vkDeviceWaitIdle` needs every queue of the device externally synchronized. - let _runtime = lock(&self.queues.runtime); - let _present = (!Arc::ptr_eq(&self.queues.runtime, &self.queues.present)) - .then(|| lock(&self.queues.present)); - #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - let failed = (self.fail_waits) - .try_update(Ordering::Relaxed, Ordering::Relaxed, |left| { - left.checked_sub(1) - }) - .is_ok(); - #[cfg(not(all(test, any(m2v_gpu, m2v_cpu_icd))))] - let failed = false; - if failed { - return; - } - // SAFETY: every queue is held. A lost device fails the wait, and then nothing is pending. - let _ = unsafe { self.device.device_wait_idle() }; + complete::wait_through(self, || { + // `vkDeviceWaitIdle` needs every queue of the device externally synchronized. + let _runtime = lock(&self.queues.runtime); + let _present = (!Arc::ptr_eq(&self.queues.runtime, &self.queues.present)) + .then(|| lock(&self.queues.present)); + // SAFETY: every queue is held. + unsafe { self.device.device_wait_idle() } + }); } } diff --git a/crates/metal2vulkan-runtime/src/import.rs b/crates/metal2vulkan-runtime/src/import.rs index 025129e7c..22b40f7b8 100644 --- a/crates/metal2vulkan-runtime/src/import.rs +++ b/crates/metal2vulkan-runtime/src/import.rs @@ -406,7 +406,13 @@ impl Sparse { /// Waits on the host until the bind that signals `value` completed: before its buffer is /// destroyed (`VUID-vkDestroyBuffer-buffer-00922`). At once where a submission waited for it /// and retired, as each that used the buffer did; a lost device ends the wait. - pub(crate) fn wait(&self, device: &ash::Device, value: u64) { + /// + /// `vkWaitSemaphores` fails with `VK_ERROR_DEVICE_LOST`, after which nothing is pending, or for + /// want of memory or with `VK_ERROR_UNKNOWN`, which say nothing of the bind: the wait is then + /// made again (`complete::wait_through`) until it succeeds or the device is lost. A lasting + /// out-of-memory result on a live device so waits, and no buffer whose bind may still be + /// pending is destroyed. + pub(crate) fn wait(&self, core: &Core, value: u64) { let Some(&timeline) = self.timeline.get() else { return; }; @@ -415,9 +421,10 @@ impl Sparse { let info = vk::SemaphoreWaitInfo::default() .semaphores(&semaphores) .values(&values); - // SAFETY: the timeline is live, and the bind that signals `value` was submitted. A lost - // device fails the wait, and then nothing is pending. - let _ = unsafe { device.wait_semaphores(&info, u64::MAX) }; + // SAFETY: the timeline is live, and the bind that signals `value` was submitted. + crate::complete::wait_through(core, || unsafe { + core.device.wait_semaphores(&info, u64::MAX) + }); } } diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 6ed6ce659..00f3c57a4 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -2854,7 +2854,7 @@ fn free_own(core: &Core, memory: &Memory, release: Option) { Some(Own::Sparse { bind, space }) => { let sparse = core.imports.sparse.as_ref(); if let Some(sparse) = sparse { - sparse.wait(&core.device, bind); + sparse.wait(core, bind); } // SAFETY: as below, and the bind completed. unsafe { core.device.destroy_buffer(memory.buffer, None) };