From 5410cd5cf4cb9ff1610d93fd132d318b3588fd8e Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 16 Nov 2026 05:23:18 -0800 Subject: [PATCH] RUNTIME 2450: Shadows: a rebind encodes the encoder of a gated copy in again An encoder that left a shadow's copy in to its batch's submission (Deferred::GatedCopyIn: over host pages a consumer logs, the regions its log decides; or a command buffer's first copy in of a shadow that may stand across command buffers) kept no log (Unlogged::Segments): no Segment::records_again test held for it. A rebind, before the command buffer's first submission, of a buffer over host pages that encoder used then failed the command buffer with EncodedUseRebound, where Metal resolves the use at the submission. Keeping the log alone would not do: the encoding again redoes the copy in for itself (a gate of the log taken again, a standing decided at the submission, ended_encoders_wrote answering false while replaying) and leaves a GatedCopyIn of its own, or records the copy in in place, but finish_replay asked every other segment to record on the GPU alone, which a gated copy in does not, and refused the encoding again. Now Deferred::left_again_by_an_encoding_again answers for GatedCopyIn too: the encoder keeps its log, its place takes the encoding again (splice_fits), finish_replay prepares the encoding again's segment as the commit prepares one (no recording, StepInputs::None), and the batch's submission records it (submit.rs's record_scrubs, which takes every unrecorded such segment). The first's goes unrun, retained. A gated copy in made by the encoding again holds a gate of the log made after the commit's decisions (DirtyShadows::committed), whose decision is none, so it copies every region (CopyInGate::regions): a superset of the rows the log reports changed, read at the submission, after every CPU write before the commit; the shadow's hold was advanced to the commit's stamp by the first gate's decision, and its image then holds at least that. Its cost, one whole copy in, falls only on a rebind of such an encoder. A standing gate is decided at the submission (stands), as the first's would be. GPU parts are unchanged: a gated copy in starts none. Unlogged::Segments now names a GPU-written indirect dispatch's host step and a scrub. Docs: deferred.rs, rebound_use.rs, encoder.rs, reencode.rs, shadow.rs (GatedCopyIn). Test: dirty_pages_device's a_rebind_before_the_first_submission_encodes_a_gated_copy_in_s_encoder_again: a kernel inverts a shadowed RGBA8 texture over a logged no-copy buffer into a plain texture, behind a shared event only the host signals; the buffer is detached and rebound over other pages, logged by the same log, before the signal. Asserts the command buffer completes with no error, the rebind encoded the encoder once, one gated copy in ran (the encoding again's) and copied every row (dirty_copies_in_gated +1, dirty_copies_in_whole +1), and the kernel read the new pages' texels. At development's files it is expected to fail on the error (EncodedUseRebound). Degradation kinds added or removed: none. Verified: m3-max-36334 at a7b5d28822 (same tree), clippy -D warnings of the runtime (all targets and features) 0. Rustdoc, the cfg clippy, both controls, the rebind tests and the touched suites run after the merge. --- .../src/command_buffer/rebound_use.rs | 3 +- .../src/command_buffer/reencode.rs | 10 +- crates/metal2vulkan-runtime/src/deferred.rs | 13 ++- crates/metal2vulkan-runtime/src/encoder.rs | 20 ++-- crates/metal2vulkan-runtime/src/shadow.rs | 4 +- .../src/tests/dirty_pages_device.rs | 99 +++++++++++++++++++ crates/metal2vulkan/src/cache/mod.rs | 2 +- 7 files changed, 129 insertions(+), 22 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs b/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs index 5223755de..15e0c94bc 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/rebound_use.rs @@ -14,8 +14,7 @@ pub(crate) enum Unlogged { /// (`predication.rs`), or one of a kind that logs none (a resource state encoder's). NoCalls, /// It left work for later that an encoding again does not record at once: a GPU-written - /// indirect dispatch's host step, a scrub, or a shadow's copy in left to its batch's - /// submission (`shadow::GatedCopyIn`) (`Segment::records_again`). + /// indirect dispatch's host step, or a scrub (`Segment::records_again`). Segments, /// The command buffer's failure fails it, or a fault of its own, as it commits. Fails, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 2e1f44f43..704f51241 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -673,7 +673,9 @@ impl State { /// imports would not copy it, `host_ram/copy.rs`), or a splice's or a merge on the host's CPU /// part (which goes, the encoding again leaving its own over the new pages, /// `shadow_splice.rs`), or a staged scatter's steps (which go, the encoding again staging it - /// again, `host_ram/copy.rs`), or its group was submitted, or the command buffer completed. + /// again, `host_ram/copy.rs`), or a shadow's gated copy in (which goes, the encoding again + /// copying in for itself, `shadow::GatedCopyIn`), or its group was submitted, or the command + /// buffer completed. pub(super) fn splice_replay( &mut self, at: usize, @@ -713,9 +715,9 @@ impl State { recorded.raws = raws; recorded.summary = summary; // Its first segments go: the encoding again left a segment of its own in each - // pending dispatch's, each splice's or merge on the host's and each staged copy - // step's place it staged again, and its work on the GPU alone in segments of its - // own, and recorded each other staged gather's copy at once. + // pending dispatch's, each splice's or merge on the host's, each staged copy step's it + // staged again and each gated copy in's place, and its work on the GPU alone in + // segments of its own, and recorded each other staged gather's copy at once. // What the commit recorded of one stays retained, never submitted, as the first // recording does. for segment in recorded.segments.drain(..) { diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index 0adf465c5..abfcd455b 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -585,12 +585,17 @@ impl Deferred { /// copy in a part of its own as the first's; and a staged gather the imports would not copy /// as the first staged it (over a chunk that takes no import, or in a part of its own: /// `StagedGather::encoded_again_through_imports`), staged again so (`host_ram/copy.rs`'s - /// `HostRamCall::staged_again`). The first's go unrun. + /// `HostRamCall::staged_again`); and a shadow's copy in left to its batch's submission + /// (`shadow::GatedCopyIn`), which the encoding again's copy in leaves again, gated as it + /// decides then (or records in place, where it decides to copy every texel): its gate of a + /// log, made after the commit's decisions (`DirtyShadows::committed`), holds no stamp and + /// copies every region (`CopyInGate::regions`). The first's go unrun. pub(super) fn left_again_by_an_encoding_again(&self) -> bool { match self { - Deferred::ShadowSplice(_) | Deferred::ScatterStage(_) | Deferred::ScatterDrain(_) => { - true - } + Deferred::ShadowSplice(_) + | Deferred::ScatterStage(_) + | Deferred::ScatterDrain(_) + | Deferred::GatedCopyIn(_) => true, Deferred::GatherStage(gather) => !gather.encoded_again_through_imports(), _ => false, } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 7a7ca530a..938313689 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -312,10 +312,10 @@ impl Segment { /// run's pass's merge, which the pass encoded again records after itself as a pass alone /// does, leaving its run (`pass_runs.rs`), a staged gather, which the encoding again /// copies through the imports in its place (`Deferred::recorded_by_an_encoding_again`), or a - /// splice's or a merge on the host's CPU part, a staged scatter's steps, or a staged gather - /// the imports would not copy, which the encoding again leaves again over the new pages - /// (`Deferred::left_again_by_an_encoding_again`). Its log is kept only where every segment - /// does. + /// splice's or a merge on the host's CPU part, a staged scatter's steps, a staged gather the + /// imports would not copy, or a shadow's gated copy in, which the encoding again leaves again + /// over the new pages (`Deferred::left_again_by_an_encoding_again`). Its log is kept only + /// where every segment does. pub(super) fn records_again(&self) -> bool { self.pends() || self.work.may_run_on_gpu_alone() @@ -4164,8 +4164,8 @@ impl EncoderCore { /// place (`State::splice_replay`), in its parts, each segment it left recorded at once on the /// GPU alone but one whose pipelines are being made or failed to make, left as the first /// encoding left it ([`Segment::keeps_pipelines`]), and a splice's or a merge on the host's - /// CPU part and a staged copy's steps, left for their host steps - /// (`Deferred::left_again_by_an_encoding_again`). Refused + /// CPU part and a staged copy's steps, left for their host steps, and a shadow's gated copy + /// in, left for its batch's submission (`Deferred::left_again_by_an_encoding_again`). Refused /// (internal) where the encoder, encoded again, failed or faulted its command buffer, or met a /// detached buffer, which its first encoding kept none of, or left work that no longer runs on /// the GPU alone: its place stays as it was. @@ -4228,8 +4228,8 @@ impl EncoderCore { } // Its segments recorded at once on the GPU alone, as its commit recorded the first // encoding's (`command_buffer/reencode.rs`): work that no longer runs there refuses the - // encoding again, but work whose pipelines are being made, a splice's CPU part and a - // staged copy's steps, which keep their segments. + // encoding again, but work whose pipelines are being made, a splice's CPU part, a + // staged copy's steps and a gated copy in, which keep their segments. let mut parts = Vec::with_capacity(split.len()); for ((raws, mut segments), summary) in split.into_iter().zip(summaries) { for segment in &mut segments { @@ -4248,8 +4248,8 @@ impl EncoderCore { } // A splice's or a merge on the host's CPU part, planned again over the pages the // buffer lies in now, and a staged copy's steps, staged again from there, are - // left for their host steps as the commit left the first's - // (`Deferred::left_again_by_an_encoding_again`). + // left for their host steps as the commit left the first's, and a gated copy in + // for its batch's submission (`Deferred::left_again_by_an_encoding_again`). if segment.work.left_again_by_an_encoding_again() { let prepared = segment.work.prepare(&open.command_buffer, segment.host)?; segment.recorded = prepared.recorded; diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index 264feb937..e4206843e 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -1668,7 +1668,9 @@ pub(super) enum Step { /// stand across command buffers (`shadow_standing.rs`) moves nothing where the image stands as /// the batch is submitted, in the scheduler's order. Recorded in a command buffer of its own /// between the encoder's, behind a barrier from everything before it and before one to -/// everything after it, so it keeps its place among the encoder's commands. +/// everything after it, so it keeps its place among the encoder's commands. A rebind's encoding +/// again of its encoder copies in for itself, its own such copy in in this one's place, gated as +/// it decides then (`Deferred::left_again_by_an_encoding_again`); this one goes unrun. pub(super) struct GatedCopyIn { copy: ShadowCopy, gate: CopyGate, diff --git a/crates/metal2vulkan-runtime/src/tests/dirty_pages_device.rs b/crates/metal2vulkan-runtime/src/tests/dirty_pages_device.rs index a1d8447a7..89ae7a847 100644 --- a/crates/metal2vulkan-runtime/src/tests/dirty_pages_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/dirty_pages_device.rs @@ -63,6 +63,10 @@ //! log among them, and a wait the log answers `false` is not made again for them //! (`WorkCounts::dirty_waits`). //! +//! A rebind, before the first submission, of the logged buffer a kernel's shadowed texture lies +//! over encodes the kernel's encoder again: its own gated copy in replaces the first, copies +//! every row (its gate holds no stamp of the commit's) and reads the new pages. +//! //! A render target over such pages, loaded by a pass whose draws' scissor bounds them to rows 0 //! to 8, copies in every texel the first time and then only the rows the log reports changed: its //! copy in is not cut to the scissor, so the image holds every texel for the next command buffer, @@ -383,6 +387,101 @@ fn a_logged_shadow_copies_in_only_the_changed_rows() { drop(device); } +/// A gated copy in leaves its encoder's log in place (`Deferred::left_again_by_an_encoding_again`): +/// a kernel reads the shadowed texture over the logged buffer behind a shared event only the host +/// signals, and the buffer is rebound before the signal over other pages, logged by the same log: +/// the rebind encodes the encoder again, whose copy in, gated by a gate made after the commit's +/// decisions, copies every row of the new pages; the first encoding's copy in goes unrun. The +/// kernel reads the new pages' texels. +#[test] +fn a_rebind_before_the_first_submission_encodes_a_gated_copy_in_s_encoder_again() { + let scratch = Scratch::new("dirty-pages-rebind"); + // Declared before the device, so dropped after it. + let (host, moved_to) = (Host::new(), Host::new()); + let device = device(&scratch.0); + let log = Arc::new(Log::default()); + let Some(buffer) = over_logged(&device, &host, &log) else { + return; + }; + host.fill(0x1010_1010); + moved_to.fill(0x4040_4040); + let shadows = device.work_counts().shadowed_textures; + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + let source = buffer.new_texture(&descriptor, 0, ROW).unwrap(); + let shadowed = device.work_counts().shadowed_textures - shadows; + let mut plain = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false); + plain.usage = TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE; + plain.resource_options = ResourceOptions::shared(); + let target = device.new_texture(&plain).unwrap(); + let invert = state(&device, "invert_texels"); + eprintln!("DIRTY-PAGES-REBIND: {shadowed} shadow made"); + if shadowed == 0 { + return; + } + // Its command buffer waits for an event only the host signals, below: the rebind comes + // before its first submission. + let gate = device.new_shared_event().unwrap(); + let before = counts(&device); + let encoding = device.work_counts(); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + (command_buffer.encode_wait_for_event(EventRef::Shared(&gate), 1)).unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&invert).unwrap(); + encoder.set_texture(Some(&source), 0).unwrap(); + encoder.set_texture(Some(&target), 1).unwrap(); + encoder + .dispatch_threads(Size::new(SIDE, SIDE, 1), Size::new(8, 8, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + assert_eq!(buffer.detach_backing(), Ok(true), "the detach"); + // SAFETY: the pages outlive every buffer over them (dropped after the device), and only the + // buffer's commands and the test use them while it lives. + let memory = unsafe { moved_to.memory() }.with_dirty_pages(Arc::clone(&log)); + // SAFETY: as above. + unsafe { buffer.rebind_bytes_no_copy(memory, None, None) }.unwrap(); + let rebound = device.work_counts(); + gate.set_signaled_value(1); + assert!(command_buffer.wait_until_completed_for(WAIT).is_ok()); + let moved = delta(&device, before); + println!( + "DIRTY-PAGES-REBIND {}: {:?} {:?}; encoders encoded again {}, refused {}; (gated, whole, \ + skipped, bytes whole, copied) {moved:?}", + device.name(), + command_buffer.status(), + command_buffer.error(), + rebound.encoders_reencoded - encoding.encoders_reencoded, + rebound.reencodes_refused - encoding.reencodes_refused, + ); + assert_eq!( + (command_buffer.status(), command_buffer.error()), + (CommandBufferStatus::Completed, None) + ); + assert_eq!( + rebound.encoders_reencoded - encoding.encoders_reencoded, + 1, + "the rebind encoded the encoder again" + ); + assert_eq!( + (moved[0], moved[1]), + (1, 1), + "one gated copy in ran, the encoding again's, and copied every row" + ); + let inverted = |value: u8| [255 - value, 255 - value, 255 - value, value]; + for row in [0, 10, SIDE - 1] { + assert_eq!( + texel(&target, row), + inverted(0x40), + "row {row} read from the pages the buffer lies in now" + ); + } + drop(source); + drop(buffer); + drop(device); +} + /// One pass over `target` that loads it and draws `color` over every pixel inside rows 0 to 8 (the /// scissor), to completion. fn draw_in_scissor(device: &Device, target: &Texture, color: [f32; 4]) { diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index e4e88a7eb..04b613f46 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2449; +pub const RUNTIME_VERSION: u32 = 2450; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles