diff --git a/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs b/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs index 6e539a932..b63d67376 100644 --- a/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs +++ b/crates/metal2vulkan-validation/src/replay/old_runtime/descriptors.rs @@ -117,14 +117,14 @@ pub(super) fn texture(call: &Call, f: &Fields, d: &mut TextureDescriptor) -> Res Ok(()) } -/// `newBufferWithDescriptor:`: the buffer's length and options. Its host memory reaches it nil: a -/// copied buffer's `contents` the player writes once the buffer is made, a no-copy buffer's bytes -/// arrive as `m2v.write`, and the pinned address is the recorded one the call answers, where the -/// backend makes the buffer (`address_placement`). A +/// `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 +/// recorded one the call answers, where the backend makes the buffer (`address_placement`). A /// no-copy buffer is played as a buffer of its length, so one of the read-only option /// (`ResourceOptions::PRIVATE_BIT`) is made without it: its GPU writes, which Metal drops, are /// kept. -pub(super) fn buffer(call: &Call) -> Result<(u64, ResourceOptions), PlayError> { +pub(super) fn buffer(call: &Call) -> Result<(u64, ResourceOptions, &[u8]), PlayError> { let f = Fields::arg( call, 0, @@ -138,15 +138,23 @@ pub(super) fn buffer(call: &Call) -> Result<(u64, ResourceOptions), PlayError> { "zeroFrom", ], )?; - if f.get("contents").is_some() { - return Err(refuse(call, "contents that are no bytes")); - } + // The bytes it was made with, where the stream gives them (`docs/REPLAY-STREAM.md`, section 5). + let contents = match f.get("contents") { + None => &[][..], + Some(value) => { + (value.as_bytes()).ok_or_else(|| refuse(call, "contents that are no bytes"))? + } + }; let sets = f.list("options")?.unwrap_or_default(); let mut raw = option_sets(call, 0, sets)?; if f.bool("noCopy")? == Some(true) { raw &= !ResourceOptions::PRIVATE_BIT; } - Ok((f.required("length", Fields::uint)?, options(call, raw)?)) + Ok(( + f.required("length", Fields::uint)?, + options(call, raw)?, + contents, + )) } /// `newHeapWithDescriptor:`: Metal's new heap descriptor holds `Private` storage. diff --git a/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs index 02024db87..932969c89 100644 --- a/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/old_runtime/mod.rs @@ -157,6 +157,47 @@ fn placed( Ok(addressed(buffer.map_err(unplaced(call, at))?)) } +/// `made`, a buffer of `options` that `call` made, holding `bytes` from its first byte, the bytes +/// the stream says it was made with (a descriptor's `contents`, a no-copy buffer's pages): where it +/// plays as the runtime's Managed buffer, its GPU copy starts from them too, as Metal makes it +/// where the device keeps two copies (`docs/REPLAY-STREAM.md`, Managed buffers). The player writes +/// them again once the buffer is made, which changes nothing. +fn made_with( + call: &Call, + made: (Object, Made), + options: ResourceOptions, + bytes: &[u8], +) -> Result<(Object, Made), PlayError> { + let (Object::Buffer(buffer), _) = &made else { + unreachable!("a buffer maker's object"); + }; + if bytes.is_empty() || options.storage_mode() != Ok(StorageMode::Managed) { + return Ok(made); + } + write_into(buffer, 0, bytes).map_err(|why| refuse(call, why))?; + let end = bytes.len() as u64; + buffer.did_modify_range(0..end).map_err(failed(call))?; + Ok(made) +} + +/// `bytes` into `buffer`'s CPU-visible bytes at `offset`; why not, where they do not fit. +fn write_into(buffer: &Buffer, offset: u64, bytes: &[u8]) -> Result<(), String> { + let fits = offset + .checked_add(bytes.len() as u64) + .is_some_and(|end| end <= buffer.length()); + let contents = (buffer.contents().filter(|_| fits)).ok_or("bytes past its CPU-visible ones")?; + // SAFETY: `[offset, offset + len)` lies in the buffer's mapped bytes, and the player waited + // for every command buffer that can complete before writing. + unsafe { + std::ptr::copy_nonoverlapping( + bytes.as_ptr(), + contents.as_ptr().add(offset as usize), + bytes.len(), + ); + } + Ok(()) +} + /// A buffer of the player's own (a staging copy, a read-back), `length` bytes of `contents`: /// outside the space, so that no recorded address can meet it. pub(super) fn own_buffer( @@ -385,7 +426,10 @@ impl OldRuntime { // Played as a buffer of its length: without the read-only option (`buffer`). let options = options(call, uint(call, 2)? & !ResourceOptions::PRIVATE_BIT)?; let options = self.played(call, options)?; - placed(device, call, uint(call, 1)?, options, BufferContents::Zero)? + let made = placed(device, call, uint(call, 1)?, options, BufferContents::Zero)?; + // The pages' bytes at its making, where the stream gives them. + let bytes = arg(call, 0)?.as_bytes().unwrap_or_default(); + made_with(call, made, options, bytes)? } "newBufferWithBytes:length:options:" => { let bytes = data(call, 0)?; @@ -398,9 +442,10 @@ impl OldRuntime { placed(device, call, length, options, BufferContents::Copy(bytes))? } "newBufferWithDescriptor:" => { - let (length, options) = descriptors::buffer(call)?; + let (length, options, contents) = descriptors::buffer(call)?; let options = self.played(call, options)?; - placed(device, call, length, options, BufferContents::Zero)? + let made = placed(device, call, length, options, BufferContents::Zero)?; + made_with(call, made, options, contents)? } "m2v.newBlockWithLength:storageMode:" => { let length = uint(call, 0)?; @@ -991,22 +1036,11 @@ impl Backend for OldRuntime { ))) } }; - let fits = offset - .checked_add(bytes.len() as u64) - .is_some_and(|end| end <= buffer.length()); - let contents = buffer.contents().filter(|_| fits).ok_or_else(|| { - PlayError::Invalid(format!("m2v.write past #{target}'s CPU-visible bytes")) - })?; - // SAFETY: `[offset, offset + len)` lies in the buffer's mapped bytes, and the player waited - // for every command buffer that can complete before writing. - unsafe { - std::ptr::copy_nonoverlapping( - bytes.as_ptr(), - contents.as_ptr().add(offset as usize), - bytes.len(), - ); - } - Ok(()) + write_into(buffer, offset, bytes).map_err(|why| { + PlayError::Invalid(format!( + "m2v.write past #{target}'s CPU-visible bytes: {why}" + )) + }) } fn wait(&mut self, command_buffer: u64) -> Result<(), PlayError> { diff --git a/crates/metal2vulkan-validation/src/replay/player.rs b/crates/metal2vulkan-validation/src/replay/player.rs index 2e23f9eff..dc5348340 100644 --- a/crates/metal2vulkan-validation/src/replay/player.rs +++ b/crates/metal2vulkan-validation/src/replay/player.rs @@ -1135,23 +1135,14 @@ fn cut(call: &Call) -> Result { } } -/// `descriptor`, a `newBufferWithDescriptor:` map, with its `contents` nil, and the bytes they -/// held: what a buffer made as a copy of host memory starts with, which the player writes once the -/// buffer is made (`docs/REPLAY-STREAM.md`, section 5). -fn copied(descriptor: Value) -> (Value, Option>) { - let Value::Map(fields) = descriptor else { - return (descriptor, None); - }; - let mut contents = None; - let fields = fields.into_iter().map(|(key, value)| match value { - Value::Bytes(bytes) if &*key == "contents" => { - contents = Some(bytes); - (key, Value::Nil) - } - value => (key, value), - }); - let fields = fields.collect(); - (Value::Map(fields), contents) +/// The bytes `descriptor`, a `newBufferWithDescriptor:` map, says the buffer was made with (its +/// `contents`): a copied buffer's, or a no-copy one's at its making. The backend's making takes +/// them with the descriptor, so a buffer that plays with two copies starts its GPU copy from them, +/// and the player writes them once the buffer is made (`docs/REPLAY-STREAM.md`, section 5). +fn copied(descriptor: &Value) -> Option> { + let fields = descriptor.as_map()?; + let (_, contents) = fields.iter().find(|(key, _)| &**key == "contents")?; + contents.as_bytes().map(<[u8]>::to_vec) } /// Whether a blob of `around` holds as many bytes as its range. @@ -1857,9 +1848,8 @@ impl<'b, B: Backend> Player<'b, B> { let arg = self.resolve(stream, arg, &mut relocated)?; let arg = match (at, &*call.selector) { (0, "newBufferWithDescriptor:") => { - let (descriptor, bytes) = copied(arg); - contents = bytes; - descriptor + contents = copied(&arg); + arg } _ => arg, }; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs b/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs index 251eda145..98b01e1e5 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/replay_streams.rs @@ -23,6 +23,9 @@ //! - A one-copy stream's Managed buffer plays as Shared: a CPU write with no `didModifyRange:` //! reaches a blit's read of it, on a device that keeps Managed buffers in two copies as on one //! that keeps one. +//! - 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 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. @@ -43,7 +46,7 @@ //! their own beside the stream's. use super::host_memory::on_device_with; -use super::rt_replay::library_of; +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, @@ -1726,3 +1729,28 @@ fn a_one_copy_stream_s_managed_buffer_plays_as_shared() { assert!(lines.iter().any(|l| l == managed), "{lines:?}"); }); } + +/// `rt_replay::made_with`'s stream on the old runtime: both Managed buffers' GPU copies start from +/// the bytes they were made with, and the report says two copies, from the stream's identity. +#[test] +fn a_two_copy_stream_s_managed_buffers_start_from_the_bytes_they_were_made_with() { + let dir = ScratchDir::new("replay-made-with").unwrap(); + let path = written(&dir, made_with); + on_device_with(at_plan, |device| { + let mut backend = OldRuntime::new(device.clone(), crate::gpu::TEST_DEVICE); + 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 made-with {} {line}", device.name()); + } + ended.unwrap(); + assert_eq!(report.checks.len(), 2); + for check in &report.checks { + 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"; + assert!(lines.iter().any(|l| l == managed), "{lines:?}"); + }); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs b/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs index 408a7df54..91d129013 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rt_replay.rs @@ -27,6 +27,10 @@ //! own second copy where the device has one): a blit's fill reaches the GPU's copy and not the //! CPU's, an announcement with no write puts the CPU's bytes back into the GPU's copy at the next //! commit, and a synchronize brings the GPU's bytes into the CPU's copy. +//! - A two-copy stream's Managed buffers start their GPU copies from the bytes they were made with: +//! a no-copy descriptor buffer and a copied one, each made with 7s and written 7s before its +//! first use with no `didModifyRange:`, read as 7s through a blit (on the old runtime too, +//! `replay_streams`). //! - A Private buffer, which has no CPU mapping, reads back through a copy into a Shared buffer of //! the play's own: a blit's fill of it reads as the fill's bytes. //! - In a stream whose header marks its announced bytes recorded, an announcement after a @@ -2344,3 +2348,71 @@ fn a_copy_from_the_guest_s_ram_plays_as_a_cpu_gather_then_one_copy() { assert_eq!(executed["guest_ram_fill_copies"], 1 + 2); assert_eq!(executed["guest_ram_fill_bytes"], 16 + 4 + 8); } + +/// A stream recorded with two copies (`hasUnifiedMemory` false), with Managed #3, a no-copy +/// descriptor buffer, and Managed #5, a copied one, 4 bytes each, made with `[7; 4]` and +/// `[9; 4]` (their descriptors' `contents`) and written so before their first use with no +/// `didModifyRange:`, as a recorder writes every buffer's bytes before its first use; a blit +/// copies each into Shared #4 and #6, which a check reads as the bytes each was made with: the +/// recording device's GPU copy started from them. +pub(super) fn made_with(w: &mut StreamWriter) -> std::io::Result<()> { + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + let identity = [("hasUnifiedMemory", Value::Bool(false))]; + w.call("m2v.deviceIdentity", 1, 0, &[], &identity)?; + w.call("newCommandQueue", 1, 2, &[], &[])?; + let managed = Value::List(vec![Value::Map(vec![( + "ResourceOptions".into(), + Value::Uint(16), + )])]); + let copy_from = "copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:"; + let mut sums = Vec::new(); + w.call("commandBuffer", 2, 10, &[], &[])?; + for (id, no_copy, byte) in [(3, true, 7u8), (5, false, 9)] { + let bytes = vec![byte; 4]; + let descriptor = Value::Map(vec![ + ("length".into(), Value::Uint(4)), + ("options".into(), managed.clone()), + ("contents".into(), Value::Bytes(bytes.clone())), + ("noCopy".into(), Value::Bool(no_copy)), + ]); + w.call("newBufferWithDescriptor:", 1, id, &[descriptor], &[])?; + let shared = [Value::Uint(4), Value::Uint(0)]; + w.call("newBufferWithLength:options:", 1, id + 1, &shared, &[])?; + let pairs = [Value::Uint(0), Value::Bytes(bytes.clone())]; + w.call("m2v.write", id, 0, &pairs, &[])?; + let encoder = 10 + id; + w.call("blitCommandEncoder", 10, encoder, &[], &[])?; + let (zero, four) = (Value::Uint(0), Value::Uint(4)); + let copy = [ + Value::Object(id), + zero.clone(), + Value::Object(id + 1), + zero, + four, + ]; + w.call(copy_from, encoder, 0, ©, &[])?; + w.call("endEncoding", encoder, 0, &[], &[])?; + sums.push(Value::Bytes(Sha256::digest(&bytes).to_vec())); + } + w.call("commit", 10, 0, &[], &[])?; + w.call(WAIT_COMPLETED, 10, 0, &[], &[])?; + let answer = [("sha256", Value::List(sums))]; + let checked = [Value::Object(4), Value::Object(6)]; + w.call("m2v.check", 0, 0, &checked, &answer) +} + +#[test] +fn a_two_copy_stream_s_managed_buffers_start_from_the_bytes_they_were_made_with() { + let dir = ScratchDir::new("rt-replay-made-with").unwrap(); + let path = written(&dir, made_with); + let (report, lines) = play("made-with", &path); + assert_eq!(report.checks.len(), 2); + for check in &report.checks { + 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): 2 Managed buffers; 0 \ + no-copy ones with contents from first use, not from create"; + // A device with unified memory adds that it played the two copies as its one. + assert!(lines.iter().any(|l| l.starts_with(managed)), "{lines:?}"); +} diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index f7cdac5fa..c4a772269 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -542,7 +542,9 @@ counted from 0), completes the work committed so far, reports as at the stream's the play with an error that says so. One copy: every Managed buffer plays as a Shared buffer, on every device. Two copies: it plays as the runtime's Managed buffer, whose GPU copy starts from the bytes it was made with: a copied buffer's bytes, or a no-copy one's bytes at its making - (section 5). A stream with no identity record gives a no-copy buffer none, so its GPU copy takes + (section 5), which the backend's making takes from the call (a descriptor's `contents`, the + pages `newBufferWithBytesNoCopy:length:options:deallocator:` holds) and the player writes again + once the buffer is made. A stream with no identity record gives a no-copy buffer none, so its GPU copy takes the writes recorded before its first use (a commit of a command buffer one of whose encoders names it), the nearest record the stream has of its bytes at its making. Where the device keeps a GPU copy, the player places it as it places a Private buffer of the buffer's length (below), a @@ -554,8 +556,10 @@ counted from 0), completes the work committed so far, reports as at the stream's record (or `--managed one-copy`), every Managed buffer and block plays as a Shared one, so a CPU write reaches the GPU as it reached the recording device's, with or without a `didModifyRange:`. Otherwise a Managed buffer plays as the old runtime's, which keeps a GPU copy - on a device without unified memory. Its report's `managed` line says which form played, from - what, and counts the buffers and blocks played as Shared. + 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. - **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