From e0a6065c65b5b6c2e92ee7052ed084cd8910d486 Mon Sep 17 00:00:00 2001 From: 39ali Date: Sun, 29 Mar 2026 14:30:38 +0300 Subject: [PATCH] fix(metal): Wait using a condition variable instead of polling Fixes #8119 --- CHANGELOG.md | 2 ++ wgpu-hal/src/metal/device.rs | 70 +++++++++++++++++------------------- wgpu-hal/src/metal/mod.rs | 11 +++--- 3 files changed, 40 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ebb0d80b1..6ffde1f74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -242,6 +242,8 @@ By @beholdnec in [#8505](https://github.com/gfx-rs/wgpu/pull/8505). #### Metal - Fix crash on fence creation when running in a MacOS Seatbelt sandbox. By @wumpf in [#9415](https://github.com/gfx-rs/wgpu/pull/9415) +- Improved command buffer completion handling. By @39ali in [#9328](https://github.com/gfx-rs/wgpu/pull/9328). + - Wait using a condition variable, instead of polling. - Fixed structure field names incorrectly ignoring reserved keywords in the Metal (MSL) backend. By @39ali [#9379](https://github.com/gfx-rs/wgpu/pull/9379). - Restore the `Queue::as_raw` method, which was removed without good reason in v29. It now returns `&ProtocolObject`. By @andyleiserson in [#9560](https://github.com/gfx-rs/wgpu/pull/9560). diff --git a/wgpu-hal/src/metal/device.rs b/wgpu-hal/src/metal/device.rs index 70bf2a7ee..e93235f36 100644 --- a/wgpu-hal/src/metal/device.rs +++ b/wgpu-hal/src/metal/device.rs @@ -1,7 +1,5 @@ use alloc::{borrow::ToOwned as _, sync::Arc, vec::Vec}; -use core::{ptr::NonNull, sync::atomic}; -use parking_lot::RwLock; -use std::{thread, time}; +use core::ptr::NonNull; use bytemuck::TransparentWrapper; use objc2::{ @@ -12,11 +10,11 @@ use objc2::{ use objc2_foundation::{ns_string, NSError, NSRange, NSString, NSUInteger}; use objc2_metal::{ MTLAccelerationStructure, MTLAccelerationStructureInstanceOptions, MTLBuffer, - MTLCaptureManager, MTLCaptureScope, MTLCommandBuffer, MTLCommandBufferStatus, - MTLCompileOptions, MTLComputePipelineDescriptor, MTLComputePipelineState, - MTLCounterSampleBufferDescriptor, MTLCounterSet, MTLDepthClipMode, MTLDepthStencilDescriptor, - MTLDevice, MTLFunction, MTLIndirectAccelerationStructureInstanceDescriptor, MTLLanguageVersion, - MTLLibrary, MTLMeshRenderPipelineDescriptor, MTLMutability, MTLPackedFloat3, MTLPackedFloat4x3, + MTLCaptureManager, MTLCaptureScope, MTLCompileOptions, MTLComputePipelineDescriptor, + MTLComputePipelineState, MTLCounterSampleBufferDescriptor, MTLCounterSet, MTLDepthClipMode, + MTLDepthStencilDescriptor, MTLDevice, MTLFunction, + MTLIndirectAccelerationStructureInstanceDescriptor, MTLLanguageVersion, MTLLibrary, + MTLMeshRenderPipelineDescriptor, MTLMutability, MTLPackedFloat3, MTLPackedFloat4x3, MTLPipelineBufferDescriptorArray, MTLPipelineOption, MTLPixelFormat, MTLPrimitiveTopologyClass, MTLRenderPipelineColorAttachmentDescriptorArray, MTLRenderPipelineDescriptor, MTLResource, MTLResourceID, MTLResourceOptions, MTLSamplerAddressMode, MTLSamplerDescriptor, @@ -24,6 +22,7 @@ use objc2_metal::{ MTLTexture, MTLTextureDescriptor, MTLTextureType, MTLTriangleFillMode, MTLVertexDescriptor, MTLVertexStepFunction, }; +use parking_lot::{Condvar, Mutex, RwLock}; use super::{adapter::VERTEX_BUFFER_SLOT_START, conv, PassthroughShader, ShaderModuleSource}; use crate::{auxil::map_naga_stage, TlasInstance}; @@ -1886,7 +1885,7 @@ impl crate::Device for super::Device { None }; Ok(super::Fence { - completed_value: Arc::new(atomic::AtomicU64::new(0)), + sync: Arc::new((Mutex::new(0), Condvar::new())), pending_command_buffers: RwLock::new(Vec::new()), shared_event, }) @@ -1897,14 +1896,7 @@ impl crate::Device for super::Device { } unsafe fn get_fence_value(&self, fence: &super::Fence) -> DeviceResult { - let mut max_value = fence.completed_value.load(atomic::Ordering::Acquire); - let pending_command_buffers = fence.pending_command_buffers.read(); - for &(value, ref cmd_buf) in pending_command_buffers.iter() { - if cmd_buf.status() == MTLCommandBufferStatus::Completed { - max_value = value; - } - } - Ok(max_value) + Ok(fence.get_latest()) } unsafe fn wait( &self, @@ -1912,38 +1904,40 @@ impl crate::Device for super::Device { wait_value: crate::FenceValue, timeout: Option, ) -> DeviceResult { - if wait_value <= fence.completed_value.load(atomic::Ordering::Acquire) { + let (ref mutex, ref condvar) = *fence.sync; + let mut lock = mutex.lock(); + + if wait_value <= *lock { return Ok(true); } - let pending_command_buffers = fence.pending_command_buffers.read(); - - let cmd_buf = match pending_command_buffers - .iter() - .find(|&&(value, _)| value >= wait_value) { - Some((_, cmd_buf)) => cmd_buf.clone(), - None => { + let pending_command_buffers = fence.pending_command_buffers.read(); + if !pending_command_buffers + .iter() + .any(|&(value, _)| value >= wait_value) + { log::error!("No active command buffers for fence value {wait_value}"); return Err(crate::DeviceError::Lost); } - }; + } - // Make sure that nothing is blocked during the actual wait. - drop(pending_command_buffers); - - let start = time::Instant::now(); - loop { - if let MTLCommandBufferStatus::Completed = cmd_buf.status() { - return Ok(true); - } - if let Some(timeout) = timeout { - if start.elapsed() >= timeout { - return Ok(false); + if let Some(deadline) = + timeout.and_then(|timeout| std::time::Instant::now().checked_add(timeout)) + { + while *lock < wait_value { + let result = condvar.wait_until(&mut lock, deadline); + if result.timed_out() { + return Ok(*lock >= wait_value); } } - thread::sleep(core::time::Duration::from_millis(1)); + } else { + while *lock < wait_value { + condvar.wait(&mut lock); + } } + + Ok(true) } unsafe fn start_graphics_debugger_capture(&self) -> bool { diff --git a/wgpu-hal/src/metal/mod.rs b/wgpu-hal/src/metal/mod.rs index fa2138cc6..7a874f019 100644 --- a/wgpu-hal/src/metal/mod.rs +++ b/wgpu-hal/src/metal/mod.rs @@ -55,7 +55,7 @@ use objc2_metal::{ MTLTriangleFillMode, MTLWinding, }; use objc2_quartz_core::CAMetalLayer; -use parking_lot::{Mutex, RwLock}; +use parking_lot::{Condvar, Mutex, RwLock}; #[derive(Clone, Debug)] pub struct Api; @@ -542,9 +542,10 @@ impl crate::Queue for Queue { ) -> Result<(), crate::DeviceError> { autoreleasepool(|_| { let extra_command_buffer = { - let completed_value = Arc::clone(&signal_fence.completed_value); + let fence_sync = Arc::clone(&signal_fence.sync); let block = block2::RcBlock::new(move |_cmd_buf| { - completed_value.store(signal_value, atomic::Ordering::Release); + *fence_sync.0.lock() = signal_value; + fence_sync.1.notify_all(); }); let raw = match command_buffers.last() { @@ -1028,7 +1029,7 @@ unsafe impl Sync for QuerySet {} #[derive(Debug)] pub struct Fence { - completed_value: Arc, + sync: Arc<(Mutex, Condvar)>, /// The pending fence values have to be ascending. pending_command_buffers: RwLock>, shared_event: Option>>, @@ -1046,7 +1047,7 @@ unsafe impl Sync for Fence {} impl Fence { fn get_latest(&self) -> crate::FenceValue { - let mut max_value = self.completed_value.load(atomic::Ordering::Acquire); + let mut max_value = *self.sync.0.lock(); let pending_command_buffers = self.pending_command_buffers.read(); for &(value, ref cmd_buf) in pending_command_buffers.iter() { if cmd_buf.status() == MTLCommandBufferStatus::Completed {