From 78af808c9883016632e560193c9af08b6d734898 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 2 Dec 2026 12:12:03 -0800 Subject: [PATCH 1/6] rt test: a texture placed over another's bytes moves at its first use, not in an upload (red) A newer heap texture placed over an older one's bytes takes its move from UNDEFINED in the upload ahead of its first command buffer. Vulkan lets that move write the image's memory. If the command buffer reads the older texture before it writes the newer one, the read can see changed bytes, and Metal changes none. The pin round's AMDVLK leg showed it: Radeon 780M under AMDVLK, job m3-max-79662 at 685df4244e, 1 of 915 failed. The failing test is heap_alias's every_device_reads_an_older_texture_before_a_newer_one_over_its_bytes_is_written: 554 of 262144 texels of the older RGBA16Float texture read NaN, for the RGBA8Unorm 256x256 newer shape, with the RGBA16Float 256x128 and R32Float 256x256 shapes failing the same way. RADV and ANV pass it. That test's comment now says so. New counts test in tests/alias.rs, deterministic on every device lavapipe included. P is written; then Q, R, S and U are each placed over P's bytes: - Q is written after a read of P: checks [0, 1], one heap move, no upload barrier. - R is read after a read of P: the same for a first use that reads. - S's heap is declared (useHeap:), then P is read: checks [1], one heap move, no upload barrier; declaring the heap again moves nothing. - U is read by the host (get_bytes): its upload moves it once, the second read not at all. At this commit the uploads move each newer texture, so the upload-barrier, check and heap-move counts differ (red); the fix follows. --- .../metal2vulkan-runtime/src/tests/alias.rs | 118 +++++++++++++++++- .../src/tests/heap_alias.rs | 8 +- 2 files changed, 118 insertions(+), 8 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/tests/alias.rs b/crates/metal2vulkan-runtime/src/tests/alias.rs index c24452ce7f..15275ef31e 100644 --- a/crates/metal2vulkan-runtime/src/tests/alias.rs +++ b/crates/metal2vulkan-runtime/src/tests/alias.rs @@ -38,10 +38,10 @@ mod on_device { use crate::texture::TextureObject; use crate::{ Block, Buffer, BufferLayout, ColorAttachmentDescriptor, CommandBuffer, CommandQueue, - CullMode, Device, Error, FunctionDescriptor, HeapRange, HostBytes, IndexClass, LoadAction, - MemoryClass, PixelFormat, PrimitiveType, Refusal, Region, RenderPassDescriptor, - RenderPipelineDescriptor, StageSource, StorageMode, StoreAction, TextureDescriptor, - TexturePlace, TextureType, TextureUsage, + CullMode, Device, DispatchType, Error, FunctionDescriptor, HeapRange, HostBytes, + IndexClass, LoadAction, MemoryClass, PixelFormat, PrimitiveType, Refusal, Region, + RenderPassDescriptor, RenderPipelineDescriptor, StageSource, StorageMode, StoreAction, + TextureDescriptor, TexturePlace, TextureType, TextureUsage, }; use metal2vulkan_devtools::fixtures_dir; use std::sync::Arc; @@ -631,4 +631,114 @@ mod on_device { (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); }); } + + fn uploads(device: &Device) -> u64 { + device.counters().metrics().upload_barriers + } + + /// A texture placed over another's bytes moves from undefined at its first use alone, after + /// every earlier command of its command buffer that read those bytes, and no upload moves it: + /// a move may write the image's memory, which those reads still need. P, 64 by 64 + /// `RGBA16Float`, is written; then, each placed over P's bytes in turn: + /// - Q, whose command buffer reads P, then writes Q: the segment ends between them, and Q's + /// check heads the second, its one move; + /// - R, whose command buffer reads P, then reads R: the same for a first use that reads; + /// - S, whose command buffer declares the heap (`useHeap:`), then reads P: S's check heads + /// the segment, as a kernel may reach S through the heap; a later declaration of the heap + /// finds nothing to move; + /// - U, an `RGBA8Unorm` texture the host reads (`getBytes:`): its upload moves it, once. + /// + /// Each command buffer's uploads record no barrier. + #[test] + fn every_device_moves_a_texture_placed_over_another_s_bytes_at_its_first_use_alone() { + let Some(libraries) = libraries() else { + return; + }; + each_device("alias_first_use", |name, _, device| { + let done = |result: Result<(), Error>| { + result.unwrap_or_else(|error| panic!("{name}: {error}")) + }; + let kernels = kernels(name, &device, &libraries); + let _grant = (device.grant_indices(IndexClass::Texture, FIRST, 8)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let (block, heap) = heap(name, &device); + let format = PixelFormat::RGBA16Float; + let p = place(name, &device, heap, (0, format, 64, 64), FIRST); + let mut buffers = Buffers::new(name, &device, 3); + let p_in = buffers.of(name, &device, &input(&p)); + let out = buffers.of(name, &device, &vec![0.0; input(&p).len()]); + let queue = device.new_command_queue(4).expect("a queue"); + let cb = queue.command_buffer().expect("a command buffer"); + write(name, &cb, &kernels, &p, &p_in); + run(name, &cb); + let mut lines = Vec::new(); + // Each newer texture's command buffer, its checks by segment, and the moves and upload + // barriers from its placement to its command buffer's completion. + let mut first_use = |what: &str, encode: &dyn Fn(&CommandBuffer)| { + let (moved, uploaded) = (moves(&device), uploads(&device)); + let cb = queue.command_buffer().expect("a command buffer"); + encode(&cb); + let checks = cb.alias_checks_for_test(); + run(name, &cb); + let got = (checks, moves(&device) - moved, uploads(&device) - uploaded); + println!( + "heap first use: {name}: {what}: (checks, moves, upload barriers) {got:?}" + ); + lines.push((what.to_owned(), got)); + }; + let q = place(name, &device, heap, (1, format, 64, 64), FIRST + 2); + let q_in = buffers.of(name, &device, &input(&q)); + first_use("Q written after P's read", &|cb| { + read(name, cb, &kernels, &p, &out); + write(name, cb, &kernels, &q, &q_in); + }); + let r = place(name, &device, heap, (2, format, 64, 64), FIRST + 4); + first_use("R read after P's read", &|cb| { + read(name, cb, &kernels, &p, &out); + read(name, cb, &kernels, &r, &out); + }); + let s = place(name, &device, heap, (3, format, 64, 64), FIRST + 6); + let use_heap = |cb: &CommandBuffer| { + let mut e = (cb.compute_command_encoder(DispatchType::Serial)).expect("an encoder"); + done(e.use_heap(block.id)); + e.end_encoding(); + }; + first_use("S's heap declared, then P read", &|cb| { + use_heap(cb); + read(name, cb, &kernels, &p, &out); + }); + first_use("the heap declared again, then P read", &|cb| { + use_heap(cb); + read(name, cb, &kernels, &p, &out); + }); + let mut d = + TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 64, 64); + d.usage = TextureUsage::SHADER_READ; + let u = (device.new_heap_texture_for_views(&d, heap, 0)) + .unwrap_or_else(|error| panic!("{name}: U: {error}")); + let whole = Region { + origin: [0; 3], + size: [64, 64, 1], + }; + let mut bytes = vec![0; 64 * 64 * 4]; + let mut host_reads = Vec::new(); + for _ in 0..2 { + let before = moves(&device); + done(u.get_bytes(&mut bytes, 64 * 4, 0, whole, 0, 0)); + host_reads.push(moves(&device) - before); + } + println!("heap first use: {name}: U's host reads moved {host_reads:?}"); + let want = [ + ("Q written after P's read", (vec![0, 1], 1, 0)), + ("R read after P's read", (vec![0, 1], 1, 0)), + ("S's heap declared, then P read", (vec![1], 1, 0)), + ("the heap declared again, then P read", (vec![0], 0, 0)), + ] + .map(|(what, got)| (what.to_owned(), got)); + assert_eq!(lines, want, "{name}: (checks, moves, upload barriers)"); + assert_eq!(host_reads, [1, 0], "{name}: U's host reads"); + drop((p, q, r, s, u, p_in, q_in, out, buffers, queue)); + (device.release_block(block)).unwrap_or_else(|error| panic!("{name}: {error}")); + }); + } } diff --git a/crates/metal2vulkan-runtime/src/tests/heap_alias.rs b/crates/metal2vulkan-runtime/src/tests/heap_alias.rs index 7e67a81821..b3dc75bd2b 100644 --- a/crates/metal2vulkan-runtime/src/tests/heap_alias.rs +++ b/crates/metal2vulkan-runtime/src/tests/heap_alias.rs @@ -940,10 +940,10 @@ pub(crate) mod on_device { } /// A newer texture placed over an older one's bytes, its first command buffer reading the - /// older one before writing it: each read of the older one is its write. No lab driver has - /// shown the loss the newer one's move home from undefined may make there: the Radeon 780M - /// (RADV) and the Iris Xe (ANV, Mesa 26.2.6) each read the older one's write for every shape. - /// The test is coverage of Metal's aliasing contract on that order. + /// older one before writing it: each read of the older one is its write, as Metal's aliasing + /// contract has it on that order. The newer one's move from undefined may write its memory: + /// AMDVLK on a Radeon 780M changed the older one's texels for three of the four shapes where + /// that move ran ahead of the read, as RADV and ANV did not. #[test] fn every_device_reads_an_older_texture_before_a_newer_one_over_its_bytes_is_written() { let Some(libraries) = libraries() else { From cffa762bda4050b96bd118a80c445951e89eba7d Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 2 Dec 2026 12:14:15 -0800 Subject: [PATCH 2/6] rt: a heap texture placed over another's bytes moves from undefined at its first use, not in an upload A newer heap texture placed over an older one's bytes moved out of UNDEFINED in the upload ahead of its first command buffer. Vulkan lets that move write the image's memory (a compression state's initialization), and a command buffer that reads the older texture before writing the newer one then reads changed bytes, where Metal changes none. AMDVLK does this on a Radeon 780M (round job m3-max-79662, 1 of 915 failed; RADV and ANV pass). The ruled form, one form on every device with no device or driver key: no upload moves such a texture. Its first use moves it, in the command stream, after the earlier reads. - alias: a texture placed with links is unmoved (Placement::unmoved) as well as stale. A first use in a command buffer of a texture unmoved as it is encoded, a read included, adds a check at the head of its segment, as a first write already did. The segment ends first where a link was read in it. The submit thread resolves the check in queue order: a write's check moves a stale texture, and any check moves an unmoved one, which is then unmoved no more. - Each heap lists its unmoved textures (Places::unmoved). An entry leaves as its texture moves or is released, so the list never holds more than the heap's live placements. The device counts them, so use_heap on a device with none loads one atomic and locks nothing. - use_heap (compute and render) is a read of each unmoved texture of the heap, since a kernel or a draw may reach it next through an address: its check goes where the use_heap is. - get_bytes of an unmoved texture moves it in its own upload, ahead of its copy (alias::host_read). replace_region already moved a stale texture (host_write). - Image.over and its source scope in Image::homing are gone: an unmoved image is made homed and never enters an upload's homes. - Runtime README: the heap texture contract says when the move happens. The known gap of textures carries the residuals: a never-written newer texture that is read; an older texture read through a heap declaration after a newer one over its bytes was made and before that one is written (in both, the move may change the older bytes, as AMDVLK's does); a first use rt cannot name; and a draw's first use, checked where the pass's part of the command buffer starts. To verify at this commit (jobs in the handover): the red commit's counts test and heap_alias on lavapipe, clippy in three configurations, doc and private doc, the runtime and validation suites on lavapipe, AMDVLK on a Radeon 780M red at the red commit and green here, and RADV, ANV and NVIDIA unchanged. --- crates/metal2vulkan-runtime/README.md | 41 ++-- crates/metal2vulkan-runtime/src/alias.rs | 214 ++++++++++++++---- crates/metal2vulkan-runtime/src/encoder.rs | 10 +- crates/metal2vulkan-runtime/src/hazard.rs | 27 +++ .../src/render_encoder.rs | 11 +- crates/metal2vulkan-runtime/src/texture.rs | 47 ++-- 6 files changed, 266 insertions(+), 84 deletions(-) diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 853acc8449..2fdbe6d5e5 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -1710,7 +1710,8 @@ made, with no lock, and never rewritten for layouts. slot that binds it reads Metal's nil texture, and writes only its second element (Set 1). The image moves from undefined to home in the upload of the next commit, ahead of every command buffer committed after the call, or ahead of its first copy; until then nothing holds it, so a - texture released first is freed at once, with nothing submitted. + texture released first is freed at once, with nothing submitted. A heap texture placed over + another resource's bytes is the exception (below): its first use moves it. - A texture's image lists the formats Metal views the texture as that the device holds in a viewed form of the image format's compatibility class, and is then mutable (`VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT` with a `VkImageFormatListCreateInfo`, its own format @@ -1800,6 +1801,11 @@ made, with no lock, and never rewritten for layouts. alias one another and the heap's buffers. A heap texture whose bytes another resource of its heap wrote since its last write moves from undefined before its next write, a GPU command's or `Texture::replace_region`'s copy (`Metrics::heap_moves`), as Vulkan's memory aliasing asks. A + heap texture placed over another resource's bytes moves from undefined at its first use, and no + upload moves it, as the move may write its memory, which the other's earlier reads still need: + a GPU command that reads or writes it, after every earlier command of its command buffer that + read those bytes; a `use_heap` of its heap, where that use is; or a `replace_region` or + `get_bytes` copy (`Metrics::heap_moves`). A placement past the heap's end, an offset in the block off the image's alignment, or a heap range past its block is refused (`Refusal::HeapTexturePlace`); the image is never bound outside its heap. The texture holds @@ -2187,16 +2193,23 @@ made, with no lock, and never rewritten for layouts. - A heap texture whose bytes another resource of its heap wrote moves out of `VK_IMAGE_LAYOUT_UNDEFINED` before its next use that writes it (`Metrics::heap_moves`), as Vulkan's memory aliasing asks: "each of those image subresources must have its layout - transitioned from `VK_IMAGE_LAYOUT_UNDEFINED` to a valid layout before it is used". What remains: - a read of such a texture before its next write takes no move; a write rt cannot name, through a - resource ID or an address outside the encoder's slots and `use_resource` declarations, leaves no - texture stale; a declared write (`use_resource` with a usage that writes) counts as a write of - the whole resource; a texture placed over another's bytes moves home from undefined at its - making, which on a device whose move writes memory may change a live alias's bytes; a move is - of the whole image, so where an alias's write met only part of it, the move takes the rest too; - and a draw's write of a texture that nothing earlier in its command buffer wrote, nor an alias - of it, is checked where the pass's part of the command buffer starts, so its move may go ahead - of a read of an alias there. + transitioned from `VK_IMAGE_LAYOUT_UNDEFINED` to a valid layout before it is used"; a texture + placed over another's bytes moves out of it at its first use, read or write. What remains: a + read of such a texture before its next write takes no move, but for its first use; a write rt + cannot name, through a resource ID or an address outside the encoder's slots and `use_resource` + declarations, leaves no texture stale, and a first use rt cannot name (no slot, `use_resource` + or `use_heap` reaches the texture) does not move a texture placed over another's bytes; a + declared write (`use_resource` with a usage that writes) counts as a write of the whole + resource; a move is of the whole image, so where an alias's write met only part of it, the move + takes the rest too; and a draw's first use of a + texture placed over another's bytes, or its write of a texture that nothing earlier in its + command buffer wrote, nor an alias of it, is checked where the pass's part of the command buffer + starts, so its move may go ahead of a read of an alias there. A move from undefined may write + the texture's memory, as AMDVLK's does on a Radeon 780M (RADV's and ANV's left an alias's texels + as written), so an older texture's bytes may change where a newer texture placed over them is + read before it is ever written, and where the older one is read through a heap declaration + (`use_heap`, which moves the heap's unmoved textures where it is) after the newer one was made + and before that one is written. - A heap buffer's use that may write it (a bound slot its kernel or draw does not read only, or a declared write) makes every heap texture over its bytes stale, though the use wrote other bytes or none: that texture's next write moves its whole image from undefined, so on a device whose @@ -2987,7 +3000,9 @@ while the driver's exit handler waited on a lock, with every runtime thread alre - `use_heap` is `useHeap:`, for the block a heap's memory is: the command buffer keeps the block until it retires, as it keeps a used buffer's block, so a heap given back while the work runs stays valid under it. It declares no access (Metal states no retention for it; keeping is the - safe reading). + safe reading). It is a first use of each texture of the heap placed over another resource's + bytes and not yet moved from undefined (Textures), which a kernel may reach next through an + address: those move there. - A dispatch of a kernel that writes no memory (the translator's `PipelineInterface::writes_memory`: no store to a buffer or through a device address, no texture write and no atomic update, in the kernel or any function it calls) records nothing, binds nothing and reads no indirect buffer, @@ -5237,7 +5252,7 @@ cache is answered compile-required on both. state that enables the scale, which is refused) and `drawIndexedPatches:` (whose control-point index buffer only a state of a control-point index type reads, which is refused). `useHeap:stages:` is `use_heap`, in the compute encoder's form: the command buffer keeps the - block and declares no access. + block, declares no access, and moves each texture of the heap not yet moved from undefined. - Refused by `Gap::RenderPass`, naming its `RenderPassKind`: a depth and a stencil attachment that are not one texture's same level and slice (`DepthStencilViews`: Vulkan's rendering takes one view for both), a `Clear` load of a depth attachment whose clear depth is outside `[0, 1]` diff --git a/crates/metal2vulkan-runtime/src/alias.rs b/crates/metal2vulkan-runtime/src/alias.rs index 3b6b72f7a5..ac5cbfff4b 100644 --- a/crates/metal2vulkan-runtime/src/alias.rs +++ b/crates/metal2vulkan-runtime/src/alias.rs @@ -14,17 +14,28 @@ //! //! A use that writes a placement makes its texture links stale. A stale texture's next use that //! writes it moves its whole image from undefined to its home layout first, in a barrier that -//! orders every earlier command before it and every later one after it. Reads move nothing. A -//! buffer is never moved; its writes make its texture links stale. A stale texture takes part -//! until that write, whether or not a link is left: the release of what wrote over its bytes -//! leaves them written over. A host write of a texture (`Texture::replace_region`) is such a use: -//! as its call records its upload, under the work lock, the move it owes goes in the upload ahead -//! of its copy, and its write applies ([`host_write`]). A command buffer committed after the call -//! is staged after it and runs after the upload; one submitted before the call was staged before -//! it and runs before the upload. A host write while a command buffer committed before it, and -//! not yet completed, writes the texture's bytes or a resource's over them is the program's race, -//! as Metal's `replaceRegion` makes it: the upload may run ahead of that command buffer, and the -//! texture's next write may move it. +//! orders every earlier command before it and every later one after it. Reads of a texture that +//! has moved once move nothing. A buffer is never moved; its writes make its texture links stale. +//! A stale texture takes part until that write, whether or not a link is left: the release of +//! what wrote over its bytes leaves them written over. A host write of a texture +//! (`Texture::replace_region`) is such a use: as its call records its upload, under the work lock, +//! the move it owes goes in the upload ahead of its copy, and its write applies ([`host_write`]). +//! A command buffer committed after the call is staged after it and runs after the upload; one +//! submitted before the call was staged before it and runs before the upload. A host write while +//! a command buffer committed before it, and not yet completed, writes the texture's bytes or a +//! resource's over them is the program's race, as Metal's `replaceRegion` makes it: the upload +//! may run ahead of that command buffer, and the texture's next write may move it. +//! +//! A texture placed over another's bytes is unmoved ([`Placement::unmoved`]): no upload moves its +//! image out of the undefined layout it is made in, as a move may write the image's memory (a +//! compression state's initialization), which the other's earlier reads may still need. Its +//! first use in the command stream moves it instead, read or write, as a write of a stale one +//! does: a read is checked as a write is, below. A host read of it (`Texture::get_bytes`) moves +//! it in the read's upload, ahead of its copy, as a host write's does ([`host_read`]). +//! A `useHeap:` is a read of each unmoved texture of the heap ([`unmoved`]), as a kernel or a draw +//! may then reach it through an address with no declaration. Each heap lists its unmoved textures, +//! and each leaves the list as it moves or is released, so a `useHeap:` of a heap with none looks +//! at no texture, and one on a device with none locks nothing. //! //! Inside a command buffer, encode order is the order its commands run in: [`Marks`] keeps what //! the command buffer did to the placements it touched, and a write of one that a link was @@ -32,15 +43,19 @@ //! nor any of its links, depends on the placement as the command buffer starts: a check at the //! head of its segment ([`Aliased`]), which the submit thread resolves as it stages the segment, //! in the order the device's one queue runs segments, a move it finds owed going in a command -//! buffer of its own ahead of the segment's, in its submit info ([`stage`]). A segment that read -//! one of the placement's links before the write ends first, so the move never goes ahead of that -//! read. Then the segment's writes apply, in their order. +//! buffer of its own ahead of the segment's, in its submit info ([`stage`]). The first use in the +//! command buffer of a texture unmoved as it is encoded, a read among them, is such a check too, +//! which finds a move owed where the texture is still unmoved as the segment is staged. A segment +//! that read one of the placement's links before the use ends first, so the move never goes ahead +//! of that read; inside a rendering nothing ends, and the check goes at the head of the segment +//! the pass is in. Then the segment's writes apply, in their order. use crate::command::DeviceLoss; use crate::counters::Metric; use crate::device::{lock, Core}; use crate::error::Error; use crate::hazard::{Access, HeapId}; +use crate::memory::BlockId; use crate::record::{memory_barrier, Reach, Recorder}; use ash::vk; use std::collections::HashMap; @@ -138,6 +153,9 @@ type ByAddress = HashMap>; pub(crate) struct Places { textures: ByAddress, buffers: ByAddress, + /// Its unmoved textures ([`Placement::unmoved`]), held weakly: each leaves as it moves or is + /// released, so the list holds at most the heap's live textures, and none once each moved. + unmoved: Vec>, /// For the device tests: the entries the heap's last placement looked at. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] examined: usize, @@ -167,12 +185,18 @@ pub(crate) struct Placement { /// As the submit thread has staged the segments: a link was written since its own last write, /// or it was placed over another's bytes and is not yet written. A texture's alone is read. stale: Arc, + /// A texture placed over another's bytes whose image has not yet moved from the undefined + /// layout it is made in, as the submit thread has staged the segments (or as a host read or + /// write recorded its upload): its first use moves it. Clear for every other placement, and + /// never set again once clear. An unmoved texture is stale. + unmoved: AtomicBool, } impl Placement { /// A resource placed at bytes `[start, end)` of `heap`'s block, an image where `moved`, /// linked with the placements of the heap whose bytes meet those, a buffer with textures - /// alone. A texture with links is stale from the start: its bytes may hold another's writes. + /// alone. A texture with links is stale and unmoved from the start: its bytes may hold + /// another's writes, which that one's reads may still need. pub(crate) fn new( heap: &Arc, start: u64, @@ -185,6 +209,7 @@ impl Placement { links: Mutex::new(Links::default()), linked: AtomicBool::new(false), stale: Arc::new(AtomicBool::new(false)), + unmoved: AtomicBool::new(false), }); let texture = moved.is_some(); let mut places = lock(heap.places()); @@ -222,6 +247,11 @@ impl Placement { place.linked.store(true, Relaxed); heap.linked(true); *lock(&place.links) = links; + if texture { + place.unmoved.store(true, Relaxed); + places.unmoved.push(Arc::downgrade(&place)); + heap.unmoved(true); + } } let entry = Entry { start, @@ -247,20 +277,31 @@ impl Placement { self.moved.is_some() && self.stale.load(Relaxed) } - /// Placed over another's bytes: its first move from the layout it is made in waits for every - /// earlier command's writes. - pub(crate) fn over(&self) -> bool { - self.stale.load(Relaxed) + /// A texture placed over another's bytes whose image has not yet moved from the undefined + /// layout it is made in: its first use moves it, and no upload does. + pub(crate) fn unmoved(&self) -> bool { + self.unmoved.load(Relaxed) } fn key(&self) -> usize { std::ptr::from_ref(self) as usize } - /// Its write, in the order the device's one queue runs it: its staleness clears and its - /// texture links turn stale. A texture that took part only for the move it owed takes none - /// once written. + /// Its image's move from undefined is recorded, in the order the device's one queue runs it: + /// it is unmoved no more, and leaves its heap's list. + fn left_undefined(&self) { + if self.unmoved.swap(false, Relaxed) { + let me: *const Placement = self; + (lock(self.heap.places()).unmoved).retain(|place| !std::ptr::eq(place.as_ptr(), me)); + self.heap.unmoved(false); + } + } + + /// Its write, in the order the device's one queue runs it, after its move where it owed one: + /// it is unmoved no more, its staleness clears and its texture links turn stale. A texture + /// that took part only for the move it owed takes none once written. fn written(&self) { + self.left_undefined(); self.stale.store(false, Relaxed); let links = lock(&self.links); for link in links.textures.iter() { @@ -276,8 +317,14 @@ impl Drop for Placement { fn drop(&mut self) { let me: *const Placement = self; let texture = self.moved.is_some(); + let unmoved = *self.unmoved.get_mut(); let met: Vec> = { - lock(self.heap.places()).of(texture).remove(&self.key()); + let mut places = lock(self.heap.places()); + places.of(texture).remove(&self.key()); + if unmoved { + (places.unmoved).retain(|place| !std::ptr::eq(place.as_ptr(), me)); + } + drop(places); let links = self.links.get_mut().unwrap_or_else(PoisonError::into_inner); links .all() @@ -287,6 +334,9 @@ impl Drop for Placement { if *self.linked.get_mut() { self.heap.linked(false); } + if unmoved { + self.heap.unmoved(false); + } for other in &met { let mut links = lock(&other.links); links.drop_to(me, texture); @@ -325,6 +375,9 @@ struct Mark { state: State, /// The segment, from 1, whose commands last read it; 0 where none did. read: usize, + /// A command of the command buffer used it, read or write: its first use, which moves it + /// where it is unmoved, is behind. + used: bool, } /// What a command buffer's commands did to the linked placements they touched, by placement's @@ -340,6 +393,7 @@ impl Marks { _place: place(), state: State::Untouched, read: 0, + used: false, }) } @@ -349,6 +403,18 @@ impl Marks { .map_or(State::Untouched, |mark| mark.state) } + /// Whether a use of texture `place`, a write where `writes`, adds a check at the head of its + /// segment: a write of one that nothing in the command buffer wrote, nor any of its links; or + /// a read of one unmoved as it is encoded that no command of the command buffer used before. + fn checks(&self, place: &Placement, writes: bool) -> bool { + match writes { + true => self.state(place) == State::Untouched, + false => { + place.unmoved() && !(self.marks.get(&place.key())).is_some_and(|mark| mark.used) + } + } + } + /// For a command whose uses of linked placements are `uses`, in segment `segment` (from 0): /// whether a check it adds must go at the head of a segment of its own, a link of the /// placement checked having been read in this one. @@ -358,8 +424,7 @@ impl Marks { .is_some_and(|mark| mark.read == segment + 1) }; (uses.iter()) - .filter(|(place, access)| access.writes() && place.moved.is_some()) - .filter(|(place, _)| self.state(place) == State::Untouched) + .filter(|(place, access)| place.moved.is_some() && self.checks(place, access.writes())) .any(|(place, _)| lock(&place.links).all().any(read_here)) } @@ -373,22 +438,17 @@ impl Marks { part: &mut Aliased, ) -> Vec> { let mut moves: Vec> = Vec::new(); - for (place, _) in uses.iter().filter(|(_, access)| access.writes()) { + for (place, access) in uses { let Some(moved) = place.moved else { continue; }; - match self.state(place) { - State::Fresh => {} - State::Stale => { - if !moves.iter().any(|m| m.image == moved.image) { - moves.push(moved.barrier()); - } - } - State::Untouched => { - if !part.checks.iter().any(|p| Arc::ptr_eq(p, place)) { - part.checks.push(Arc::clone(place)); - } + let writes = access.writes(); + if writes && self.state(place) == State::Stale { + if !moves.iter().any(|m| m.image == moved.image) { + moves.push(moved.barrier()); } + } else if self.checks(place, writes) { + part.check(place, writes); } } for (place, access) in uses { @@ -400,21 +460,35 @@ impl Marks { } part.writes.push(Arc::clone(place)); } + let mark = self.mark(place.key(), || Arc::downgrade(place)); + mark.used = true; if access.reads() { - self.mark(place.key(), || Arc::downgrade(place)).read = segment + 1; + mark.read = segment + 1; } } moves } } -/// A segment's part: the checks at its head and its writes of linked placements, in order. +/// A segment's part: the checks at its head, each with whether a write added it (else a first +/// read of an unmoved texture), and its writes of linked placements, in order. #[derive(Default)] pub(crate) struct Aliased { - checks: Vec>, + checks: Vec<(Arc, bool)>, writes: Vec>, } +impl Aliased { + /// A check of `place` at the segment's head, a write's where `writes`: one for each + /// placement, a write's where any is. + fn check(&mut self, place: &Arc, writes: bool) { + match self.checks.iter_mut().find(|(p, _)| Arc::ptr_eq(p, place)) { + Some((_, by_write)) => *by_write |= writes, + None => self.checks.push((Arc::clone(place), writes)), + } + } +} + impl Placement { /// For the device tests: its links. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -437,9 +511,10 @@ impl Aliased { } } -/// As the submit thread stages a segment whose part is `part`: the moves its checks find owed, -/// recorded into a command buffer of `recorder` that goes ahead of the segment's, each counted -/// (`Metrics::heap_moves`); then its writes, applied in order. `None` where nothing is owed. +/// As the submit thread stages a segment whose part is `part`: the moves its checks find owed (a +/// write's where its texture is stale, any where its texture is unmoved), recorded into a command +/// buffer of `recorder` that goes ahead of the segment's, each counted (`Metrics::heap_moves`); +/// then its writes, applied in order. `None` where nothing is owed. /// /// Err: the Vulkan call that failed, which loses the device. pub(crate) fn stage( @@ -447,10 +522,16 @@ pub(crate) fn stage( recorder: &mut Option, part: &Aliased, ) -> Result, DeviceLoss> { - let moves: Vec> = (part.checks.iter()) - .filter(|place| place.stale.load(Relaxed)) + let owed: Vec<&Arc> = (part.checks.iter()) + .filter(|(place, writes)| place.unmoved() || (*writes && place.stale.load(Relaxed))) + .map(|(place, _)| place) + .collect(); + let moves: Vec> = (owed.iter()) .filter_map(|place| place.moved.map(Moved::barrier)) .collect(); + for place in owed { + place.left_undefined(); + } for place in &part.writes { place.written(); } @@ -516,6 +597,49 @@ pub(crate) unsafe fn host_write(core: &Core, command: vk::CommandBuffer, place: place.written(); } +/// A host read of the heap texture placed as `place` (`Texture::get_bytes`), recorded into +/// `command`, its upload's, under the work lock, ahead of the read's copy: where it is unmoved, +/// its move from undefined, as [`record`] records it, counted (`Metrics::heap_moves`). The read is +/// its first use; the call submits the upload at once, so the move goes ahead of every command +/// buffer committed after the call, as a host write's does ([`host_write`]). Nothing where it owes +/// no move. +/// +/// # Safety +/// +/// As [`host_write`]. +pub(crate) unsafe fn host_read(core: &Core, command: vk::CommandBuffer, place: &Placement) { + let Some(moved) = place.moved.filter(|_| place.unmoved()) else { + return; + }; + let counters = &core.counters; + // SAFETY: the caller's contract. + unsafe { + record( + &core.device, + command, + &[moved.barrier()], + Metric::UploadBarriers, + &mut |m| counters.count(m), + ) + }; + place.left_undefined(); +} + +/// The unmoved textures of the heaps in `block` (a `useHeap:`'s), each of which a command may +/// reach next through the heap with no declaration: nothing, with no lock taken, where the device +/// has none. +pub(crate) fn unmoved(core: &Core, block: BlockId) -> Vec> { + if !core.heap_ids.any_unmoved() { + return Vec::new(); + } + let mut unmoved = Vec::new(); + for heap in core.heap_ids.heaps_in(block) { + let places = lock(heap.places()); + unmoved.extend(places.unmoved.iter().filter_map(Weak::upgrade)); + } + unmoved +} + /// Records `moves`, heap textures' moves from undefined ([`Marks::used`]), into `command`, in one /// barrier that orders every earlier command before them and every later one after, counted in /// `cause`, one of the barrier causes, and each move counted (`Metrics::heap_moves`). diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 8f98201e61..b93790ebce 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -946,13 +946,21 @@ impl ComputeCommandEncoder { /// reading. It declares no access: a dispatch touches its bound slots and the `use_resource` /// declarations, and a kernel that reaches a heap's resources through addresses outside its /// slots already orders against every write since the last barrier, and every dispatch that - /// writes after it before the next barrier orders against it. + /// writes after it before the next barrier orders against it. It is a read of each texture + /// of the heap placed over another resource's bytes and not yet moved from the undefined + /// layout it is made in (`crate::alias`), which a kernel may reach next through an address: + /// its move goes here, after every earlier command of the command buffer that read the bytes + /// it may change. /// /// Err: [`Error::NoSuchBlock`] for a number no handle names. pub fn use_heap(&mut self, heap: BlockId) -> Result<(), Error> { let building = self.building(); let block = building.device.block(heap)?; building.keep_block(&block); + let unmoved = crate::alias::unmoved(building.device.core(), heap); + if !unmoved.is_empty() { + building.places(unmoved.iter().map(|place| (Some(place), Access::Read)))?; + } Ok(()) } diff --git a/crates/metal2vulkan-runtime/src/hazard.rs b/crates/metal2vulkan-runtime/src/hazard.rs index 747e315a20..0c2be803de 100644 --- a/crates/metal2vulkan-runtime/src/hazard.rs +++ b/crates/metal2vulkan-runtime/src/hazard.rs @@ -261,6 +261,16 @@ impl HeapId { false => linked.fetch_sub(1, Relaxed), }; } + + /// A texture of the heap was placed unmoved (`gained`), or moved or was released unmoved + /// (`crate::alias`). + pub(crate) fn unmoved(&self, gained: bool) { + let unmoved = &self.core.heap_ids.unmoved; + match gained { + true => unmoved.fetch_add(1, Relaxed), + false => unmoved.fetch_sub(1, Relaxed), + }; + } } impl Drop for HeapId { @@ -279,6 +289,9 @@ pub(crate) struct HeapIds { /// The device's heap placements that take part (`crate::alias`): while none does, a command's /// uses look at no placement. linked: AtomicUsize, + /// The device's unmoved heap textures (`crate::alias`): while none is, a `useHeap:` looks at no + /// heap. + unmoved: AtomicUsize, } #[derive(Default)] @@ -296,6 +309,20 @@ impl HeapIds { self.linked.load(Relaxed) != 0 } + /// Whether a heap texture of the device is unmoved. + pub(crate) fn any_unmoved(&self) -> bool { + self.unmoved.load(Relaxed) != 0 + } + + /// The live heaps in `block`. + pub(crate) fn heaps_in(&self, block: BlockId) -> Vec> { + let state = crate::device::lock(&self.state); + (state.heaps.iter()) + .filter(|((of, _), _)| *of == block) + .filter_map(|(_, id)| id.upgrade()) + .collect() + } + /// The id of the heap at `offset` in `block`, a new one where no resource of it lives. pub(crate) fn of(&self, core: &Arc, block: BlockId, offset: u64) -> Arc { let mut state = crate::device::lock(&self.state); diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index fb4bdfe6ed..980ad1b692 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -2347,13 +2347,22 @@ impl RenderCommandEncoder { /// order its draws after every earlier command and before every later one. A later draw that /// may read beyond its slots while an attachment of the pass in the heap is out of its home /// layout counts in [`Metrics::unslotted_attachment_reads`](crate::Metrics::unslotted_attachment_reads), as Vulkan leaves - /// such a read undefined. + /// such a read undefined. It is a read of each texture of the heap placed over another + /// resource's bytes and not yet moved from the undefined layout it is made in + /// (`crate::alias`), which a draw may reach next through an address: its move goes at the + /// head of the segment the pass is in. /// /// Err: [`Error::NoSuchBlock`] for a number no handle names. pub fn use_heap(&mut self, heap: BlockId) -> Result<(), Error> { let building = self.building(); let block = building.device.block(heap)?; building.keep_block(&block); + let unmoved = alias::unmoved(building.device.core(), heap); + let uses = alias::uses(unmoved.iter().map(|place| (Some(place), Access::Read))); + if !uses.is_empty() { + // A read moves nothing in place, so the rendering goes on. + building.aliases(&uses, true)?; + } if !self.declared.heaps.contains(&heap) { self.declared.heaps.push(heap); // An attachment in the heap that the pass holds out of its home layout. diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 645dd07cf6..550d1b36de 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -9,7 +9,9 @@ //! where shaders only read it, the attachment layout where only render passes use it. A new image //! moves from undefined to home in the upload of the next commit, ahead of every command buffer //! committed after [`Device::new_texture`] returns, or ahead of its first copy; nothing -//! holds it until then, so a texture released first is freed at once. +//! holds it until then, so a texture released first is freed at once. A heap texture placed over +//! another resource's bytes is the exception: its first use moves it, in the command stream +//! (`crate::alias`). //! //! A texture the runtime places (a new texture of [`Device::new_texture`], //! [`Device::new_texture_for_views`] or [`Device::new_managed_texture`]) reads zero until written: @@ -574,10 +576,6 @@ pub(crate) struct Image { /// dma-buf's import, undefined, as an image made with external memory info is, and its move /// home is an acquire that names the general layout instead (`foreign`, [`homing`](Self::homing)). first: vk::ImageLayout, - /// A heap texture's image placed over bytes another resource of its heap reaches - /// (`crate::alias`): its move home waits for every earlier command's writes. False for every - /// other image. - over: bool, /// In place over a dma-buf's import (`Device::import_dma_buf`, on Unix): the import's buffer /// and the range of it the image's memory is, which its move home acquires from the foreign /// queue family (`VK_QUEUE_FAMILY_FOREIGN_EXT`) in one barrier with the image, so that both @@ -585,8 +583,10 @@ pub(crate) struct Image { foreign: Option<(vk::Buffer, u64, u64)>, /// An upload recorded its move from `first` to `home`. Read and set under the work lock. A /// Direct3D 11 plane is made with it set: it owes no move, as each acquire takes it from the - /// general layout ([`handed`](Self::handed)). An exported surface's plane in place is moved - /// by its making's command buffer instead, on the submit thread ([`making_move`](Self::making_move)). + /// general layout ([`handed`](Self::handed)). So is a heap texture's image placed over another + /// resource's bytes: its first use moves it, in the command stream (`crate::alias`). An + /// exported surface's plane in place is moved by its making's command buffer instead, on the + /// submit thread ([`making_move`](Self::making_move)). homed: AtomicBool, /// How the move home zeroes it, for an image the runtime places for a texture of its own /// (`Source::Plain` and `Source::Managed`); `None` for every other image. @@ -983,18 +983,10 @@ impl Image { .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) .image(self.image) .subresource_range(whole(self.aspects)); - // Placed over another resource's bytes, after every earlier command's writes. - let (stages, written) = match self.over { - true => ( - vk::PipelineStageFlags2::ALL_COMMANDS, - vk::AccessFlags2::MEMORY_WRITE, - ), - false => (vk::PipelineStageFlags2::NONE, vk::AccessFlags2::NONE), - }; let Some(zero) = self.zero else { let first = barrier - .src_stage_mask(stages) - .src_access_mask(written) + .src_stage_mask(vk::PipelineStageFlags2::NONE) + .src_access_mask(vk::AccessFlags2::NONE) .dst_stage_mask(vk::PipelineStageFlags2::ALL_COMMANDS) .dst_access_mask(every) .old_layout(first) @@ -1141,7 +1133,6 @@ impl Image { cube: plan.cube, stand_ins: None, first: vk::ImageLayout::UNDEFINED, - over: false, homed: AtomicBool::new(false), released: Mutex::new(None), zero: None, @@ -1701,7 +1692,6 @@ impl Device { cube: false, stand_ins: None, first: vk::ImageLayout::UNDEFINED, - over: false, // No move home until the consumer acquires it. homed: AtomicBool::new(true), released: Mutex::new(None), @@ -1962,7 +1952,9 @@ impl Device { }) }); // A heap's texture's image is placed among its heap's resources, linked with those whose - // bytes meet its (`crate::alias`). + // bytes meet its (`crate::alias`). Placed over another's bytes, it is unmoved: its first + // use in the command stream moves it from undefined, after every command before it, and + // no upload does. let place = (heap_id.as_ref().zip(heap_at)).map(|(heap, at)| { let moved = Moved { image, @@ -1971,6 +1963,7 @@ impl Device { }; Placement::new(heap, at, at.saturating_add(bytes), Some(moved)) }); + let unmoved = place.as_ref().is_some_and(|place| place.unmoved()); let image = Arc::new(Image { core: Arc::clone(core), image, @@ -1996,9 +1989,9 @@ impl Device { cube: plan.cube, stand_ins: None, first, - over: place.as_ref().is_some_and(|place| place.over()), foreign, - homed: AtomicBool::new(false), + // Unmoved, it owes the uploads no move (`crate::alias`). + homed: AtomicBool::new(unmoved), released: Mutex::new(None), zero, drawable: None, @@ -2061,7 +2054,9 @@ impl Device { inner: Arc::new(inner), device: self.clone(), }; - core.work.home(core, texture.inner.imaged())?; + if !unmoved { + core.work.home(core, texture.inner.imaged())?; + } // Over a Managed buffer's device copy, its buffer keeps what Metal's Managed events owe it // (`crate::over::ManagedOvers`), once the move to its home layout goes ahead of every // later commit, a capture's copy in among them. @@ -5247,6 +5242,11 @@ impl Texture { [Held::Texture(Arc::clone(inner.imaged()))], // SAFETY: as in `replace_region`. |device, command| unsafe { + // An unmoved heap texture moves from undefined before the copy + // (`crate::alias`). + if let Some(place) = inner.placement() { + crate::alias::host_read(core, command, place); + } let region = copy.buffer_image_copy(stage.offset(), 0, 0); inner.record( device, @@ -6986,7 +6986,6 @@ impl Device { cube: false, stand_ins: made.linear_attachment.then(Box::default), first: vk::ImageLayout::UNDEFINED, - over: false, // A Direct3D 11 plane owes no move: each acquire takes it from the general layout // (`Image::handed`). An exported one's is its making's (`Image::making_move`). homed: AtomicBool::new(general), From 55cca59b13ad3f05d98c73c6ad1f4867c54f6b30 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 2 Dec 2026 13:50:51 -0800 Subject: [PATCH 3/6] validation test: an input above the toolchain's newest version is skipped and counted (red) On macos-26, CI's Xcode 26.6 refuses the public fixtures of AIR 2.9 and Metal 4.1, which come from the macOS 27 SDK: `xcrun metallib` says "air version set to 2.9.0 (...), but expecting 2.8" for 31 typed fixtures, and `xcrun metal` says "invalid value 'metal4.1' in '-std=metal4.1'" for the 10 sources that name metal4.1. typed_fixtures_round_trip and msl_fixtures_round_trip fail on them. round_trip_all now keeps each input's outcome in a Tally, whose finish lists every skipped input and the total above the toolchain's newest version. The tests own their inputs and need no Mac: a fixture of AIR 2.9 refused by a toolchain that states 2.8, and a source naming metal4.1 refused by a compiler whose notes offer up to metal4.0, are each to be skipped and counted; every other error (another metallib error, a refusal whose expected version is not below the input's or names another version, a refused standard the source does not name or that the compiler offers, any other compiler error) is a failure, and a failure fails the round trip. Red here: Tally::refused files every refusal as a failure, so the two skip tests fail. --- .../src/air_writer/tests.rs | 143 ++++++++++++++++-- 1 file changed, 131 insertions(+), 12 deletions(-) diff --git a/crates/metal2vulkan-validation/src/air_writer/tests.rs b/crates/metal2vulkan-validation/src/air_writer/tests.rs index eb6439fdb4..dd28ab703d 100644 --- a/crates/metal2vulkan-validation/src/air_writer/tests.rs +++ b/crates/metal2vulkan-validation/src/air_writer/tests.rs @@ -558,8 +558,46 @@ fn float_constants_widen_exactly() { assert_eq!(f32_bits_as_f64(0xFF80_0001), 0xFFF0_0000_2000_0000); } -/// Round trip every input. An input the decoder itself refuses is outside the writer's domain -/// (the writer spells decoded IR): it is listed visibly, not failed. +/// What became of a round trip's inputs: how many round-tripped, the inputs the decoder refuses +/// (outside the writer's domain: the writer spells decoded IR), the inputs above the newest +/// version the toolchain takes, and the failures. +#[derive(Default)] +struct Tally { + written: usize, + undecodable: Vec, + above: Vec, + failures: Vec, +} + +impl Tally { + /// A step on the input at `path` failed with `error`: a failure. + fn refused(&mut self, path: &Path, error: &str) { + self.failures.push(format!("{}: {error}", path.display())); + } + + /// Lists each skipped input, and the total of those above the toolchain's newest version; then + /// fails on any failure, or where nothing of the `inputs` round-tripped. + fn finish(self, what: &str, inputs: usize) { + for u in &self.undecodable { + eprintln!("{what}: SKIP (the decoder refuses the input): {u}"); + } + for a in &self.above { + eprintln!("{what}: SKIP (above the toolchain's newest version): {a}"); + } + if !self.above.is_empty() { + eprintln!( + "{what}: SKIP {} of {inputs} inputs above the toolchain's newest version", + self.above.len() + ); + } + assert!(self.failures.is_empty(), "{}", self.failures.join("\n\n")); + assert!(self.written > 0, "{what}: nothing round-tripped"); + eprintln!("{what}: {} of {inputs} inputs round-trip", self.written); + } +} + +/// Round trip every input, each outcome in a [`Tally`]: an input the decoder itself refuses is +/// listed visibly, not failed. fn round_trip_all( what: &str, inputs: &[PathBuf], @@ -567,35 +605,116 @@ fn round_trip_all( package: Option<&ScratchDir>, ) { assert!(!inputs.is_empty(), "{what}: no inputs"); - let (mut failures, mut undecodable, mut written) = (Vec::new(), Vec::new(), 0); + let mut tally = Tally::default(); for path in inputs { let original = match bitcode(path) { Ok(bytes) => decode_bytes(&bytes), Err(e) => { - failures.push(format!("{}: {e}", path.display())); + tally.refused(path, &e); continue; } }; let original = match original { Ok(d) => d, Err(e) => { - undecodable.push(format!("{}: {e}", path.display())); + tally.undecodable.push(format!("{}: {e}", path.display())); continue; } }; let result = round_trip(&original) .and_then(|air| package.map_or(Ok(()), |scratch| metallib(&air, scratch))); match result { - Ok(()) => written += 1, - Err(e) => failures.push(format!("{}: {e}", path.display())), + Ok(()) => tally.written += 1, + Err(e) => tally.refused(path, &e), } } - for u in &undecodable { - eprintln!("{what}: SKIP (the decoder refuses the input): {u}"); + tally.finish(what, inputs.len()); +} + +/// An Xcode older than the SDK the fixtures were compiled with refuses their AIR version +/// (`xcrun metallib` of Xcode 26.6 on a fixture of AIR 2.9): the input is skipped, listed and +/// counted, not failed. The input is a fixture of AIR 2.9 (its own `!air.version`), refused by a +/// toolchain that states 2.8 as the version it expects. +#[test] +fn an_input_above_the_toolchain_s_air_version_is_skipped_and_counted() { + let path = fixtures().join("engine").join("air_2_9_front_end.air.ll"); + let refusal = "metallib: error: air version set to 2.9.0 (!10 = !{i32 2, i32 9, i32 0}), but \ + expecting 2.8\n"; + let mut tally = Tally::default(); + tally.refused(&path, refusal); + assert_eq!(tally.failures, Vec::::new()); + assert_eq!(tally.above.len(), 1, "{:?}", tally.above); + assert!(tally.above[0].contains("air_2_9_front_end.air.ll")); +} + +/// An Xcode older than the SDK the fixtures were compiled with refuses the Metal standard a source +/// names (`xcrun metal -std=metal4.1` of Xcode 26.6, whose newest is metal4.0): the source is +/// skipped, listed and counted, not failed. The input is a fixture whose `// metal-std:` names +/// metal4.1, refused by a compiler whose notes offer standards up to metal4.0. +#[test] +fn a_source_above_the_compiler_s_metal_standard_is_skipped_and_counted() { + let path = fixtures().join("engine").join("a27_memory_order.metal"); + let refusal = "a27_memory_order.metal: error: invalid value 'metal4.1' in '-std=metal4.1'\n\ + note: use 'macos-metal2.4' for 'Metal 2.4 (macOS)' standard\n\ + note: use 'metal3.2' for 'Metal 3.2' standard\n\ + note: use 'metal4.0' for 'Metal 4.0' standard\n"; + let mut tally = Tally::default(); + tally.refused(&path, refusal); + assert_eq!(tally.failures, Vec::::new()); + assert_eq!(tally.above.len(), 1, "{:?}", tally.above); + assert!(tally.above[0].contains("a27_memory_order.metal")); +} + +/// Every other toolchain error still fails: another metallib error; a version refusal whose +/// expected version is not below the input's, or that names a version the input does not state; a +/// compiler refusal of a standard the source does not name, or where the compiler offers the +/// source's; any other compiler error. +#[test] +fn every_other_toolchain_error_fails() { + let air = fixtures().join("engine").join("air_2_9_front_end.air.ll"); + let msl = fixtures().join("engine").join("a27_memory_order.metal"); + let errors = [ + (&air, "metallib: error: undefined symbol '_air.foo'\n"), + ( + &air, + "metallib: error: air version set to 2.9.0 (!10 = !{i32 2, i32 9, i32 0}), but \ + expecting 2.9\n", + ), + ( + &air, + "metallib: error: air version set to 2.7.0 (!10 = !{i32 2, i32 7, i32 0}), but \ + expecting 2.6\n", + ), + ( + &msl, + "error: invalid value 'metal4.2' in '-std=metal4.2'\n\ + note: use 'metal4.0' for 'Metal 4.0' standard\n", + ), + ( + &msl, + "error: invalid value 'metal4.1' in '-std=metal4.1'\n\ + note: use 'metal4.1' for 'Metal 4.1' standard\n", + ), + (&msl, "error: use of undeclared identifier 'foo'\n"), + ]; + for (path, error) in errors { + let mut tally = Tally::default(); + tally.refused(path, error); + assert_eq!((tally.failures.len(), tally.above.len()), (1, 0), "{error}"); } - assert!(failures.is_empty(), "{}", failures.join("\n\n")); - assert!(written > 0, "{what}: nothing round-tripped"); - eprintln!("{what}: {written} of {} inputs round-trip", inputs.len()); +} + +/// A failure fails the round trip, a skip beside it included. +#[test] +#[should_panic(expected = "undefined symbol")] +fn a_failure_fails_the_round_trip() { + let tally = Tally { + written: 1, + above: vec!["skipped.air.ll: the input's AIR 2.9.0, the toolchain's newest AIR 2.8".into()], + failures: vec!["failed.air.ll: metallib: error: undefined symbol '_air.foo'".into()], + ..Tally::default() + }; + tally.finish("a_failure_fails_the_round_trip", 2); } #[test] From da37e9e5df4288b547bed8c3d4480fbfe137214b Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 2 Dec 2026 13:54:10 -0800 Subject: [PATCH 4/6] validation test: skip an input whose version the toolchain refuses as above its newest Tally::refused now reads the input's own version and keys the skip on the toolchain's own refusal of it, compared with the version the toolchain says it takes: - typed AIR: the input's `!air.version` node, and `xcrun metallib`'s "air version set to X (...), but expecting Y". Skipped only where X is the input's version and Y is below it. - MSL: the source's `// metal-std:` standard S, and `xcrun metal`'s "invalid value 'S' in '-std=S'". Skipped only where every `metalX.Y` the compiler's notes offer is below S. Anything else stays a failure. finish lists each skipped input with both versions, then prints "SKIP of inputs above the toolchain's newest version". Over the public fixtures, 31 of 582 typed inputs state AIR 2.9.0 (545 state 2.8.0, the rest older) and 10 of 747 MSL sources name metal4.1. Those are the counts of the two refusals in CI run 46959260218 on macos-26 (31 and 10). On that runner, the two round trips should print "SKIP 31 of 582" and "SKIP 10 of 747" and pass. ci.yml is unchanged. The macos-26 arm64 image 20261123.0526.1 carries Xcode 26.0.1 to 26.6 (default 26.6) and SDKs up to macOS 26.5, so no Xcode on it takes AIR 2.9. --- .../src/air_writer/tests.rs | 78 ++++++++++++++++++- 1 file changed, 76 insertions(+), 2 deletions(-) diff --git a/crates/metal2vulkan-validation/src/air_writer/tests.rs b/crates/metal2vulkan-validation/src/air_writer/tests.rs index dd28ab703d..55218700e9 100644 --- a/crates/metal2vulkan-validation/src/air_writer/tests.rs +++ b/crates/metal2vulkan-validation/src/air_writer/tests.rs @@ -570,9 +570,20 @@ struct Tally { } impl Tally { - /// A step on the input at `path` failed with `error`: a failure. + /// A step on the input at `path` failed with `error`: skipped where it is the toolchain's own + /// refusal of the version the input states, above the newest version the toolchain says it + /// takes ([`air_ceiling`], [`std_ceiling`]); else a failure. fn refused(&mut self, path: &Path, error: &str) { - self.failures.push(format!("{}: {error}", path.display())); + let text = std::fs::read_to_string(path).unwrap_or_default(); + let above = (air_version_of(&text).and_then(|input| air_ceiling(error, input))) + .or_else(|| metal_std_of(&text).and_then(|std| std_ceiling(error, std))); + match above { + Some((input, newest)) => self.above.push(format!( + "{}: the input's {input}, the toolchain's newest {newest}", + path.display() + )), + None => self.failures.push(format!("{}: {error}", path.display())), + } } /// Lists each skipped input, and the total of those above the toolchain's newest version; then @@ -596,6 +607,69 @@ impl Tally { } } +/// The dotted numbers of `version` (`2.9.0`, `2.8`), as major, minor and patch, a missing one 0. +fn version_numbers(version: &str) -> Option<[u32; 3]> { + let mut numbers = [0; 3]; + for (at, part) in version.split('.').enumerate() { + *numbers.get_mut(at)? = part.parse().ok()?; + } + Some(numbers) +} + +/// The AIR version typed AIR text states: the operands of the node its `!air.version` names. +fn air_version_of(text: &str) -> Option<[u32; 3]> { + let node = (text.lines()) + .find_map(|l| l.strip_prefix("!air.version = !{!"))? + .strip_suffix('}')?; + let prefix = format!("!{node} = !{{"); + let operands = (text.lines()) + .find_map(|l| l.strip_prefix(prefix.as_str()))? + .strip_suffix('}')?; + let numbers: Vec = (operands.split(',')) + .map(|o| o.trim().strip_prefix("i32 ")?.parse().ok()) + .collect::>()?; + numbers.try_into().ok() +} + +/// The Metal standard an MSL source names: its `// metal-std:` line. +fn metal_std_of(text: &str) -> Option<&str> { + (text.lines()) + .find_map(|l| l.trim().strip_prefix("// metal-std:")) + .map(str::trim) +} + +/// `xcrun metallib`'s refusal of an input of AIR version `input` in `error`: "air version set to +/// X (...), but expecting Y", where X is the input's own version and Y, the version the toolchain +/// says it expects, is below it. The two versions as text; `None` for any other error. +fn air_ceiling(error: &str, input: [u32; 3]) -> Option<(String, String)> { + let (set, rest) = error.split_once("air version set to ")?.1.split_once(' ')?; + let expecting = rest + .split_once("but expecting ")? + .1 + .split_whitespace() + .next()?; + let ok = version_numbers(set)? == input && version_numbers(expecting)? < input; + ok.then(|| (format!("AIR {set}"), format!("AIR {expecting}"))) +} + +/// `xcrun metal`'s refusal of the Metal standard `std` a source names, in `error`: "invalid value +/// 'S' in '-std=S'" with S the source's own, where every `metalX.Y` standard the compiler's notes +/// offer is below it. The source's standard and the newest offered; `None` for any other error. +fn std_ceiling(error: &str, std: &str) -> Option<(String, String)> { + if !error.contains(&format!("invalid value '{std}' in '-std={std}'")) { + return None; + } + let input = version_numbers(std.strip_prefix("metal")?)?; + let newest = (error.lines()) + .filter_map(|l| l.split_once("note: use 'metal")?.1.split_once('\'')) + .filter_map(|(offered, _)| version_numbers(offered)) + .max()?; + (newest < input).then(|| { + let newest = format!("metal{}.{}", newest[0], newest[1]); + (std.to_string(), newest) + }) +} + /// Round trip every input, each outcome in a [`Tally`]: an input the decoder itself refuses is /// listed visibly, not failed. fn round_trip_all( From 4329b35edb8709dd07af75bcbf14190fc492878b Mon Sep 17 00:00:00 2001 From: atinseau <65445747+atinseau@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:50:01 +0100 Subject: [PATCH 5/6] Expose the shared ranges retained by a recorded command buffer --- crates/metal2vulkan-runtime/src/coherence.rs | 4 +++ crates/metal2vulkan-runtime/src/command.rs | 30 +++++++++++++++++++ crates/metal2vulkan-runtime/src/encoder.rs | 1 + crates/metal2vulkan-runtime/src/lib.rs | 2 +- .../src/render_encoder.rs | 3 +- .../metal2vulkan-runtime/src/tests/command.rs | 20 +++++++++++++ 6 files changed, 58 insertions(+), 2 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/coherence.rs b/crates/metal2vulkan-runtime/src/coherence.rs index 52b7fed67d..134f600a8a 100644 --- a/crates/metal2vulkan-runtime/src/coherence.rs +++ b/crates/metal2vulkan-runtime/src/coherence.rs @@ -108,6 +108,10 @@ impl Range { ) } + pub(crate) fn intersects(self, other: Range) -> bool { + self.memory == other.memory && self.start < other.end && other.start < self.end + } + fn bytes(self) -> u64 { self.end - self.start } diff --git a/crates/metal2vulkan-runtime/src/command.rs b/crates/metal2vulkan-runtime/src/command.rs index f0c34dcb5f..ad2d34d818 100644 --- a/crates/metal2vulkan-runtime/src/command.rs +++ b/crates/metal2vulkan-runtime/src/command.rs @@ -243,6 +243,7 @@ pub(crate) struct Building { /// Whether the first command buffer began: the pair was taken, and where one was, the start /// timestamp recorded. started: bool, + pub(crate) may_use_unbound_memory: bool, /// Its pair of timestamp queries, from its first record; None before it and where it runs /// untimed. stamps: Option, @@ -477,6 +478,18 @@ impl Pending { } } +/// Shared memory explicitly retained by a recorded command buffer. +pub struct RetainedSharedRanges(Vec); + +impl RetainedSharedRanges { + /// Whether a buffer overlaps retained shared storage, or cannot be classified. + pub fn may_touch(&self, buffer: &Buffer) -> bool { + buffer.shared_range(1).is_none_or(|range| { + self.0.iter().any(|retained| retained.intersects(range)) + }) + } +} + impl CommandBuffer { /// A new command buffer of `queue`, which counted it live, keeping its objects in `kept`, /// empty, the lists of a retired one where the queue had them. @@ -515,6 +528,7 @@ impl CommandBuffer { completed: Vec::new(), }, started: false, + may_use_unbound_memory: false, stamps: None, owed: None, owed_all: false, @@ -551,6 +565,22 @@ impl CommandBuffer { f(state.open()?) } + /// Shared storage retained by buffers, textures and heaps in this recording. + /// Returns `None` if a draw or dispatch can access storage through an unbound address. + /// The caller must take this snapshot after encoding and before committing. + pub fn retained_shared_ranges(&self) -> Result, Error> { + self.building(|building| { + if building.may_use_unbound_memory { + return Ok(None); + } + let gpu = &building.gpu; + let ranges = Ranges::of(&gpu.kept, &gpu.blocks, &coherence::Writes::default(), 1); + Ok(Some(RetainedSharedRanges( + ranges.map_or_else(Vec::new, |ranges| ranges.reached), + ))) + }) + } + /// Takes what is being recorded for an encoder, until [`close_encoder`](Self::close_encoder). /// Err: [`Refusal::Committed`]; [`Refusal::EncoderOpen`]. pub(crate) fn open_encoder(&self) -> Result { diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index b93790ebce..590299e336 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1368,6 +1368,7 @@ impl ComputeCommandEncoder { // memory outside its resources, or such an image is ahead of its buffer, and among // the buffers it reaches only in the last two. let unbound = interface.reads_unbound || interface.writes_unbound; + building.may_use_unbound_memory |= unbound; let ahead = building.overs_ahead(); if building.copies_over() && (unbound || self.copied > 0 || ahead) { let reached = accesses.overs(interface, unbound || ahead, false); diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 2b56804668..159053efb6 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -77,7 +77,7 @@ pub use arrays::{IndexClass, IndexGrant, ResourceId}; pub use blit::{BlitCommandEncoder, BlitOption, BufferLayout, TexturePlace}; pub use block::Block; pub use buffer::{Buffer, MAX_BUFFER_LENGTH}; -pub use command::{CommandBuffer, CommandBufferError, CommandBufferStatus, DeviceLoss}; +pub use command::{CommandBuffer, CommandBufferError, CommandBufferStatus, DeviceLoss, RetainedSharedRanges}; pub use counters::{ Counters, Gauges, Metrics, OverCause, OverCopyKind, SiteAllocations, Timed, VariantMake, VariantStart, diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index ac8e0e78f8..ae5b0812c4 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -3625,12 +3625,13 @@ impl RenderCommandEncoder { .filter_map(|&(_, index)| tables[VERTEX].buffer(index)) .chain(index.into_iter().flatten().map(BufferObject::object)) .chain(factors); + let unbound = draws.reads_unbound || draws.writes_unbound || commands; + building.may_use_unbound_memory |= unbound; let copies = match overs { false => over::Copies::default(), true => { // The buffers it reads owe copies back only where it reaches memory outside its // resources or such an image is ahead of its buffer. - let unbound = draws.reads_unbound || draws.writes_unbound || commands; let buffers = unbound || building.overs_ahead(); let vertex = (vertex_reads.clone()) .filter(|_| buffers) diff --git a/crates/metal2vulkan-runtime/src/tests/command.rs b/crates/metal2vulkan-runtime/src/tests/command.rs index 84efa0647b..65fe9118ac 100644 --- a/crates/metal2vulkan-runtime/src/tests/command.rs +++ b/crates/metal2vulkan-runtime/src/tests/command.rs @@ -489,6 +489,26 @@ pub(crate) mod on_device { .expect("a fill"); } + #[test] + fn retained_ranges_distinguish_buffers_sharing_an_allocation() { + each_device("retained_ranges", |_, _, device| { + let mut arena = Arena::new(&device); + let used = arena.buffer(); + let unused = arena.buffer(); + let alias = device.new_buffer(arena.block.id, 64, 64, None).expect("an alias"); + let queue = device.new_command_queue(4).expect("a queue"); + let cb = queue.command_buffer().expect("a command buffer"); + let mut blit = cb.blit_command_encoder().expect("a blit encoder"); + blit.fill_buffer(&used, 0..used.length(), 0x7f).expect("a fill"); + blit.end_encoding(); + + let retained = cb.retained_shared_ranges().expect("a scope").expect("known storage"); + assert!(retained.may_touch(&used)); + assert!(retained.may_touch(&alias)); + assert!(!retained.may_touch(&unused)); + }); + } + /// A buffer's first word, as the host reads it. pub(crate) fn word(buffer: &Buffer) -> u32 { let contents = buffer.contents().expect("a Shared buffer"); From 4b68c1095a2ebf047b60c65dcb31af06003c97ca Mon Sep 17 00:00:00 2001 From: "ios-linux-sync[bot]" Date: Sun, 6 Dec 2026 13:08:59 +0000 Subject: [PATCH 6/6] chore(sync): record upstream metadata for x86sim/metal2vulkan@4329b35edb87 --- .github/upstream-sync-state.json | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 .github/upstream-sync-state.json diff --git a/.github/upstream-sync-state.json b/.github/upstream-sync-state.json new file mode 100644 index 0000000000..a54f27641f --- /dev/null +++ b/.github/upstream-sync-state.json @@ -0,0 +1,12 @@ +{ + "upstream_repo": "x86sim/metal2vulkan", + "upstream_branch": "x86sim", + "upstream_sha": "4329b35edb8709dd07af75bcbf14190fc492878b", + "maintained_branch": "drill/sync-clean-20261206", + "maintained_base_sha": "881c20164ac323c0220dea6d630b6b94d64e3a72", + "commits_merged": 6, + "latest_upstream_release": "", + "recent_upstream_releases": [], + "synced_at_utc": "2026-12-06T13:08:58.014953+00:00", + "status": "pending_review" +}