From 1d15b13eb7d558bcd535766af4e65bd619c07b66 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 21 Oct 2026 22:56:45 +0300 Subject: [PATCH] Complete a queued commit its own work refused The steps this packet landed as, in order: - Pin the runtime sources with a refused queued commit's completion Content: the tree of `development` at a62e8a365f, unchanged. --- .../src/command_buffer/mod.rs | 90 ++++++++++++++----- .../src/tests/deferred_calls.rs | 79 +++++++++++++++- .../runtime-sources.sha256 | 2 +- docs/API.md | 5 +- docs/REFUSALS.md | 6 +- 5 files changed, 152 insertions(+), 30 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 9c2c78218..4c4d5c51f 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -147,6 +147,20 @@ impl std::fmt::Debug for CommandBuffer { } } +/// How a commit runs ([`CommandBuffer::commit_now`]). +#[derive(Clone, Copy, PartialEq, Eq)] +enum CommitRun { + /// Inside `commit` (or `commit_failed`). + AtCall, + /// After `commit` returned, its own work having waited for a render encoder's end + /// (`render/queued_commits.rs`). + Queued, + /// Again after that work refused it (`State::refuse_commit`): nothing of the command buffer + /// runs, and nothing that may fail is made for it (its predication tables, its root tables' + /// pointing, its function-table snapshots, its argument samplers' listing), so it commits. + Refused, +} + /// A command buffer as the device's commits that wait hold it (`render/queued_commits.rs`): a /// trait object, whose `Send` and `Sync` its bounds give, made with no allocation. A program's /// crate proves the device's `Send` and `Sync` within its own recursion limit (rustc's 128 by @@ -453,6 +467,10 @@ pub(super) struct State { ending: Option, /// The device's lowering thread lowered the end it holds (`ending`). end_lowered: bool, + /// The commits' own work fails this many more times (a device test's injection of an out of + /// memory, `tests::deferred_calls`). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + failures_injected: u32, /// `commit` returned with its own work left to run once a render encoder's end is lowered /// (`render/queued_commits.rs`), which has not run: to the program, the command buffer is /// committed. @@ -1498,6 +1516,8 @@ impl CommandBuffer { abandoned: false, ending: None, end_lowered: false, + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + failures_injected: 0, queued_commit: false, committing: false, pool: None, @@ -1606,6 +1626,13 @@ impl CommandBuffer { self.0 } + /// Fail the work of its next `count` commits (not one run again with nothing of it run), as + /// out of memory: a device test's injection (`tests::deferred_calls`). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn fail_commit_work(&self, count: u32) { + self.state().failures_injected = count; + } + /// Whether `waiting` holds this command buffer. pub(crate) fn is(&self, waiting: &dyn Waiting) -> bool { self.0.address() == waiting.address() @@ -1971,7 +1998,8 @@ impl CommandBuffer { /// (docs/API.md section 1). A refusal only that work finds (an executed indirect command's, /// out of memory) fails the command buffer with nothing of it run /// ([`CommandBufferError::CallRefused`] of `commit`, where no call of it was refused before; - /// [`refusal`](Self::refusal) keeps the error). + /// [`refusal`](Self::refusal) keeps the error): it completes in its queue's order, its + /// completed handlers run. pub fn commit(&self) -> Result<(), Error> { self.commit_as("commit", None) } @@ -2014,7 +2042,7 @@ impl CommandBuffer { } // The last render encoder's end, where its call left it to the device's lowering thread. self.settle_end(); - self.commit_settled(call, failure, false) + self.commit_settled(call, failure, CommitRun::AtCall) } /// Under `RenderLoweringPolicy::Worker`, where the command buffer holds a render encoder's @@ -2058,19 +2086,23 @@ impl CommandBuffer { /// Run the commit's own work, which waited for a render encoder's end /// (`render/queued_commits.rs`), the end lowered: on the device's lowering thread /// (`by_thread`) or the program's. A refusal it finds fails the command buffer - /// (`State::refuse_commit`), which then commits with nothing of it run. Where even that - /// commit fails (the device out of memory), the command buffer never completes; its refusal - /// keeps the first error. + /// (`State::refuse_commit`), which then commits again with nothing of it run and nothing that + /// may fail made for it ([`CommitRun::Refused`]): it completes, in its queue's order, with + /// that error, and its completed handlers run, as every committed command buffer of Metal's + /// does. pub(crate) fn commit_queued(&self, by_thread: bool) { let counts = &self.0.device.shared().counts; counts.render_log_commit_run(by_thread); self.settle_end(); - let Err(error) = self.commit_settled("commit", None, true) else { + let Err(error) = self.commit_settled("commit", None, CommitRun::Queued) else { return; }; self.state().refuse_commit(error); - // A refusal of this one is already kept, as the first. - let _ = self.commit_settled("commit", None, true); + let committed = self.commit_settled("commit", None, CommitRun::Refused); + debug_assert!( + committed.is_ok(), + "a refused commit's commit of nothing failed: {committed:?}" + ); } /// Before a wait for the command buffer: where its commit's own work waits @@ -2088,21 +2120,21 @@ impl CommandBuffer { } } - /// The commit, the last render encoder's end lowered: `queued` where its own work waited - /// (`render/queued_commits.rs`). + /// The commit, the last render encoder's end lowered, run as `run` says. fn commit_settled( &self, call: &'static str, failure: Option, - queued: bool, + run: CommitRun, ) -> Result<(), Error> { // The waiting fetched render targets take their storage form at this commit where it // allows (`storage_form.rs`): one atomic read where none waits. The scheduler's thread - // ends the switch once it submitted the command buffer. - if !self.take_storage_forms(failure.is_some()) { - return self.commit_now(call, failure, queued); + // ends the switch once it submitted the command buffer. None where nothing of it runs. + let injected = failure.is_some() || run == CommitRun::Refused; + if !self.take_storage_forms(injected) { + return self.commit_now(call, failure, run); } - let committed = self.commit_now(call, failure, queued); + let committed = self.commit_now(call, failure, run); if committed.is_err() { self.give_up_storage_forms(); } @@ -2114,14 +2146,14 @@ impl CommandBuffer { &self, call: &'static str, failure: Option, - queued: bool, + run: CommitRun, ) -> Result<(), Error> { let device = &self.0.device; let (segments, failure, reached): (Vec<(Deferred, bool)>, _, _) = { let mut state = self.state(); - let refusal = match queued { - true => state.commit_refusal(), - false => state.refusal(), + let refusal = match run { + CommitRun::AtCall => state.refusal(), + CommitRun::Queued | CommitRun::Refused => state.commit_refusal(), }; if let Some(problem) = refusal { return Err(invalid(call, problem)); @@ -2132,8 +2164,10 @@ impl CommandBuffer { } // Its last unit of command predication ends: a live block left open where a unit // ended refuses, and each step's gates are listed for it. - let held = &mut *state; - held.predication.commit(&mut held.uploads, device)?; + if run != CommitRun::Refused { + let held = &mut *state; + held.predication.commit(&mut held.uploads, device)?; + } let failure = Failure::of(failure, state.fails_from, ended); let failure = Failure::with_faults(failure, &state.faulted, ended); // The encoders that run: all but those `failure` fails. @@ -2204,9 +2238,21 @@ impl CommandBuffer { } state.prepare(prepared); state.plan_checks(); + // A refused commit's commands run nothing: none of what follows is made for them. + if run == CommitRun::Refused { + state.table_snapshots.clear(); + state.sampler_listings.clear(); + } + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + if run != CommitRun::Refused && state.failures_injected > 0 { + state.failures_injected -= 1; + return Err(vulkan(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY)); + } // Its root tables search every live buffer of its own on the device, and what its // encoders bound and made resident (`live_buffers.rs`). - state.point_root_tables(device)?; + if run != CommitRun::Refused { + state.point_root_tables(device)?; + } // The function-table snapshots read the tables' words as they stand now. for snapshot in &state.table_snapshots { snapshot.refresh()?; diff --git a/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs b/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs index e9f5acf79..2a687f59c 100644 --- a/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs +++ b/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs @@ -9,7 +9,8 @@ //! a buffer detached after the call refuses nothing of it; a program that outruns the device's //! lowering thread waits for it at the cap of its encoder's batches, and goes on; an end and a //! commit return before the lowering thread lowered the end, the commit's own work waiting for it, -//! and the commits after it waiting behind it. +//! and the commits after it waiting behind it, and one whose own work fails completing with the +//! refusal. //! //! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are the owned fixture @@ -17,7 +18,7 @@ use super::blit_holds::{busy, over_host, until, Host, Scratch, FILLED, WAIT}; use super::encoder_holds::{bits, bytes_of, pass, render_state, words_of}; -use crate::error::invalid; +use crate::error::{invalid, vulkan}; use crate::render::{BATCH_CALLS, HANDED_BATCHES}; use crate::StoreAction; use crate::{ @@ -26,6 +27,7 @@ use crate::{ Origin, Problem, RenderCommandEncoder, RenderPipelineState, ResourceOptions, RuntimeGap, ShaderCacheOptions, Size, Texture, TextureDescriptor, VertexAmplificationViewMapping, Viewport, }; +use ash::vk; use metal2vulkan::device::RenderLoweringPolicy; use metal2vulkan::metal::{IndexType, PixelFormat, PrimitiveType, TextureUsage}; use std::path::Path; @@ -929,3 +931,76 @@ fn a_commit_after_an_end_in_flight_refuses_a_predication_block_left_open() { ); } } + +/// A commit whose own work fails, after it returned, fails its command buffer as Metal's committed +/// command buffers fail: with an out of memory injected into that work twice, under Worker (the +/// slot's lowering held, so the commit's work waits for the end), `commit` returns; the command +/// buffer completes with `CallRefused` of `commit` and the error kept, its completed handler runs +/// and its wait returns; a command buffer committed after it on the same queue completes after +/// it, its fill landed. Its second injected failure never ran: the commit ran again making nothing +/// that may fail. Under `AtCall` the commit returns the error. +#[test] +fn a_commit_whose_own_work_fails_completes_with_the_refusal() { + let scratch = Scratch::new("deferred-commit-fails"); + let error = vulkan(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY); + for policy in POLICIES { + let device = device(&scratch.0, policy, &[], &Heard::default()); + let state = rectangle_state(&device); + let queue = device.new_command_queue().unwrap(); + let target = target(&device); + let refused = queue.command_buffer().unwrap(); + let mut encoder = refused.render_command_encoder(&pass(&target)).unwrap(); + rectangle(&state, &mut encoder); + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + let order = Arc::new(Mutex::new(Vec::new())); + let ran = Arc::clone(&order); + let handler = Box::new(move |_: &CommandBuffer| ran.lock().unwrap().push("refused")); + refused.add_completed_handler(handler).unwrap(); + if policy != RenderLoweringPolicy::Worker { + encoder.end_encoding().unwrap(); + refused.fail_commit_work(1); + assert_eq!(refused.commit(), Err(error.clone())); + assert_eq!(refused.status(), CommandBufferStatus::NotEnqueued); + continue; + } + let slots = device.shared().deferred.taken(); + let [slot] = &slots[..] else { + panic!("{} encoders' slots taken, not one", slots.len()); + }; + refused.fail_commit_work(2); + let committed = slot.while_held(|| { + encoder.end_encoding().unwrap(); + refused.commit() + }); + assert_eq!(committed, Ok(())); + let filled = device.new_buffer(4, ResourceOptions::shared()).unwrap(); + let later = queue.command_buffer().unwrap(); + let mut blit = later.blit_command_encoder().unwrap(); + blit.fill_buffer(&filled, 0..4, 0x5a).unwrap(); + blit.end_encoding().unwrap(); + let ran = Arc::clone(&order); + let handler = Box::new(move |_: &CommandBuffer| ran.lock().unwrap().push("later")); + later.add_completed_handler(handler).unwrap(); + later.commit().unwrap(); + refused.wait_until_completed_for(WAIT).unwrap(); + later.wait_until_completed_for(WAIT).unwrap(); + let commit = EncoderCall { + selector: "commit", + index: 0, + }; + assert_eq!(refused.status(), CommandBufferStatus::Error); + assert_eq!( + refused.error(), + Some(CommandBufferError::CallRefused(commit)) + ); + assert_eq!(refused.refusal(), Some(error.clone())); + assert_eq!(later.status(), CommandBufferStatus::Completed); + assert_eq!(words_of(&filled), vec![u32::from_le_bytes([0x5a; 4])]); + assert_eq!(*order.lock().unwrap(), ["refused", "later"]); + let counts = device.work_counts(); + let commits = counts.render_log_commits_by_thread + counts.render_log_commits_by_program; + assert_eq!(commits, 2, "{counts:?}"); + } +} diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 59289f643..520e8c528 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -98be5a02d537ee4d861591c0ccf9bea610251efaa6fb5c5716731b1cfd984de6 +ef23fce4d7bb57f64f9635bad931d6a0d915199e779a8e4f06aa6e961bb06cdd diff --git a/docs/API.md b/docs/API.md index 07d57122c..eaaee69cc 100644 --- a/docs/API.md +++ b/docs/API.md @@ -141,8 +141,9 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: wait for the command buffer lowers on the waiting thread what that thread has not. A refusal only the commit's own work finds (an executed indirect command's recording, the commit's uploads) fails the command buffer, nothing of it run, with `CallRefused` of `commit` at index - 0 where no call of it was refused before; where even that commit fails (out of memory), the - command buffer never completes. An end that checks the depth/stencil + 0 where no call of it was refused before: it commits again with nothing made for its commands, + so it completes, in its queue's order, its completed handlers run and its waits return, as + every committed command buffer of Metal's does. An end that checks the depth/stencil attachment's store actions or store action options (one `Unknown`, options set, or any store action or resolve target set by a call) is lowered inside `end_encoding`, which returns its refusal. The call still makes Metal's checks of its arguments and of the encoder's state, and returns diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 8860aa41c..bb94c0740 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -14,7 +14,7 @@ Columns: - `none`: no public API path: malformed or non-Metal input, Apple-private calls, or a cap no valid program of ordinary size meets; - `?`: not assessed yet. -Generated at `fb41c3216`. +Generated at `d282c7964`. ## Totals @@ -134,7 +134,7 @@ Generated at `fb41c3216`. | `TextureSwizzle` | A texture swizzle whose Metal behavior is not measured | devices short of a Vulkan feature the site names; every device (not implemented) | 7: `crates/metal2vulkan-runtime/src/binding_view.rs:167`, `crates/metal2vulkan-runtime/src/texture.rs:980` (+5) | `app`: texture swizzles whose Metal behaviour is unmeasured | | `MipmapGeneration` | `generateMipmapsForTexture:` where the device's filter is not shown to give Metal's answer | devices without VkFeature::ShaderInt64; devices without a format's usage; every device (not implemented) | 7: `crates/metal2vulkan-runtime/src/blit_texture.rs:1787`, `crates/metal2vulkan-runtime/src/mipmap_pick.rs:37` (+5) | `app`: generateMipmapsForTexture: where the device's filter is not Metal's | | `HostMemory` | A buffer over the caller's host memory without a copy (`newBufferWithBytesNoCopy:`) | devices without VkExtension::ExtExternalMemoryHost; every device (no Vulkan mechanism); every device (not implemented) | 5: `crates/metal2vulkan-runtime/src/host_memory.rs:393`, `crates/metal2vulkan-runtime/src/host_memory.rs:433` (+3) | `system`: newBufferWithBytesNoCopy: where the device cannot import the memory | -| `GpuTimes` | A command buffer's GPU times (`GPUStartTime`, `GPUEndTime`) on a device whose queue family writes no timestamps (`timestampValidBits` 0) | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2496` | `rare`: GPU times on a queue without timestamps | +| `GpuTimes` | A command buffer's GPU times (`GPUStartTime`, `GPUEndTime`) on a device whose queue family writes no timestamps (`timestampValidBits` 0) | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2542` | `rare`: GPU times on a queue without timestamps | | `CountingVisibility` | A `Counting` visibility result (`MTLVisibilityResultModeCounting`) on a device without `occlusionQueryPrecise` | devices without VkFeature::OcclusionQueryPrecise | 1: `crates/metal2vulkan-runtime/src/visibility.rs:452` | `rare`: counting occlusion queries on a device without precise queries | | `ViewFormatReinterpretation` | A texture view whose format has other components, or components of other widths, than its texture's (`RGBA8Unorm` as `R32Uint`), on a device whose... | every device (no Vulkan mechanism) | 1: `crates/metal2vulkan-runtime/src/view_plan.rs:568` | `app`: a view of another component layout on a portability subset (MoltenVK) | | `SeparateMultisampledDepthStencil` | A render pass whose depth and stencil attachments are separate multisampled textures that it loads or may store, on a device without maintenance8,... | - | via a helper: 7: `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:188`, `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:294` (+5) | `rare`: separate multisampled depth and stencil textures | @@ -400,7 +400,7 @@ Each refusal's sites, with the function that builds it. - `feature::TextureSwizzle`: `crates/metal2vulkan-runtime/src/binding_view.rs:167 (binding_view)`; `crates/metal2vulkan-runtime/src/texture.rs:980 (may_view)`; `crates/metal2vulkan/src/bind/plan/resources.rs:1102 (plain_texture)`; `crates/metal2vulkan/src/lower/sampler/select.rs:2587 (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3391 (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3738 (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs:307 (select)` - `feature::MipmapGeneration`: `crates/metal2vulkan-runtime/src/blit_texture.rs:1787 (mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_pick.rs:37 (pick_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:262 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:270 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:275 (plan_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs:304 (plan_mipmaps)`; `crates/metal2vulkan/src/bind/mipmap_filter.rs:973 (mipmap_filter_module)` - `feature::HostMemory`: `crates/metal2vulkan-runtime/src/host_memory.rs:393 (not_importable)`; `crates/metal2vulkan-runtime/src/host_memory.rs:433 (refuse_unwritable)`; `crates/metal2vulkan-runtime/src/host_memory.rs:652 (new)`; `crates/metal2vulkan-runtime/src/host_memory.rs:657 (new)`; `crates/metal2vulkan-runtime/src/host_memory.rs:675 (new)` -- `feature::GpuTimes`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2496 (gpu_times)` +- `feature::GpuTimes`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs:2542 (gpu_times)` - `feature::CountingVisibility`: `crates/metal2vulkan-runtime/src/visibility.rs:452 (check_mode)` - `feature::ViewFormatReinterpretation`: `crates/metal2vulkan-runtime/src/view_plan.rs:568 (reinterpretation_refused)` - `feature::SeparateMultisampledDepthStencil`: `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:188 (sampled_candidate)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:294 (by_draws)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:336 (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:376 (scratch)`; `crates/metal2vulkan-runtime/src/depth_stencil_scratch.rs:777 (plan)`; `crates/metal2vulkan-runtime/src/nan_clear.rs:651 (nan_write)`; `crates/metal2vulkan-runtime/src/texture/signed_depth.rs:191 (sample_strip)`