From 077709c8d22ce257b720ccd90c3ecb965498b8e7 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 25 Oct 2026 06:09:23 +0200 Subject: [PATCH] Say what MoltenVK reads after a command buffer's signal, and keep the fence Content: the tree of `development` at 8f89bd810c, unchanged. --- .../src/command_buffer/completion.rs | 17 ++-- .../src/command_buffer/fences.rs | 90 ++++++++++++++++--- .../src/driver_defects.rs | 28 ++++-- .../src/runtime_lane/commit_work.rs | 52 +++++++---- 4 files changed, 143 insertions(+), 44 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs index 1f72dff79..635861b6e 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs @@ -30,13 +30,16 @@ //! the turn and the program's thread took up to 13 to 55 ms at a light burst's 99th percentile //! of the queue storm (`runtime_lane::queue_storms`), over Metal's one wake from its completion; //! counted (`WorkCounts::completed_where_seen`). -//! - **A command buffer finishes at its fence, where it has one.** Where the driver still reads -//! a command buffer's objects after the value (MoltenVK 1.4.1), the batch that ends it also -//! signals a fence ([`fences`](super::fences)), which the driver signals after those reads: the -//! turn posts the transition, after which what the command buffer used is released, only once -//! the fence is signaled too, and then resets the fence and gives it back. A wait for fences -//! holds up the other queues' batches by as long. Elsewhere Vulkan's value is enough, and the -//! batch has no fence. +//! - **A command buffer finishes at its fence, where it has one.** Where the driver still reads a +//! command buffer's query pools after the value (MoltenVK), the batch that ends it also signals +//! a fence ([`fences`](super::fences)), which the driver signals after those reads: the turn +//! posts the transition, after which what the command buffer used is released, only once the +//! fence is signaled too, and then resets the fence and gives it back. A wait for fences holds +//! up the other queues' batches by as long. Elsewhere Vulkan's value is enough, and the batch +//! has no fence. On MoltenVK every command buffer takes one, not only the ones whose query pools +//! that driver reads late: a relayed queue's failure attribution needs one for every batch, and +//! the host sees the fence sooner than the value there anyway (`fences.rs`, which holds the +//! argument, the reading of MoltenVK's completed handlers and the measurement). //! - **One waiter per `VkQueue`, each waiting for one object** (replacing the wait for any of the //! timelines). Each `VkQueue`'s waiter thread waits for its queue's first pending batch past the //! value it saw reached: for the batch's fence where it has one, else for its queue's timeline to diff --git a/crates/metal2vulkan-runtime/src/command_buffer/fences.rs b/crates/metal2vulkan-runtime/src/command_buffer/fences.rs index 46569c656..93ae47c6c 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/fences.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/fences.rs @@ -3,20 +3,82 @@ //! only once both its queue's timeline reached the batch's value and the fence is signaled //! ([`completion`](super::completion)). //! -//! - **Where both.** Vulkan makes the two equivalent: once a timeline semaphore's value is -//! reached, the work submitted before its signal completed, and what it used may be released. -//! A driver may still read some of it later. MoltenVK 1.4.1 signals a timeline semaphore from -//! the GPU (an `MTLSharedEvent`), before the Metal command buffer's completed handlers run, and -//! one of those handlers calls into every query pool the command buffer reset or began, without -//! retaining it: a command buffer released at the value crashed there. It signals a fence from -//! the last of those handlers. That is MoltenVK's behavior, not a guarantee of Vulkan's, and the -//! device's driver defects name it (`RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal`, -//! `driver_defects.rs`). +//! - **The value is the completion, and Vulkan says so.** A batch's timeline signal follows the +//! batch's commands: "The first synchronization scope of each semaphore signal operation defined +//! by this command includes every command in the same batch that the signal operation is defined +//! in, and all commands that occur earlier in submission order" (`vkQueueSubmit`). A host wait +//! for the value orders the host after that signal: "signal operations happening before host +//! operations that wait on them" system-synchronize-with them (the memory model), where +//! `vkGetSemaphoreCounterValue` alone gives no such dependency (its value "may immediately be +//! out of date"). So once the waiter's `vkWaitSemaphores` returned for the value, the batch's +//! commands completed and what they used may be released, and nothing but the waiter's wait is +//! relied on ([`completion`](super::completion), where the waits are, and what publishes a +//! batch). The waiter waits for one semaphore, never for any of several +//! (`RuntimeDriverDefect::WaitForAnyObjectLosesASignal`). +//! - **MoltenVK reads some of it later, and only some.** MoltenVK signals a timeline semaphore +//! from the GPU (`MVKSemaphoreMTLEvent::encodeSignal`, `[mtlCmdBuff encodeSignalEvent:]`), so +//! the host sees the value before the Metal command buffer's completed handlers run, and it +//! signals a fence from the last of those handlers. What those handlers read decides whether the +//! value alone is enough. Every `addCompletedHandler:` of 1.4.2's source, read in full (the +//! `addScheduledHandler:` of `MVKImage.mm` is a swapchain's, which the runtime makes none of): +//! - `MVKCommandEncoder::finishQueries` (`MVKCommandBuffer.mm`) calls `finishQueries` on every +//! query pool the command buffer reset, began or ended, through a raw `MVKQueryPool*` it does +//! not retain, and that call takes the pool's `_availabilityLock` and writes its +//! `_availability`. **A Vulkan object of the command buffer's**, and the only handler that +//! reads one the runtime may release at the value. Registered only where the encoder +//! collected an activated query (`_pActivatedQueries`, from `addActivatedQueries`), so only +//! for a command buffer that recorded a query command. +//! - `MVKCommandEncoder::getTempMTLBuffer` and `MVKCmdUpdateBuffer::encode` return a +//! `MVKMTLBufferAllocation` to the pool it came from, which lives in the `MVKCommandPool` of +//! the `VkCommandPool` the command buffer was allocated from +//! (`MVKCommandEncoder::getCommandEncodingPool`). The runtime calls +//! `vkDestroyCommandPool` on a command buffer's pool only as the device is torn down, after +//! its queues are idle, and resets a spare with `vkResetCommandPool` of no flag, which leaves +//! `MVKCommandPool`'s encoding pool alone (`MVKCommandPool::reset` trims only for +//! `VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT`, which the runtime never passes; +//! `spares.rs`). So that pool outlives every handler. +//! - `MVKImagePlane::pullFromDeviceOnCompletion` (`MVKImage.mm`) copies a texture into mapped +//! host-coherent memory through its `MVKImagePlane*`, a `VkImage`'s. Registered only from +//! `MVKImagePlane::applyImageMemoryBarrier`, and only where the barrier's destination names +//! `VK_ACCESS_HOST_READ_BIT` or `VK_ACCESS_MEMORY_READ_BIT` into `VK_IMAGE_LAYOUT_GENERAL`; +//! no image memory barrier of the runtime names either (`image_barrier.rs`, which is where +//! all of them are made, held to it by `tests::image_barriers`), so it is registered for none +//! of the runtime's command buffers. +//! - `MVKQueueCommandBufferSubmission::finish` (`MVKQueue.mm`) reads the submission, its +//! `MVKQueue`, and the signal semaphores and fence it retains for exactly this +//! ("We therefore retain() each here to ensure they live long enough for this submission to +//! finish using them"); `MVKQueue::handleMTLCommandBufferError` reads the `MTLCommandBuffer` +//! and the device. Neither reads an object of the command buffer. +//! - `MVKCommandEncoder::getStageCountersMTLFence` releases an `MTLFence` the block retains, and +//! `MVKCmdBlitImage::encode`'s three release an `MTLTexture` the block retains. Metal objects +//! of MoltenVK's own, no Vulkan object. +//! +//! So the hazard is one handler and one object class: the query pools of a command buffer that +//! recorded a query command. The device's driver defects name it +//! (`RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal`, `driver_defects.rs`). +//! - **The fence is kept for every command buffer there all the same, and it is the faster wait.** +//! A command buffer that records no query command could learn its completion from the value +//! alone, which Vulkan makes enough (above). It does not, for two measured reasons. +//! - **The host sees the fence before it sees the value.** MoltenVK signals the fence from the +//! last of the completed handlers, after the GPU signalled the value, but its host wait for a +//! timeline value goes through an `MTLSharedEvent`'s listener while its fence is a condition +//! variable the handler thread broadcasts. On an Apple M3 Max (macOS 27.0.1, MoltenVK 1.4.2, +//! `runtime_lane::commit_costs`) one submission of a barrier alone, waited for 200 times after +//! 20: its fence returned 49.3 us after the submission (p10 44.6, p90 60.1) and its timeline +//! value 58.6 us (p10 48.2, p90 82.6). Waiting for the value in its place would cost about 9 +//! us a command buffer at the median and 22 at the 90th percentile, not save any. For scale, a +//! whole empty command buffer of the runtime completes 32.4 us after its commit there (p90 +//! 43.1), so the handler chain is no hundreds of microseconds. +//! - **A queue whose failures are relayed needs one for every batch** (`device/relay.rs`), and +//! every MoltenVK device the runtime creates relays: MoltenVK reports a command buffer's +//! failure to the instance's messenger from the first of the same completed handlers, before +//! the fence's, and the relay gives the failure to the first submission in flight whose fence +//! is unsignaled. A command buffer finished at its value could be finished before its failure +//! arrived. A device the runtime adopts relays none (`Device::from_raw`: an adopted instance +//! has no messenger of the runtime's), so there the defect above is the whole reason. //! - **Only there**. Every other driver signals the fence with the value, so a command buffer there //! ends at its value alone and its commit takes no fence ([`ends_at_fence`]): NVIDIA's -//! `vkCreateFence` on the commit path waited up to 1.9 s for other processes' work. A queue whose -//! failures are relayed (`device/relay.rs`) still takes one for every batch, which its log of -//! submissions in flight needs. +//! `vkCreateFence` on the commit path waited up to 1.9 s for other processes' work. //! - **Pooled, and bounded.** A fence is taken when the last batch is submitted (made only when //! none is idle) and given back, reset, once a completion turn saw it signaled. At most //! [`IDLE`] wait idle; the ones beyond are released. So the fences live are the command buffers @@ -39,8 +101,8 @@ use std::sync::Mutex; pub(crate) const IDLE: usize = 16; /// Whether a submission to `device`'s `VkQueue` `queue` that ends a command buffer takes a fence: -/// where the driver reads a command buffer's objects after its signal, or the queue's failures -/// are relayed (the module docs). +/// where the driver reads a command buffer's query pools after its signal, or the queue's +/// failures are relayed (the module docs). pub(crate) fn ends_at_fence(device: &Device, queue: usize) -> bool { device.shared().flights(queue).is_some() || (device.properties().driver_defects) diff --git a/crates/metal2vulkan-runtime/src/driver_defects.rs b/crates/metal2vulkan-runtime/src/driver_defects.rs index c7a2e1611..bebf1a12f 100644 --- a/crates/metal2vulkan-runtime/src/driver_defects.rs +++ b/crates/metal2vulkan-runtime/src/driver_defects.rs @@ -174,12 +174,28 @@ pub(super) struct Affected { /// load of a released `MVKQueryPool`'s vtable; /// `runtime_lane::visibility::command_buffers_released_at_completion_leave_nothing_read_later` /// passed 0 of 8 runs on an M4). MoltenVK signals a fence from the last of those handlers. Read -/// in 1.4.1's source and measured on 1.4.1 (driverVersion 10401): known broken through 1.4.1. -/// Nothing is refused: a command buffer's last batch signals a fence there too, and the -/// command buffer finishes once both are signaled (`command_buffer/fences.rs`). Every other -/// driver ends a command buffer at its value alone: Vulkan makes the value enough, and their -/// fences are signaled with it, so a fence there only added a `vkCreateFence` to the commit -/// path, which NVIDIA's 615.71.09 held for up to 1.9 s while other processes' work ran. +/// in 1.4.1's source and measured on 1.4.1 (driverVersion 10401); read again in 1.4.2's, where +/// it is unchanged: known broken through 1.4.2. +/// +/// **It covers the query pools of a command buffer that recorded a query command, and nothing +/// else.** Every `addCompletedHandler:` of 1.4.2's source was read, and `finishQueries` is the +/// only handler that reads a Vulkan object of the command buffer: the temporary-buffer handlers +/// reach the `VkCommandPool`'s encoding pool, which the runtime never destroys or releases +/// before the device is torn down; `MVKImagePlane::pullFromDeviceOnCompletion` reads a `VkImage` +/// but is registered only for an image memory barrier naming `HOST_READ` or `MEMORY_READ` into +/// `GENERAL`, which the runtime never makes (`image_barrier.rs`); and the rest read MoltenVK's +/// own objects or ones it retains for the handler. The handler is registered only where the +/// encoder collected an activated query (`MVKCommandEncoder::addActivatedQueries`). +/// +/// Nothing is refused: a command buffer's last batch signals a fence there too, and the command +/// buffer finishes once both are signaled (`command_buffer/fences.rs`). Every command buffer +/// does, not only the ones the narrower scope above can reach: a MoltenVK device the runtime +/// creates relays its queues' failures, which needs a fence for every batch (`device/relay.rs`), +/// and the host sees the fence sooner than the value there anyway (measured on an M3 Max at +/// 1.4.2, `fences.rs`). Every other driver ends a command buffer at its value alone: Vulkan +/// makes the value enough, and their fences are signaled with it, so a fence there only added a +/// `vkCreateFence` to the commit path, which NVIDIA's 615.71.09 held for up to 1.9 s while other +/// processes' work ran. /// /// `WaitForAnyObjectLosesASignal`: /// - MoltenVK (`MOLTENVK`): a host wait for any of several objects to be signaled, which the diff --git a/crates/metal2vulkan-validation/src/runtime_lane/commit_work.rs b/crates/metal2vulkan-validation/src/runtime_lane/commit_work.rs index ee109bf9b..6b0fd3301 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/commit_work.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/commit_work.rs @@ -20,12 +20,16 @@ //! queue outside a batch is there (`device/relay.rs`). //! Before, it was a `vkQueueSubmit` of its own, a second kernel submission listing every buffer //! object of the device on ANV over i915. -//! - **Fences.** Command buffers that each end in one submission complete at their fences where -//! the driver reads their objects after their values (MoltenVK): the queues' waiters wait -//! for no timeline value; before, they waited for one each, which MoltenVK wakes through a shared -//! event's listener. Elsewhere they end at their values, and the device makes no fence for -//! them; before, each commit could make one, which NVIDIA's driver held for up to 1.9 s while -//! other processes' work ran. +//! - **Fences.** Command buffers that each end in one submission complete at their fences on a +//! device whose queues' failures are relayed, which takes one for every batch (MoltenVK, +//! `device/relay.rs`): the queues' waiters wait for no timeline value; before, they waited for +//! one each, which MoltenVK wakes through a shared event's listener. Elsewhere they end at their +//! values, and the device makes no fence for them; before, each commit could make one, which +//! NVIDIA's driver held for up to 1.9 s while other processes' work ran. On a device the runtime +//! adopts, which relays none, every command buffer still ends at a fence where the driver reads +//! a command buffer's query pools after its value, which only the ones that record a query +//! command can suffer: the fence is the faster wait there all the same +//! (`command_buffer/fences.rs`). //! - **The live buffers.** A buffer made or released between commits costs the next resident set //! no ask of a listed buffer and no new buffer to upload it to; before, each asked every //! listed buffer for its pages again and uploaded the set to a new buffer. @@ -621,16 +625,19 @@ fn chained_batches(batch_order: BatchOrderPolicy) { ); } -/// Command buffers that each end in one submission, empty or of a blit, complete at their -/// fences where the driver reads a command buffer's objects after its value -/// (`RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal`): the queues' waiters wait for -/// no timeline value. Elsewhere they end at their values alone: the device makes no fence for -/// any of them, from its creation on, and the queues' waiters wait for their values. +/// Command buffers that each end in one submission, empty or of a blit, complete at their fences +/// on a device whose queues' failures are relayed (`device/relay.rs`), which takes one for every +/// batch, and on one whose driver reads a command buffer's query pools after its value +/// (`RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal`), which takes one for every +/// command buffer's last batch: the queues' waiters wait for no timeline value. Elsewhere they +/// end at their values alone: the device makes no fence for any of them, from its creation on, and +/// the queues' waiters wait for their values. #[test] fn command_buffers_end_at_fences_only_where_the_driver_reads_them_later() { on_device(|device, _| { let queue = device.new_command_queue().unwrap(); let buffer = device.new_buffer(4096, ResourceOptions::default()).unwrap(); + let relayed = relay_marks(device, &queue) > 0; let before = device.work_counts(); for _ in 0..4 { finish(&queue.command_buffer().unwrap()); @@ -640,17 +647,28 @@ fn command_buffers_end_at_fences_only_where_the_driver_reads_them_later() { let late_reads = (device.properties().driver_defects) .contains(&RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal); eprintln!( - "COMMAND-BUFFER-ENDS {}: reads after the value {late_reads}, {} fences made, {} \ - timeline waits for 8 command buffers", + "COMMAND-BUFFER-ENDS {}: reads after the value {late_reads}, failures relayed \ + {relayed}, {} fences made, {} fence waits and {} timeline waits for 8 command \ + buffers that record no query", device.name(), after.fences_made, + after.fence_waits - before.fence_waits, after.timeline_waits - before.timeline_waits ); - if late_reads { - assert_eq!(after.timeline_waits, before.timeline_waits); + // `fences::ends_at_fence` of the queue these command buffers were committed to. + if relayed || late_reads { + assert!(after.fence_waits > before.fence_waits, "fence waits"); + assert_eq!( + after.timeline_waits, before.timeline_waits, + "timeline waits" + ); } else { - assert_eq!(after.fences_made, 0); - assert!(after.timeline_waits > before.timeline_waits); + assert_eq!(after.fence_waits, before.fence_waits, "fence waits"); + assert!( + after.timeline_waits > before.timeline_waits, + "timeline waits" + ); + assert_eq!(after.fences_made, 0, "fences made"); } }); }