From fb183b48f73de54a73d33c58df0507b5fb25bbcc Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 19 Nov 2026 12:22:35 -0800 Subject: [PATCH] player: the old backend gives a no-copy Managed buffer of a two-copy stream with no identity its writes before first use The new runtime's backend plays a stream with no identity record under --managed two-copy by its first-use rule. A no-copy Managed buffer made with no bytes is fresh until the command buffer that first names it commits, and a write into it while fresh reaches its GPU copy too (did_modify_range). That write is the nearest record the stream has of the buffer's bytes at its making (docs/REPLAY-STREAM.md, Managed buffers). The old backend had no such rule. Those writes reached only its CPU copy, so on a device that keeps two copies its GPU copy read zeros where the new runtime's read the bytes. The old backend now follows the same rule. It notes each encoder's command buffer, marks a buffer's first use when an encoder names it, drops the mark at that command buffer's commit, and announces a fresh buffer's writes. Its managed line counts the buffers whose contents came from first use, as the new runtime's does. docs/REPLAY-STREAM.md states the two-copy rule for both runtimes: which writes before first use reach the GPU copy, and what an identity record changes. Found by a synthetic stream of our own on the RX 550 (m3-max-53813): with no identity record under --managed two-copy, rt read the write and old read zeros. Recordings it touches: gb-3090-r2 (641 Managed objects read without them, the first in frame 0) and windrag-780m-b2 (15), where played as two copies. Test: a_two_copy_stream_with_no_identity_gives_a_no_copy_buffer_its_writes_ before_first_use (replay_streams), which fails without the fix on a device that keeps two copies. The made-with test's managed line now carries the count. --- .../src/replay/new_runtime/mod.rs | 2 +- .../src/replay/old_runtime/descriptors.rs | 25 +++-- .../src/replay/old_runtime/mod.rs | 94 ++++++++++++++++++- .../src/runtime_lane/replay_streams.rs | 70 +++++++++++++- docs/REPLAY-STREAM.md | 9 +- 5 files changed, 176 insertions(+), 24 deletions(-) diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index d71d352be..130fd99b4 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -391,7 +391,7 @@ pub struct NewRuntime { } /// The objects `values` name, lists included. -fn objects_named(values: &[Value], out: &mut Vec) { +pub(super) fn objects_named(values: &[Value], out: &mut Vec) { for value in values { match value { Value::Object(id) => out.push(*id), diff --git a/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs b/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs index b63d67376..1a40ae60b 100644 --- a/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs +++ b/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs @@ -117,6 +117,17 @@ pub(super) fn texture(call: &Call, f: &Fields, d: &mut TextureDescriptor) -> Res Ok(()) } +/// A `newBufferWithDescriptor:` descriptor's fields. +pub(super) const BUFFER_FIELDS: [&str; 7] = [ + "length", + "options", + "pinnedGpuAddress", + "contents", + "noCopy", + "deallocator", + "zeroFrom", +]; + /// `newBufferWithDescriptor:`: the buffer's length, options and the bytes it was made with (its /// `contents`, empty where the stream gives none), which the player also writes once the buffer /// is made; a no-copy buffer's later bytes arrive as `m2v.write`, and the pinned address is the @@ -125,19 +136,7 @@ pub(super) fn texture(call: &Call, f: &Fields, d: &mut TextureDescriptor) -> Res /// (`ResourceOptions::PRIVATE_BIT`) is made without it: its GPU writes, which Metal drops, are /// kept. pub(super) fn buffer(call: &Call) -> Result<(u64, ResourceOptions, &[u8]), PlayError> { - let f = Fields::arg( - call, - 0, - &[ - "length", - "options", - "pinnedGpuAddress", - "contents", - "noCopy", - "deallocator", - "zeroFrom", - ], - )?; + let f = Fields::arg(call, 0, &BUFFER_FIELDS)?; // The bytes it was made with, where the stream gives them (`docs/REPLAY-STREAM.md`, section 5). let contents = match f.get("contents") { None => &[][..], diff --git a/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs index 932969c89..b0735971d 100644 --- a/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs @@ -9,13 +9,13 @@ mod descriptors; mod encoders; use super::heaps::HeapSplit; -use super::new_runtime::ManagedCopies; +use super::new_runtime::{objects_named, ManagedCopies}; use super::player::{Backend, Counters, Made, PlayError}; use super::stream::Call; use super::value::Value; use crate::gpu::wait::{runtime::wait_for_command_buffer, SubmissionBackend}; use crate::gpu::DeviceType; -use args::{arg, data, failed, metal, options, range, refuse, region, uint, Fields}; +use args::{arg, data, failed, metal, option_sets, options, range, refuse, region, uint, Fields}; use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage}; use metal2vulkan_runtime::{ AddressPlacement, BlitCommandEncoder, BlitOption, Buffer, BufferContents, BufferDescriptor, @@ -99,6 +99,15 @@ pub struct OldRuntime { identity: bool, /// The Managed buffers and blocks a one-copy stream made, played as Shared. managed_shared: Cell, + /// Each encoder's command buffer. + owners: HashMap, + /// The no-copy Managed buffers of a two-copy stream with no identity record that were made + /// with no bytes and whose first use has not been committed, with the command buffer that + /// first uses one: the stream's writes into such a buffer reach its GPU copy too, as the new + /// runtime's backend plays them (`docs/REPLAY-STREAM.md`, Managed buffers). + fresh: HashMap>, + /// The no-copy Managed buffers whose GPU copy took bytes written before their first use. + from_first_use: HashSet, } /// A made object with no address. @@ -240,6 +249,9 @@ impl OldRuntime { managed: None, identity: false, managed_shared: Cell::new(0), + owners: HashMap::new(), + fresh: HashMap::new(), + from_first_use: HashSet::new(), } } @@ -250,6 +262,33 @@ impl OldRuntime { self } + /// Whether `call` makes a buffer whose GPU copy takes the writes before its first use: a + /// no-copy Managed buffer made with no bytes, in a two-copy stream with no identity record + /// (the form the player's setting gives), as the new runtime's backend plays it. + fn fresh_at_making(&self, call: &Call) -> Result { + if self.managed != Some(ManagedCopies::Two) || self.identity { + return Ok(false); + } + let (raw, bytes) = match &*call.selector { + "newBufferWithBytesNoCopy:length:options:deallocator:" => { + let bytes = arg(call, 0)?.as_bytes().is_some_and(|b| !b.is_empty()); + (uint(call, 2)?, bytes) + } + "newBufferWithDescriptor:" => { + let f = Fields::arg(call, 0, &descriptors::BUFFER_FIELDS)?; + if f.bool("noCopy")? != Some(true) { + return Ok(false); + } + let raw = option_sets(call, 0, f.list("options")?.unwrap_or_default())?; + let bytes = f.get("contents").and_then(Value::as_bytes); + (raw, bytes.is_some_and(|b| !b.is_empty())) + } + _ => return Ok(false), + }; + let mode = options(call, raw)?.storage_mode(); + Ok(mode == Ok(StorageMode::Managed) && !bytes) + } + /// The options a buffer or block of `options` is made with: Shared where `options` are /// Managed and the stream was recorded with one copy, as the new runtime's backend plays them /// (`docs/REPLAY-STREAM.md`, Managed buffers), so a CPU write reaches the GPU as it reached @@ -904,8 +943,23 @@ impl Backend for OldRuntime { fn call(&mut self, call: &Call) -> Result { if &*call.selector == "release" { self.objects.remove(&call.receiver); + self.owners.remove(&call.receiver); + self.fresh.remove(&call.receiver); return Ok(Made::default()); } + if !self.fresh.is_empty() { + // An encoder naming a no-copy Managed buffer not yet used: its command buffer is the + // buffer's first use. + if let Some(&user) = self.owners.get(&call.receiver) { + let mut named = Vec::new(); + objects_named(&call.args, &mut named); + for id in named { + if let Some(first @ None) = self.fresh.get_mut(&id) { + *first = Some(user); + } + } + } + } if self.skipped(call.receiver) { // A call on a skipped object; what it makes is skipped too. self.skips.calls += 1; @@ -950,7 +1004,18 @@ impl Backend for OldRuntime { } _ => return Err(refuse(call, "not played on a command queue")), }, - Some(Object::CommandBuffer(_)) => self.command_buffer_call(call)?.map(unaddressed), + Some(Object::CommandBuffer(_)) => { + let made = self.command_buffer_call(call)?; + if &*call.selector == "commit" { + // Its first use committed, a no-copy Managed buffer's GPU copy changes only by + // `didModifyRange:` from here. + self.fresh.retain(|_, user| *user != Some(call.receiver)); + } + if made.is_some() && call.selector.contains("CommandEncoder") { + self.owners.insert(call.result, call.receiver); + } + made.map(unaddressed) + } Some(Object::Compute(_)) => { self.compute_call(call)?; None @@ -996,6 +1061,9 @@ impl Backend for OldRuntime { call.selector ))); } + if self.fresh_at_making(call)? { + self.fresh.insert(call.result, None); + } self.objects.insert(call.result, object); Ok(made) } @@ -1040,7 +1108,19 @@ impl Backend for OldRuntime { PlayError::Invalid(format!( "m2v.write past #{target}'s CPU-visible bytes: {why}" )) - }) + })?; + // Bytes recorded before a no-copy Managed buffer's first use are its contents at creation, + // as near as the stream has them: its GPU copy takes them too. + if self.fresh.contains_key(&target) && !bytes.is_empty() { + let end = offset + bytes.len() as u64; + let did = buffer.did_modify_range(offset..end); + did.map_err(|error| PlayError::Runtime { + selector: "m2v.write".into(), + error: error.to_string(), + })?; + self.from_first_use.insert(target); + } + Ok(()) } fn wait(&mut self, command_buffer: u64) -> Result<(), PlayError> { @@ -1181,7 +1261,11 @@ impl Backend for OldRuntime { "managed one copy ({from}): {} Managed buffers and blocks played as Shared", self.managed_shared.get() ), - ManagedCopies::Two => format!("managed two copies ({from}): played as recorded"), + ManagedCopies::Two => format!( + "managed two copies ({from}): played as recorded; {} no-copy ones with \ + contents from first use, not from create", + self.from_first_use.len() + ), }); } lines diff --git a/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs b/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs index 98b01e1e5..32fc5cb62 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs @@ -26,6 +26,9 @@ //! - A two-copy stream's Managed buffers start their GPU copies from the bytes they were made with //! (`rt_replay::made_with`): a no-copy descriptor buffer and a copied one read through a blit as //! the bytes each was made with, on a device that keeps two copies as on one that keeps one. +//! - A two-copy stream with no identity record (the player's setting): a no-copy Managed buffer +//! made with no bytes takes the writes recorded before its first use into its GPU copy too, as +//! the new runtime's backend plays it, so a blit reads them. //! - A buffer made as a copy of host memory starts with its contents, and the IDs the program saw //! are compared with the runtime's. //! - A texture its descriptor marks `outside` takes none of the program's IDs. @@ -49,8 +52,8 @@ use super::host_memory::on_device_with; use super::rt_replay::{library_of, made_with}; use super::{at_plan, public_case}; use crate::replay::{ - Backend, OldRuntime, PlayError, Player, Report, StreamReader, StreamWriter, Value, - WAIT_COMPLETED, + Backend, ManagedCopies, OldRuntime, PlayError, Player, Report, StreamReader, StreamWriter, + Value, WAIT_COMPLETED, }; use crate::ScratchDir; use metal2vulkan_devtools::metallib::{metallib, wrap, MtlbFunction}; @@ -1750,7 +1753,68 @@ fn a_two_copy_stream_s_managed_buffers_start_from_the_bytes_they_were_made_with( let object = check.object; assert_eq!(Some(check.sha256), check.recorded, "#{object}'s GPU copy"); } - let managed = "managed two copies (the stream's device identity): played as recorded"; + let managed = "managed two copies (the stream's device identity): played as recorded; 0 \ + no-copy ones with contents from first use, not from create"; + assert!(lines.iter().any(|l| l == managed), "{lines:?}"); + }); +} + +/// A stream with no identity record, played with two copies (`--managed two-copy`): Managed #3, a +/// no-copy descriptor buffer of 4 bytes made with none, takes 7s by a write with no +/// `didModifyRange:` before its first use, a blit copying it into Shared #4, which a check reads +/// as the 7s. The write is the nearest record the stream has of the buffer's bytes at its making, +/// so its GPU copy takes it, as the new runtime's backend plays it. +#[test] +fn a_two_copy_stream_with_no_identity_gives_a_no_copy_buffer_its_writes_before_first_use() { + let dir = ScratchDir::new("replay-first-use").unwrap(); + let path = written(&dir, |w| { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + w.call("newCommandQueue", 1, 2, &[], &[])?; + let managed = Value::List(vec![Value::Map(vec![( + "ResourceOptions".into(), + Value::Uint(16), + )])]); + let descriptor = Value::Map(vec![ + ("length".into(), Value::Uint(4)), + ("options".into(), managed), + ("noCopy".into(), Value::Bool(true)), + ]); + w.call("newBufferWithDescriptor:", 1, 3, &[descriptor], &[])?; + let shared = [Value::Uint(4), Value::Uint(0)]; + w.call("newBufferWithLength:options:", 1, 4, &shared, &[])?; + let pairs = [Value::Uint(0), Value::Bytes(vec![7; 4])]; + w.call("m2v.write", 3, 0, &pairs, &[])?; + w.call("commandBuffer", 2, 10, &[], &[])?; + w.call("blitCommandEncoder", 10, 11, &[], &[])?; + let (zero, four) = (Value::Uint(0), Value::Uint(4)); + let copy = [Value::Object(3), zero.clone(), Value::Object(4), zero, four]; + let copy_from = "copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:"; + w.call(copy_from, 11, 0, ©, &[])?; + w.call("endEncoding", 11, 0, &[], &[])?; + w.call("commit", 10, 0, &[], &[])?; + w.call(WAIT_COMPLETED, 10, 0, &[], &[])?; + let answer = [("sha256", sha(&[7; 4]))]; + w.call("m2v.check", 0, 0, &[Value::Object(4)], &answer) + }); + on_device_with(at_plan, |device| { + let backend = OldRuntime::new(device.clone(), crate::gpu::TEST_DEVICE); + let mut backend = backend.with_managed(ManagedCopies::Two); + let mut reader = StreamReader::open(std::slice::from_ref(&path), None).unwrap(); + let (report, ended) = Player::new(&mut backend).play(&mut reader); + let lines = backend.lines(); + for line in report.lines().iter().chain(&lines) { + eprintln!("REPLAY first-use {} {line}", device.name()); + } + ended.unwrap(); + assert_eq!(report.checks.len(), 1); + let check = &report.checks[0]; + assert_eq!( + Some(check.sha256), + check.recorded, + "the blit read the write" + ); + let managed = "managed two copies (the player's setting): played as recorded; 1 no-copy \ + ones with contents from first use, not from create"; assert!(lines.iter().any(|l| l == managed), "{lines:?}"); }); } diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index c4a772269..5555b47cd 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -558,8 +558,13 @@ counted from 0), completes the work committed so far, reports as at the stream's `didModifyRange:`. Otherwise a Managed buffer plays as the old runtime's, which keeps a GPU copy on a device without unified memory, and that copy starts from the bytes the buffer was made with, as on the new runtime: the backend's making takes them from the call and announces them - (`didModifyRange:` over them). Its report's `managed` line says which form played, from what, - and counts the buffers and blocks played as Shared. + (`didModifyRange:` over them). In a stream with no identity record played with two copies, a + no-copy Managed buffer made with no bytes takes the writes recorded before its first use into + its GPU copy too, by the new runtime's rule (above); an identity record gives the bytes at its + making instead, and its later writes reach the GPU copy only by `didModifyRange:`, on both + runtimes. Its report's `managed` line says which form played, from what, and counts the + buffers and blocks played as Shared, or under two copies the no-copy ones whose contents came + from first use. - **No-copy buffers** (the new runtime) play as the product makes them, by creator: - A `newBufferWithDescriptor:` with `noCopy` is a pool buffer in the product: a guest buffer's storage in one of the host's blocks. Where its recorded address and length lie inside a live