diff --git a/crates/metal2vulkan-conformance/probes/icb_cross_queue_writes.m b/crates/metal2vulkan-conformance/probes/icb_cross_queue_writes.m new file mode 100644 index 000000000..0339de589 --- /dev/null +++ b/crates/metal2vulkan-conformance/probes/icb_cross_queue_writes.m @@ -0,0 +1,151 @@ +// Plain Metal's answer, with the API validation layer OFF, for an execution of an indirect command +// buffer whose CPU-written command 0 names a render pipeline state of another color format than +// the executing pass's target, in a command buffer X that waits for a shared event and is +// committed first, on one queue; and a command buffer Y on another queue, committed after X, whose +// kernel writes command 0 again (a valid state, taken from its argument buffer, a vertex buffer and +// a draw of one triangle) and which then signals the event: +// +// written Y's kernel writes command 0, then Y signals; +// unwritten Y signals alone: X runs the CPU's command. +// +// X's render encoder makes the indirect command buffer resident for reading and writing, as a +// guest's does; Y's compute encoder makes it resident for writing. It prints X's and Y's status and +// error and X's target's centre texel (a 16x16 RGBA8Unorm target cleared to red: green where the +// kernel's command ran). The functions are the owned fixture +// `crates/metal2vulkan-validation/fixtures/public/engine/icb_routed_writes.metal`, whose path is +// the second argument; the runtime's lane `runtime_lane::write_routes` runs the same shape. +// +// Build (no GPU needed to build): +// +// clang -fobjc-arc -fmodules -framework Metal -framework Foundation \ +// -o icb_cross_queue_writes icb_cross_queue_writes.m +// +// Run ONE SHAPE PER PROCESS, WITHOUT MTL_DEBUG_LAYER: +// +// ./icb_cross_queue_writes +// +// A shape whose process Metal ends prints no `DONE`, and its exit status is the reading. + +#import +#import + +static void fail(NSString *what, NSError *error) { + printf("FAIL %s: %s\n", what.UTF8String, error.localizedDescription.UTF8String); + exit(2); +} + +// A render state of the fixture's triangle drawing into `format`. +static id stateOf(id device, id library, + MTLPixelFormat format) { + NSError *error = nil; + MTLRenderPipelineDescriptor *descriptor = [MTLRenderPipelineDescriptor new]; + descriptor.vertexFunction = [library newFunctionWithName:@"irw_vertex"]; + descriptor.fragmentFunction = [library newFunctionWithName:@"irw_fragment"]; + descriptor.colorAttachments[0].pixelFormat = format; + descriptor.supportIndirectCommandBuffers = YES; + id state = [device newRenderPipelineStateWithDescriptor:descriptor + error:&error]; + if (!state) fail(@"render state", error); + return state; +} + +int main(int argc, const char **argv) { + @autoreleasepool { + if (argc != 3) { + printf("usage: %s \n", argv[0]); + return 2; + } + BOOL written = [@(argv[1]) isEqual:@"written"]; + NSError *error = nil; + NSString *source = [NSString stringWithContentsOfFile:@(argv[2]) + encoding:NSUTF8StringEncoding + error:&error]; + if (!source) fail(@"source", error); + id device = MTLCreateSystemDefaultDevice(); + id library = [device newLibraryWithSource:source options:nil error:&error]; + if (!library) fail(@"library", error); + printf("%s on %s, %s\n", argv[1], device.name.UTF8String, + [NSProcessInfo processInfo].operatingSystemVersionString.UTF8String); + id executing = [device newCommandQueue]; + id writing = [device newCommandQueue]; + id event = [device newSharedEvent]; + id good = stateOf(device, library, MTLPixelFormatRGBA8Unorm); + id other = stateOf(device, library, MTLPixelFormatRGBA16Float); + id writer = [device + newComputePipelineStateWithFunction:[library newFunctionWithName:@"irw_encode_draw"] + error:&error]; + if (!writer) fail(@"draw writer", error); + MTLIndirectCommandBufferDescriptor *commands = [MTLIndirectCommandBufferDescriptor new]; + commands.commandTypes = MTLIndirectCommandTypeDraw; + commands.inheritPipelineState = NO; + commands.inheritBuffers = NO; + commands.maxVertexBufferBindCount = 1; + commands.maxFragmentBufferBindCount = 0; + id icb = + [device newIndirectCommandBufferWithDescriptor:commands maxCommandCount:1 options:0]; + float corners[12] = {-1, -1, 0, 1, 3, -1, 0, 1, -1, 3, 0, 1}; + id cornerBuffer = [device newBufferWithBytes:corners + length:sizeof corners + options:MTLResourceStorageModeShared]; + id cpu = [icb indirectRenderCommandAtIndex:0]; + [cpu setRenderPipelineState:other]; + [cpu setVertexBuffer:cornerBuffer offset:0 atIndex:0]; + [cpu drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3 instanceCount:1 + baseInstance:0]; + MTLResourceID ids[2] = {icb.gpuResourceID, good.gpuResourceID}; + id table = [device newBufferWithBytes:ids + length:sizeof ids + options:MTLResourceStorageModeShared]; + MTLTextureDescriptor *targetDescriptor = + [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm + width:16 + height:16 + mipmapped:NO]; + targetDescriptor.usage = MTLTextureUsageRenderTarget; + targetDescriptor.storageMode = MTLStorageModeShared; + id target = [device newTextureWithDescriptor:targetDescriptor]; + + // X: waits for the event, then executes command 0; committed first. + id x = [executing commandBuffer]; + [x encodeWaitForEvent:event value:1]; + MTLRenderPassDescriptor *pass = [MTLRenderPassDescriptor renderPassDescriptor]; + pass.colorAttachments[0].texture = target; + pass.colorAttachments[0].loadAction = MTLLoadActionClear; + pass.colorAttachments[0].clearColor = MTLClearColorMake(1, 0, 0, 1); + pass.colorAttachments[0].storeAction = MTLStoreActionStore; + id render = [x renderCommandEncoderWithDescriptor:pass]; + [render useResource:icb + usage:MTLResourceUsageRead | MTLResourceUsageWrite + stages:MTLRenderStageVertex | MTLRenderStageFragment]; + [render useResource:cornerBuffer usage:MTLResourceUsageRead stages:MTLRenderStageVertex]; + [render executeCommandsInBuffer:icb withRange:NSMakeRange(0, 1)]; + [render endEncoding]; + [x commit]; + + // Y: on the other queue, writes command 0 again (or not), then signals. + id y = [writing commandBuffer]; + if (written) { + id compute = [y computeCommandEncoder]; + [compute useResource:icb usage:MTLResourceUsageWrite]; + [compute setComputePipelineState:writer]; + [compute setBuffer:table offset:0 atIndex:0]; + [compute setBuffer:cornerBuffer offset:0 atIndex:1]; + [compute dispatchThreads:MTLSizeMake(1, 1, 1) + threadsPerThreadgroup:MTLSizeMake(1, 1, 1)]; + [compute endEncoding]; + } + [y encodeSignalEvent:event value:1]; + [y commit]; + [y waitUntilCompleted]; + [x waitUntilCompleted]; + uint8_t texel[4] = {0}; + [target getBytes:texel bytesPerRow:64 fromRegion:MTLRegionMake2D(8, 8, 1, 1) mipmapLevel:0]; + printf("X: status %ld error %s; centre texel %u %u %u %u\n", (long)x.status, + x.error ? x.error.localizedDescription.UTF8String : "none", texel[0], texel[1], + texel[2], texel[3]); + printf("Y: status %ld error %s\n", (long)y.status, + y.error ? y.error.localizedDescription.UTF8String : "none"); + printf("DONE\n"); + } + return 0; +} diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index a4152815a..7e325d2ca 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -1722,7 +1722,9 @@ impl State { retained, pipelines, bound, + held, } = prepared; + segment.host |= held; segment.gpu_alone = for_good && recorded.is_some(); segment.bound = bound; segment.recorded = recorded; diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index 2195738d8..57efbc67b 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -21,6 +21,7 @@ use super::shadow::GatedCopyIn; use super::sparse::emulated::Scrub; use super::tracker::Summary; use super::Device; +use super::IndirectCommandBuffer; use crate::pipeline::budget::Urgency; use std::any::Any; use std::sync::Arc; @@ -103,6 +104,27 @@ pub(super) struct Prepared { /// Where its host step records it for what the GPU may write, what the step's recording may /// use that Metal orders (`Segment::bound`). pub(super) bound: Option>, + /// `commit`'s recording of it was refused, though a route met later may write the records it + /// read first ([`Deferred::prepare`]): its host step records it once the work before it + /// completed (`Segment::host`). + pub(super) held: bool, +} + +/// Whether `commit`'s refused recording of an execution of `executed`, buffers read from the CPU's +/// records, is held for its host step: where its command buffer made one of them resident for +/// writing (`residency`, its), as a route met after the commit may still write the records before +/// the work runs (another queue's command buffer it waits for through an event, encoded after this +/// commit: the probe `crates/metal2vulkan-conformance/probes/icb_cross_queue_writes.m`), and Metal +/// runs what that route wrote. The step records the work from the records as they stand once the +/// work before it completed, and fails the command buffer, at the batch's submission, only where +/// they are still refused (`WorkCounts::commit_refusals_held`). A refusal of another buffer's +/// records stands at `commit`. +fn held<'a>( + residency: &crate::residency::Residency, + executed: impl IntoIterator, +) -> bool { + let writable = residency.writable_indirect_command_buffers(); + executed.into_iter().any(|icb| writable.contains(icb)) } impl Deferred { @@ -208,6 +230,7 @@ impl Deferred { retained, pipelines: false, bound: None, + held: false, }); } let residency = command_buffer.residency()?.kernel(); @@ -220,10 +243,33 @@ impl Deferred { retained: Some(Box::new(variants)), pipelines: false, bound: execute.bound(&residency), + held: false, }) } Deferred::Execute(execute) => { - let recorded = execute.record(command_buffer, None)?; + let recorded = match execute.record(command_buffer, None) { + Ok(recorded) => recorded, + // Held for its host step (`held`). + Err(error) => { + let residency = command_buffer.residency()?; + if !held(&residency, [&execute.icb]) { + return Err(error); + } + device.shared().counts.commit_refusal_held(); + let residency = residency.kernel(); + let Settled { states, variants } = + execute.settle(device, execute.states(device), &residency); + return Ok(Prepared { + recorded: None, + for_good: false, + inputs: StepInputs::Settled(states), + retained: Some(Box::new(variants)), + pipelines: false, + bound: execute.bound(&residency), + held: true, + }); + } + }; let residency = command_buffer.residency()?.kernel(); let unforeseen = Unforeseen::new(device, execute, residency); execute.icb.watch(&unforeseen); @@ -234,6 +280,7 @@ impl Deferred { retained: None, pipelines: false, bound: None, + held: false, }) } Deferred::Dispatch(dispatch) if step => Ok(Prepared { @@ -245,6 +292,7 @@ impl Deferred { )), pipelines: false, bound: None, + held: false, }), Deferred::Dispatch(_) => Err(internal( "an indirect dispatch recorded before the work it waits for completed", @@ -257,6 +305,7 @@ impl Deferred { retained: None, pipelines: false, bound: None, + held: false, }) } // Recorded now for good where every execution whose records the GPU may write runs @@ -274,6 +323,7 @@ impl Deferred { retained: None, pipelines: false, bound: None, + held: false, }); } pass.make_ahead(command_buffer); @@ -284,6 +334,7 @@ impl Deferred { retained: Some(Box::new(pass.settle(command_buffer))), pipelines: pass.making() || pass.failed(), bound: pass.bound(device, &command_buffer.residency()?), + held: false, }) } // A pass of draws whose pipelines are being made, or one of which failed, is @@ -302,15 +353,38 @@ impl Deferred { retained: None, pipelines: true, bound: None, + held: false, }); } + let recorded = match pass.record(command_buffer, false) { + Ok(recorded) => recorded, + // Held for its host step (`held`), as a step's pass is prepared above. + Err(error) => { + let residency = command_buffer.residency()?; + if !held(&residency, pass.executed()) { + return Err(error); + } + device.shared().counts.commit_refusal_held(); + pass.make_ahead(command_buffer); + return Ok(Prepared { + recorded: None, + for_good: false, + inputs: StepInputs::RenderPass, + retained: Some(Box::new(pass.settle(command_buffer))), + pipelines: false, + bound: pass.bound(device, &residency), + held: true, + }); + } + }; Ok(Prepared { - recorded: Some(pass.record(command_buffer, false)?), + recorded: Some(recorded), for_good: false, inputs: StepInputs::RenderPass, retained: None, pipelines: false, bound: None, + held: false, }) } // Its host step reads the unit's halt word once the laying completed. @@ -321,6 +395,7 @@ impl Deferred { retained: None, pipelines: false, bound: None, + held: false, }), // Recorded now where its pipelines are made; else by a host step once they are, // which makes again one whose making failed. @@ -336,6 +411,7 @@ impl Deferred { retained: None, pipelines: later, bound: None, + held: false, }) } } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 8d95095b0..0407ac091 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -2519,6 +2519,7 @@ impl EncoderCore { segment.recorded = prepared.recorded; segment.inputs = Some(prepared.inputs); segment.pipelines = prepared.pipelines; + segment.host |= prepared.held; continue; } let recorded = segment.work.record_on_gpu(&open.command_buffer)?; diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index 8098b0121..e692bf9fd 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -2873,6 +2873,11 @@ impl DeferredPass { .any(|execution| execution.icb.gpu_written() || execution.range.indirect()) } + /// The indirect command buffers its executions run. + pub(crate) fn executed(&self) -> impl Iterator { + self.executions.iter().map(|execution| &execution.icb) + } + /// Whether a pipeline one of its draws or tile dispatches records is still being made, or one /// its executions' settle handed to the device's pool ([`settle`](Self::settle)). pub(crate) fn making(&self) -> bool { diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index dd09fbd64..65f50c99e 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -101,6 +101,7 @@ pub(crate) struct Counters { host_step_chunks_recorded_again: AtomicU64, host_step_records_compared: AtomicU64, host_step_compare_nanos: AtomicU64, + commit_refusals_held: AtomicU64, creation_pipelines_made: AtomicU64, creations_left_making: AtomicU64, creation_pipelines_drawn: AtomicU64, @@ -1293,6 +1294,12 @@ impl Counters { ); } + /// A commit's refused recording of an execution of indirect commands was held for its host + /// step (`deferred.rs`, `held`). + pub(crate) fn commit_refusal_held(&self) { + self.commit_refusals_held.fetch_add(1, Ordering::Relaxed); + } + /// A state's creation made a `VkPipeline` of `predicted` (`pipeline/predicted.rs`, /// `pipeline/dispatch_making.rs`): counted in both the whole count and its prediction's. pub(crate) fn creation_pipeline_made(&self, predicted: Predicted) { @@ -3788,6 +3795,13 @@ pub struct WorkCounts { /// The time those comparisons took, in nanoseconds: part of /// [`host_step_nanos`](Self::host_step_nanos). pub host_step_compare_nanos: u64, + /// Segments whose recording at `commit` was refused, of an execution of an indirect command + /// buffer the command buffer made resident for writing, held for a host step, one each + /// (`deferred.rs`): a route met after the commit (another queue's command buffer the work + /// waits for) may write the records first, as Metal runs what it wrote. The step records the + /// work once the work before it completed, and fails the command buffer only where the records + /// are still refused. + pub commit_refusals_held: u64, /// `VkPipeline`s states' creations made: each render state's predicted key /// (`pipeline/predicted.rs`), and each compute state's predicted region /// (`pipeline/dispatch_making.rs`). @@ -6046,6 +6060,7 @@ impl Device { .load(Ordering::Relaxed), host_step_records_compared: counters.host_step_records_compared.load(Ordering::Relaxed), host_step_compare_nanos: counters.host_step_compare_nanos.load(Ordering::Relaxed), + commit_refusals_held: counters.commit_refusals_held.load(Ordering::Relaxed), creation_pipelines_made: counters.creation_pipelines_made.load(Ordering::Relaxed), creations_left_making: counters.creations_left_making.load(Ordering::Relaxed), creation_pipelines_drawn: counters.creation_pipelines_drawn.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/write_routes.rs b/crates/metal2vulkan-validation/src/runtime_lane/write_routes.rs index ef135775f..20dedf0f1 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/write_routes.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/write_routes.rs @@ -20,6 +20,10 @@ //! buffer that inherits the encoder's state may run on the GPU, as draws of the one primitive type //! the summary allows (`bind::draw_replay_primitive_type`), the CPU's triangle here, unless the //! summary holds the kernel's point too. +//! +//! [`a_refused_command_another_queue_writes_again_runs_what_it_wrote`]: a command the runtime +//! refuses at commit, which a later command buffer of another queue writes again before the +//! execution runs, runs what that one wrote, as Metal's does. use super::degrade_notices::on_device; use super::{buffer_with, read_buffer, WAIT}; @@ -32,10 +36,10 @@ use metal2vulkan::pipeline::{ }; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ - Buffer, ClearColor, CommandBuffer, CommandBufferStatus, ComputePipelineState, Device, + Buffer, ClearColor, CommandBuffer, CommandBufferStatus, ComputePipelineState, Device, EventRef, IndirectCommandBuffer, IndirectCommandBufferDescriptor, Library, LoadAction, PipelineOptions, Region, RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, - StoreAction, TextureDescriptor, + StoreAction, Texture, TextureDescriptor, }; /// Where the command buffer makes the indirect command buffer resident for writing. @@ -125,10 +129,14 @@ impl Scene { /// A render state of `vertex` and `irw_fragment` that indirect command buffers may run. fn render_state(&self, vertex: &str) -> RenderPipelineState { + self.render_state_in(vertex, PixelFormat::RGBA8Unorm) + } + + /// [`render_state`](Self::render_state), drawing into `format`. + fn render_state_in(&self, vertex: &str, format: PixelFormat) -> RenderPipelineState { let mut descriptor = RenderPipelineDescriptor::new(self.function(vertex)); descriptor.fragment = Some(self.function("irw_fragment")); - descriptor.color_attachments[0] = - Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(format)); descriptor.support_indirect_command_buffers = true; (self.device) .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) @@ -143,6 +151,18 @@ impl Scene { encode: impl FnOnce(&mut RenderCommandEncoder), at: [(u64, u64); N], ) -> [[u8; 4]; N] { + let (target, pass) = self.target(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encode(&mut encoder); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + texels(&target, at) + } + + /// A new target cleared red, and a pass over it. + fn target(&self) -> (Texture, RenderPassDescriptor) { let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); target.usage = TextureUsage::RENDER_TARGET; target.resource_options = ResourceOptions::shared(); @@ -153,18 +173,7 @@ impl Scene { color.load_action = LoadAction::Clear; color.clear_color = ClearColor::new(1.0, 0.0, 0.0, 1.0); color.store_action = StoreAction::Store; - let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); - encode(&mut encoder); - encoder.end_encoding().unwrap(); - command_buffer.commit().unwrap(); - command_buffer.wait_until_completed_for(WAIT).unwrap(); - assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); - at.map(|(x, y)| { - let mut texel = [0u8; 4]; - let region = Region::new_2d(x, y, 1, 1); - target.get_bytes(&mut texel, 4, 0, region, 0, 0).unwrap(); - texel - }) + (target, pass) } /// The render command's run, as `resident` says: the target's centre texel. @@ -267,6 +276,16 @@ impl Scene { } } +/// `target`'s texels at `at`. +fn texels(target: &Texture, at: [(u64, u64); N]) -> [[u8; 4]; N] { + at.map(|(x, y)| { + let mut texel = [0u8; 4]; + let region = Region::new_2d(x, y, 1, 1); + target.get_bytes(&mut texel, 4, 0, region, 0, 0).unwrap(); + texel + }) +} + /// Points `(x, y)` as `float4(x, y, 0, 1)`, in a new buffer. fn floats(device: &Device, points: &[f32]) -> Buffer { let bytes: Vec = (points.chunks(2)) @@ -333,3 +352,69 @@ fn an_execution_after_its_writer_runs_what_metal_runs() { assert_eq!(seen, expected, "{steps}"); }); } + +/// A render command the CPU wrote with a state that draws into another color format than the +/// pass's target, which the runtime refuses at commit, executed by a command buffer that waits for +/// an event and is committed first, its render encoder making the buffer resident for reading and +/// writing; then, on another queue, a command buffer whose kernel writes the command again (the +/// valid state, taken from its argument buffer) and which signals the event. Metal runs the +/// kernel's command (the probe `crates/metal2vulkan-conformance/probes/icb_cross_queue_writes.m`, +/// `written`, on an M3 Max, macOS 27.0.1: both complete, the target's centre green), so the first +/// commit holds its refusal for the host step (`WorkCounts::commit_refusals_held`), which records +/// the kernel's command once the writer completed: both complete, the centre green. +#[test] +fn a_refused_command_another_queue_writes_again_runs_what_it_wrote() { + on_device(|device, _| { + let scene = Scene::new(device); + let state = scene.render_state("irw_vertex"); + let other = scene.render_state_in("irw_vertex", PixelFormat::RGBA16Float); + let writer = scene.kernel("irw_encode_draw", false); + let mut commands = IndirectCommandBufferDescriptor::new(); + commands.command_types = IndirectCommandType::DRAW; + commands.max_vertex_buffer_bind_count = 1; + let icb = device + .new_indirect_command_buffer(&commands, 1, ResourceOptions::shared()) + .unwrap(); + let corners = floats(device, &[-1.0, -1.0, 3.0, -1.0, -1.0, 3.0]); + let cpu = icb.indirect_render_command_at(0).unwrap(); + cpu.set_render_pipeline_state(&other).unwrap(); + cpu.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + cpu.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + let table = scene.table(&icb, state.gpu_resource_id().0); + let (executing, writing) = ( + device.new_command_queue().unwrap(), + device.new_command_queue().unwrap(), + ); + let event = device.new_shared_event().unwrap(); + let before = device.work_counts().commit_refusals_held; + let executes = executing.command_buffer().unwrap(); + executes + .encode_wait_for_event(EventRef::from(&event), 1) + .unwrap(); + let (target, pass) = scene.target(); + let mut encoder = executes.render_command_encoder(&pass).unwrap(); + let both = ResourceUsage::READ | ResourceUsage::WRITE; + let stages = RenderStages::VERTEX | RenderStages::FRAGMENT; + (encoder.use_resource(icb.as_resource(), both, stages)).unwrap(); + let vertex = RenderStages::VERTEX; + (encoder.use_resource(corners.as_resource(), ResourceUsage::READ, vertex)).unwrap(); + encoder.execute_commands_in_buffer(&icb, 0..1).unwrap(); + encoder.end_encoding().unwrap(); + executes.commit().unwrap(); + let held = device.work_counts().commit_refusals_held - before; + let writes = writing.command_buffer().unwrap(); + Scene::write(&writes, Resident::Same, (&writer, &table, &corners), &icb); + writes + .encode_signal_event(EventRef::from(&event), 1) + .unwrap(); + writes.commit().unwrap(); + for command_buffer in [&writes, &executes] { + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + } + assert_eq!(held, 1, "the commit held its refusal for the host step"); + let [centre] = texels(&target, [(SIDE / 2, SIDE / 2)]); + assert_eq!(centre, [0, 255, 0, 255], "the kernel's command ran"); + }); +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index d9a008a36..625492c39 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2547,6 +2547,7 @@ field metal2vulkan-runtime::WorkCounts.command_buffers_unsubmitted pub command_b field metal2vulkan-runtime::WorkCounts.command_pools_made pub command_pools_made: u64 field metal2vulkan-runtime::WorkCounts.commands_noted_as_before pub commands_noted_as_before: u64 field metal2vulkan-runtime::WorkCounts.commands_recorded pub commands_recorded: CommandsRecorded +field metal2vulkan-runtime::WorkCounts.commit_refusals_held pub commit_refusals_held: u64 field metal2vulkan-runtime::WorkCounts.commits_handed_off pub commits_handed_off: u64 field metal2vulkan-runtime::WorkCounts.commits_taken_in pub commits_taken_in: u64 field metal2vulkan-runtime::WorkCounts.completed_waits pub completed_waits: u64 diff --git a/docs/API.md b/docs/API.md index a93851464..3952ea687 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3895,7 +3895,12 @@ each item named states the rule in full. - **A render execution records its pass at commit**, from the records as they stand then, as Metal's does. - **A command's refusal is one typed error wherever it is recorded**: the CPU's records are checked - as `commit` records them, and `commit` returns what a command refuses. + as `commit` records them, and `commit` returns what a command refuses; but for a buffer the + command buffer made resident for writing, as a route met after the commit may still write the + records before they run (another queue's command buffer the work waits for through an event, + whose writes Metal runs), the host step records them once the work before it completed, and the + command buffer fails at that batch's submission only where they are still refused + (`WorkCounts::commit_refusals_held`). - **A render execution's range read from a buffer is read before its pass** (`execute_commands_in_buffer_indirect`). - **An indirect command's buffer outside the resident resources misses**: its Metal address