From 41b5038342f2d769740fbf014e28feb377a25f1d Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 22 Nov 2026 13:29:00 -0800 Subject: [PATCH] Player: a commit waits on the CPU for the backend's own surface fill before it goes What: the replay player's surface backend keeps its last command buffer on its own queue, a fill at a shape's making or the refill a picture owes at its first use (Surfaces::unwaited). The stream's next commit waits for it on the CPU, once, before committing, counted as surface_host_waits (an executed counter, and in the report's surfaces line). New test a_surface_picture_fills_before_its_use_behind_another_queues_long_work plays the same picture behind 256 dispatches over 4 MiB committed first on another queue, and checks the second picture, one refill and one host wait. The runtime README's queue rule now says what Metal and the code do: a command buffer sharing a tracked resource with an earlier-committed one of another queue goes after it only once that one is submitted (the M3 Max rows of that section, jobs m3-max-52432 and m3-max-52415), a cut command buffer that has begun counting as submitted until its next piece waits for an event; an event wait holds only its own queue; the fence sentence says what the code does, Metal's side measured only by jobs m3-max-52186 and m3-max-52188. Its known gaps name a program that relies on commit order between queues for a shared resource with no event or fence. docs/REPLAY-STREAM.md gives the wait and its counter. Why: a_surface_picture_fills_its_shapes_at_their_first_use read the first picture's inverse on the RX 550, the 780M, the Iris Xe and lavapipe at 62183f55af. On the RX 550, alternated in one job (m3-max-68619), f979769faf passed 4 of 4 and 62183f55af failed 3 of 4, each failure reading [239 223 207 64]x4 for [175 159 143 128]x4. The player fills an owed shape by a blit on its own queue and relied on commit order alone to run it before the stream's kernel on queue #2. Under the device's room the player's queue had turn 1 (its making fill still in flight) and #2 turn 0, so has_room and rank sent the kernel's submission first; it took the upload of the first picture's replace_region, as that upload's contract says, and the refill ran after the kernel. At f979769faf room was per queue with no rank, so the refill went as it was staged. Metal's hazard tracking orders such a pair only against work already submitted (the M3 Max rows above), so the runtime owes no order there, and the player does what a program must: it waits for its own fill, as the consumer's video paths wait on the CPU. Verified (check tree 5c42e1bae6, this commit's code; this commit rewords the new test's doc comment only): - fmt, clippy plain / --cfg m2v_gpu / --cfg m2v_cpu_icd and workspace Rustdoc, all -D warnings: m3-max-68681. - lavapipe under --cfg m2v_cpu_icd, LP_NUM_THREADS=1, m3-max-68682: with the fix, 129 of 129 validation replay:: tests pass; with surfaces.rs of f21db0934c (the fix out, the test in), the original test reads [239 223 207 64]x4 (rt_replay.rs:2338). - RX 550 (RADV POLARIS12), m3-max-68686 (archive m3-max-68684): both surface tests pass 4 of 4. - The new test is not a forcing test. Without the fix it read the first picture in 9 of 9 runs started alone with --no-capture (m3-max-68698 one at 256 dispatches; m3-max-68707 four at 256 and four at 1,024), and the right picture, failing only its host-wait count, in all 3 suite runs (m3-max-68682 at 256, m3-max-68711 at 1,024, m3-max-68717 at 1,024 run alone under threads-required). What tells those runs apart is not found. With the fix it passes in every run above. --- crates/metal2vulkan-runtime/README.md | 21 +++- .../src/replay/new_runtime/surfaces.rs | 37 +++++-- .../src/replay/rt_replay.rs | 96 +++++++++++++++++++ docs/REPLAY-STREAM.md | 10 +- 4 files changed, 150 insertions(+), 14 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index cccd2f7b1..303208d45 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -1904,9 +1904,15 @@ made, with no lock, and never rewritten for layouts. updates, or either reaches memory outside its resources: then it goes after the last piece (`Metrics::shared_holds`), held only while the cut one's next piece is ready; where that piece waits for an event not yet met, it goes, as Metal's wait stops only its own queue, and the - signal may come from the queue it holds. Across queues, work goes to the device in any order, - except that a command buffer never goes ahead of an earlier-committed one it shares a tracked - resource or a fence with, and an event wait holds only its own queue. Two readers of one + signal may come from the queue it holds. Across queues, a command buffer that shares a tracked + resource with an earlier-committed one of another queue goes after it only once that one is + submitted, as Metal's hazard tracking orders such a pair against work already submitted, and no + more (the M3 Max rows below, jobs m3-max-52432 and m3-max-52415); a cut command buffer that has + begun counts as submitted until its next piece waits for an event. An event wait holds only its + own queue. A command buffer that waits on a fence goes after each command buffer of another + queue that updates it and is held in a group or for room, and after every ready piece of a cut + one; Metal's side of that is measured only by the probe under `Fence` below (jobs m3-max-52186 + and m3-max-52188). Two readers of one resource share it here, so a read waits behind a cut command buffer that only reads what it reads, though no write orders them: an over-hold. The cut command buffer is scheduled as its first piece is submitted, where none of its later pieces waits for an event, and its GPU times run from its first piece's @@ -2065,8 +2071,8 @@ made, with no lock, and never rewritten for layouts. buffers). A waiter with nothing for the GPU (an encoder that only waits) completes no sooner than the last submission that updates its fence, as Metal's does (job m3-max-52194); its GPU times are one time, as for any command buffer with nothing for the GPU, where Metal reports a - span over the update's run. Work with no fence between it is ordered as well, where Metal may - run it at once. + span over the update's run. Work with no fence or event between it is ordered only as the + queue rule above says. - `CommandQueue::abandon` ends every command buffer of the queue held at an event wait or not yet scheduled with `NotRun` and runs its handlers, as a Mac drops a dead process's held work, each retiring in the queue's order. Segments already submitted still complete, and so does a group @@ -2119,6 +2125,11 @@ while the driver's exit handler waited on a lock, with every runtime thread alre ### Known gaps +- A program that relies on commit order between queues for a shared resource, with no event or + fence, can read the earlier contents on the runtime, where a Mac's timing usually hides it: work + held behind its own queue's can go to the device after another queue's later command buffer. + That is Metal's rule (the M3 Max rows in the queue rule above, jobs m3-max-52432 and + m3-max-52415). - A lost device is not recovered. After a loss, the device and everything made on it stay dead: its buffers, textures, heaps, pipeline states, queues and events, and every device address and resource ID it handed out. Every later commit ends `DeviceLost`. The consumer may make a new device diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/surfaces.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/surfaces.rs index b91699ce8..d35efb509 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/surfaces.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/surfaces.rs @@ -244,6 +244,11 @@ pub(super) struct Surfaces { queue: Option, /// The refills' command buffers not yet seen complete (`timed`). refilling: VecDeque, + /// The last command buffer committed to `queue` (a making's fill or a refill) that no commit + /// has waited for yet: the next commit whose encoders use a surface's texture waits for it on + /// the CPU first (`surface_fill_owed`), as nothing on the device orders a command buffer of + /// another queue after it. + unwaited: Option, /// A count of makings and lettings go, for the shapes' recency. tick: u64, counts: Counts, @@ -289,6 +294,8 @@ struct Counts { /// The GPU time of the refills' command buffers seen complete, and the longest one's. refill_nanos: u64, refill_max_nanos: u64, + /// The commits that waited on the CPU for the backend's own fills (`unwaited`). + host_waits: u64, /// Copies from the guest's RAM into a shape, and copies back to the guest's RAM that read a /// buffer with shapes. copies_in: u64, @@ -457,13 +464,14 @@ impl Surfaces { } /// The executed counters. - pub(super) fn counted(&self) -> [(&'static str, u64); 26] { + pub(super) fn counted(&self) -> [(&'static str, u64); 27] { let c = &self.counts; [ ("surface_external_writes", c.external_writes), ("surface_refills", c.refills), ("surface_refill_bytes", c.refill_bytes), ("surface_refill_gpu_nanos", c.refill_nanos), + ("surface_host_waits", c.host_waits), ("surface_pictures_filled", c.pictures_filled), ("surface_pictures_unfilled", c.pictures_unfilled), ("surface_textures", c.views), @@ -499,7 +507,8 @@ impl Surfaces { argument buffer with no use named unseen, not counted); {} dirty shapes written back ({} bytes); {} CPU writes, \ {} external writes, {} of them filled at a use and {} landed over before any (and \ {} not used yet), filling {} shapes ({} bytes, {} ns of GPU time, the longest \ - command buffer {} ns), {} copies from the guest's RAM into a shape and {} back, {} \ + command buffer {} ns), {} commits waiting on the CPU for those fills, {} copies \ + from the guest's RAM into a shape and {} back, {} \ bytes in all; {} refused for a format a plain shape does not view as, {} declaring \ pixel-format-view usage over a plain shape; {} across planes skipped", c.views, @@ -524,6 +533,7 @@ impl Surfaces { c.refill_bytes, c.refill_nanos, c.refill_max_nanos, + c.host_waits, c.copies_in, c.copies_out, c.bytes, @@ -698,6 +708,7 @@ impl NewRuntime { (blit.copy_from_buffer(buffer, layout, shape.size(), &texture, ORIGIN)) .map_err(failed(call))?; blit.end_encoding(); + self.surfaces.unwaited = Some(command_buffer.clone()); self.commit(&queue, command_buffer, 0) .map_err(failed(call))?; let surfaces = &mut self.surfaces; @@ -803,11 +814,24 @@ impl NewRuntime { /// Before command buffer `call.receiver` commits: every owing shape of the receiver buffers /// its encoders used is filled from its buffer, by blits in a command buffer of the play's own - /// committed now, ahead of it. + /// committed now, and the last command buffer of the play's own queue (that fill or a + /// making's) is waited for on the CPU, once (`Surfaces::unwaited`, counted): the device orders + /// no command buffer of another queue after work held behind its own queue's, as Metal's + /// hazard tracking orders such a pair only against work already submitted. pub(super) fn surface_fill_owed(&mut self, call: &Call) -> Result<(), PlayError> { - let Some(used) = self.surfaces.used.remove(&call.receiver) else { - return Ok(()); - }; + if let Some(used) = self.surfaces.used.remove(&call.receiver) { + self.surface_refill(call, used)?; + } + if let Some(fill) = self.surfaces.unwaited.take() { + fill.wait_until_completed().map_err(failed(call))?; + self.surfaces.counts.host_waits += 1; + } + Ok(()) + } + + /// Every owing shape of the receiver buffers `used` filled from its buffer, by blits in a + /// command buffer of the play's own committed now, which the commit then waits for. + fn surface_refill(&mut self, call: &Call, used: HashSet) -> Result<(), PlayError> { let mut owing = Vec::new(); for id in used { let shapes = (self.surfaces).shapes_of(id, |_, entry| entry.owed); @@ -832,6 +856,7 @@ impl NewRuntime { } blit.end_encoding(); self.surfaces.refilling.push_back(command_buffer.clone()); + self.surfaces.unwaited = Some(command_buffer.clone()); self.commit(&queue, command_buffer, 0) .map_err(failed(call))?; let surfaces = &mut self.surfaces; diff --git a/crates/metal2vulkan-validation/src/replay/rt_replay.rs b/crates/metal2vulkan-validation/src/replay/rt_replay.rs index df73c3bec..fab90b756 100644 --- a/crates/metal2vulkan-validation/src/replay/rt_replay.rs +++ b/crates/metal2vulkan-validation/src/replay/rt_replay.rs @@ -2348,6 +2348,102 @@ fn a_surface_picture_fills_its_shapes_at_their_first_use() { assert_eq!(counts, [2, 1, 1, 1], "{executed:?}"); } +/// The surface picture of [`a_surface_picture_fills_its_shapes_at_their_first_use`] behind +/// another queue's long work: queue #20's command buffer #24, 256 dispatches over 4 MiB, is +/// committed first, so #8's making fill can run behind it on the device and the refill the +/// kernel's commit owes be held behind both, where queue #2, idle, ranks first for the room +/// (`metal2vulkan_runtime`'s submit thread), as Metal's hazard tracking allows: it orders a +/// command buffer of another queue only against work already submitted. Whatever the order the +/// device takes, the commit waits on the CPU for the refill, once (`surface_host_waits`), so the +/// kernel reads the second picture. +#[test] +fn a_surface_picture_fills_before_its_use_behind_another_queues_long_work() { + let dir = ScratchDir::new("rt-replay-surface-behind").unwrap(); + let first = [0x10, 0x20, 0x30, 0x40].repeat(4); + let second = [0x50, 0x60, 0x70, 0x80].repeat(4); + let path = written(&dir, |w| { + let functions = [("invert_texels", 2, 0), ("scale_and_offset", 2, 0)]; + let library = w.blob(&library(&dir, &functions))?; + w.call("MTLCreateSystemDefaultDevice", 0, 1, &[], &[])?; + w.call("newCommandQueue", 1, 2, &[], &[])?; + w.call("newCommandQueue", 1, 20, &[], &[])?; + w.call( + "newLibraryWithData:error:", + 1, + 3, + &[Value::Blob(library)], + &[], + )?; + let made = "newComputePipelineStateWithFunction:error:"; + for (name, function, state) in [("invert_texels", 4, 5), ("scale_and_offset", 21, 22)] { + let kernel = [Value::Str(name.into())]; + w.call("newFunctionWithName:", 3, function, &kernel, &[])?; + w.call(made, 1, state, &[Value::Object(function)], &[])?; + } + let long = [Value::Uint(4 << 20), Value::Uint(0)]; + w.call("newBufferWithLength:options:", 1, 23, &long, &[])?; + w.call("newBufferWithLength:options:", 1, 26, &long, &[])?; + w.call("commandBuffer", 20, 24, &[], &[])?; + w.call("computeCommandEncoder", 24, 25, &[], &[])?; + w.call("setComputePipelineState:", 25, 0, &[Value::Object(22)], &[])?; + let scale = [Value::Bytes(vec![0; 4]), Value::Uint(4), Value::Uint(2)]; + w.call("setBytes:length:atIndex:", 25, 0, &scale, &[])?; + for (buffer, at) in [(23, 0), (26, 1)] { + let bind = [Value::Object(buffer), Value::Uint(0), Value::Uint(at)]; + w.call("setBuffer:offset:atIndex:", 25, 0, &bind, &[])?; + } + let size = |n| uints(&[("width", n), ("height", 1), ("depth", 1)]); + let dispatch = "dispatchThreadgroups:threadsPerThreadgroup:"; + for _ in 0..256 { + w.call(dispatch, 25, 0, &[size(1 << 14), size(64)], &[])?; + } + w.call("endEncoding", 25, 0, &[], &[])?; + w.call("commit", 24, 0, &[], &[])?; + let pages = [Value::Uint(16), Value::Uint(0)]; + w.call("newBufferWithLength:options:", 1, 6, &pages, &[])?; + let texture = |usage| { + uints(&[ + ("textureType", 2), + ("pixelFormat", 70), + ("width", 2), + ("height", 2), + ("usage", usage), + ("storageMode", 0), + ]) + }; + let plane = Value::Map(vec![ + ("plane".into(), Value::Uint(0)), + ("offset".into(), Value::Uint(0)), + ("bytesPerRow".into(), Value::Uint(8)), + ("planar".into(), Value::Bool(false)), + ("facts".into(), Value::Nil), + ]); + let surface = "newTextureWithDescriptor:iosurface:plane:"; + w.call(surface, 6, 8, &[texture(1), plane], &[])?; + for picture in [&first, &second] { + let bytes = [Value::Uint(0), Value::Bytes(picture.clone())]; + w.call("m2v.write", 6, 0, &bytes, &[])?; + w.call("m2v.externalWriteDone", 6, 0, &[], &[])?; + } + w.call("newTextureWithDescriptor:", 1, 10, &[texture(2)], &[])?; + invert(w, 11, 8, 10)?; + w.call(WAIT_COMPLETED, 24, 0, &[], &[]) + }); + let (report, lines, rows) = play_then("surface-behind", &path, |backend| { + let bytes = backend.read(10).unwrap(); + let pitch = bytes.len() / 2; + [&bytes[..8], &bytes[pitch..pitch + 8]].concat() + }); + let inverse: Vec = (second.chunks(4)) + .flat_map(|t| [0xFF - t[0], 0xFF - t[1], 0xFF - t[2], t[3]]) + .collect(); + assert_eq!(rows, inverse, "{lines:?}"); + let executed = &report.total.executed; + let counted = |key: &str| executed.get(key).copied().unwrap_or(0); + let counts = ["surface_refills", "surface_host_waits"].map(counted); + assert_eq!(counts, [1, 1], "{executed:?}"); +} + /// Textures over plane 0 of one surface (#2), 2 by 2, none declaring shader write: #3, /// RGBA8Unorm, makes a plain shape, and #4, its sRGB sibling, is a view of it; then `last`, a /// texture of BGRA8Unorm over the plane or a view of #3 as BGRA8Unorm, is refused and counted: diff --git a/docs/REPLAY-STREAM.md b/docs/REPLAY-STREAM.md index 78cfb8df0..aebfeb1d1 100644 --- a/docs/REPLAY-STREAM.md +++ b/docs/REPLAY-STREAM.md @@ -845,7 +845,11 @@ records as text, and buffer: the first command buffer whose encoders use a texture of the buffer fills every owing shape of the buffers it uses before its commit, by blits in a command buffer of the backend's own committed then, and a picture that another one lands over before any use is never copied - (`surface_pictures_filled`, `surface_pictures_unfilled`). Another call that names a receiver + (`surface_pictures_filled`, `surface_pictures_unfilled`). The next commit of the stream after a + command buffer of the backend's own (a fill at a making or at a use) waits on the CPU for it + first (`surface_host_waits`): the runtime, as Metal, orders a command buffer of another queue + only after work already submitted, and the backend's fill may be held behind its queue's + earlier work. Another call that names a receiver buffer as a buffer is refused, and a texture of a format that reads across a surface's two planes (a two-plane YCbCr or XR10 format) is skipped (`skipped_surfaces_across_planes`). The counts (`surface_textures`, `surface_shapes`, `surface_shapes_found`, `surface_order_shapes`, @@ -853,8 +857,8 @@ records as text, and `surface_overlap_copies`, `surface_overlap_bytes`, `surface_straddled`, `surface_unordered_writes`, `surface_usage_writes`, `surface_declared_writes`, `surface_cpu_writes`, `surface_external_writes`, `surface_refills`, `surface_refill_bytes`, - `surface_refill_gpu_nanos`, `surface_pictures_filled`, `surface_pictures_unfilled`, - `surface_copies_in`, `surface_copies_out`, `surface_bytes`, + `surface_refill_gpu_nanos`, `surface_host_waits`, `surface_pictures_filled`, + `surface_pictures_unfilled`, `surface_copies_in`, `surface_copies_out`, `surface_bytes`, `surface_format_refusals`, `surface_plain_format_views`) are the player's work, among its executed counters; `surface_refill_gpu_nanos` is the GPU time of the refills' command buffers, counted in the frame whose end first sees each complete. The report's `surfaces` line gives them with the longest refill command buffer.