From d62e1d2bd95a9e5fe12cab359e3341b1b8003e37 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 15 Nov 2026 13:46:15 -0800 Subject: [PATCH] RUNTIME 2382: a heap's decoded-format texture on a shadow route keeps a decoded twin Under DevicePolicy::exact_answers (HeapAnswerPolicy::Metal) a heap's PVRTC or ETC2 texture on RADV PHOENIX misses Metal's answer (its BC1 carrier image takes 4096 B @ 4096, Metal answers 128 @ 128 or 2048 @ 128), so it lies in memory of its own as a shadow of the heap's bytes (MemoryShadow; Shadow or Tiled where those serve). heap_texture_at gave a decoded twin only to the Direct, HostTransfer, Linear and Hidden routes, so its sampled view fell to the carrier, which has no sampled usage, and every kernel read and sample was refused, Unsupported(Format) (8 of 8 cases in m3-max-33467), where Metal samples it and the device can decode it. A heap's PVRTC, ETC2 or EAC texture on a shadow route (not over the caller's host pages, not detached) now gets its decoded twin. ShadowCopy::record_gated records the shadow's decode (ShadowCopies::decode) after a copy in that moved texels, and only then (record_moves answers whether it moved any); the pass is set at making (Image::decode_after_copies_in) and its kernel is made in ShadowCopies::prepare at first use, so no making compiles. WorkCounts::shadow_twin_decodes counts the decodes. 4:2:2 heap shadows stay twinless; heaps over the caller's host pages stay the documented copies-alone gap. Docs: decoded_twin.rs, pvrtc.rs, etc.rs, degradation.rs, docs/API.md, docs/FAST-PATHS.md (heap shadows of decoded formats are no longer for copies alone). New device test runtime_lane/heap_carried_reads.rs. Public surface: WorkCounts (for the lanes) gains shadow_twin_decodes, blessed in api_signatures.tsv. Verified: PHOENIX m3-max-33568 (carried binary of the lane tip d5bf9cac82): heap_carried_reads, a_carried_heap_texture_reads_its_bytes_with_no_commit, pvrtc_texels_read_as_metal_s and etc_texels_read_as_metal_s pass. Under HeapAnswerPolicy::Metal all 8 cases shadowed; a use takes 1 copy and 1 decode, a second encoder in the same command buffer 0 and 0; kernel reads, samples, blit out and getBytes equal the texture outside a heap, and samples follow a blit and a replaceRegion. Under HeapAnswerPolicy::Device: not shadowed, 0 copies, 0 decodes, equal. Without the fix (33467 at the test commit) all 8 reads were refused. lavapipe (msi 33535): the 4 tests pass. Clippy x3 running in 33569. --- .../src/buffer_texture.rs | 3 + .../metal2vulkan-runtime/src/degradation.rs | 7 +- crates/metal2vulkan-runtime/src/encoder.rs | 5 +- crates/metal2vulkan-runtime/src/etc.rs | 7 +- crates/metal2vulkan-runtime/src/pvrtc.rs | 8 +- crates/metal2vulkan-runtime/src/shadow.rs | 109 +++- .../metal2vulkan-runtime/src/tests/shadow.rs | 2 + .../src/texture/decoded_twin.rs | 41 +- .../metal2vulkan-runtime/src/texture/faces.rs | 1 + .../metal2vulkan-runtime/src/texture/heap.rs | 29 +- .../src/texture/surface_depth.rs | 1 + .../src/texture/surface_pairs.rs | 1 + .../src/texture/surface_two_planes.rs | 1 + .../src/texture/view_shadow.rs | 1 + .../src/texture/ycbcr_image.rs | 3 + .../metal2vulkan-runtime/src/work_counts.rs | 13 + .../src/runtime_lane.rs | 2 + .../src/runtime_lane/first_use.rs | 29 +- .../src/runtime_lane/heap_carried_reads.rs | 513 ++++++++++++++++++ crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/API.md | 9 +- docs/FAST-PATHS.md | 11 +- 23 files changed, 741 insertions(+), 58 deletions(-) create mode 100644 crates/metal2vulkan-validation/src/runtime_lane/heap_carried_reads.rs diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index bdb7879b9..07f17ab96 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -2035,6 +2035,7 @@ impl Texels { tracked: self.tracked(), drops_writes: false, levels: None, + decode: Default::default(), backing: self.backing(), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), @@ -2377,6 +2378,7 @@ impl Texels { tracked: texels.tracked(), drops_writes: false, levels: None, + decode: Default::default(), backing: texels.backing(), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), @@ -2526,6 +2528,7 @@ impl Texels { tracked: self.tracked(), drops_writes: false, levels: None, + decode: Default::default(), backing: self.backing(), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index e122130e9..f7588a137 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2034,7 +2034,9 @@ degradations! { /// value (`decoded-texel-precision`), a PVRTC texture's, an ASTC sRGB one's and an 8-bit /// ETC2 or EAC one's 8-bit codes, exact, an ASTC HDR texture's halves, exact, decoded /// after each write into it (a PVRTC - /// texture's whole levels). An ASTC texture's first view in its other colour space gives + /// texture's whole levels); a heap's texture whose image is a shadow of the heap's bytes + /// (`texture/heap.rs`), its whole twin after each copy in that moves its blocks. An ASTC + /// texture's first view in its other colour space gives /// it a second twin of that form's decode. Also a texture of a 4:2:2 format (`GBGR422`, /// `BGRG422`) on every device, whose Vulkan formats are viewed only through a sampler /// Y′CbCr conversion: its texels' bytes lie in an `R8G8_UNORM` carrier, and its twin holds @@ -2052,7 +2054,8 @@ degradations! { does not take those codes), two for an ASTC texture viewed in both colour \ spaces, and a decode after each write into it: a pass on the GPU for a blit, a copy from a texture or a CPU copy through a \ submission; on the CPU, on the device's decode thread, where its CPU copies go on \ - the host or the staging queue"; + the host or the staging queue; and a pass on the GPU after each copy in that moves \ + the blocks of a heap's texture whose image shadows the heap's bytes"; /// A texture with an ASTC LDR decoded twin (`carried-decoded-twin`) of 8-bit codes, or an /// EAC 11-bit one of 16-bit codes: Metal decodes an ASTC LDR channel /// to a 12-bit value (`C >> 4` over 4095 of the 16-bit interpolated channel `C`), which the diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index acd17664b..23d9f5bdf 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -2391,8 +2391,9 @@ impl EncoderCore { // What a copy records beyond what the texture holds from its making: a converted // two-plane YCbCr texture's conversion, made at its first use of its image; a 4:2:2 // texture's set over its buffer's `VkBuffer` now, held until the command buffer completes; - // the kernel and sets of a tiled or two-plane heap texture's moves and of a YCbCr write - // shadow's write-back, made at its first use. + // the kernel and sets of a tiled or two-plane heap texture's moves, of a YCbCr write + // shadow's write-back and of a heap carrier's decode after its copies in, made at its + // first use. for shadow in shadows { if let Some(held) = shadow.copies.prepare()? { self.retain_shared(held); diff --git a/crates/metal2vulkan-runtime/src/etc.rs b/crates/metal2vulkan-runtime/src/etc.rs index 114448941..0f44fb478 100644 --- a/crates/metal2vulkan-runtime/src/etc.rs +++ b/crates/metal2vulkan-runtime/src/etc.rs @@ -25,9 +25,10 @@ //! `carried-decoded-twin`. //! Refused: a view of another decode (an `R11` or `RG11` format's other signedness; //! `Feature::TextureView`) and a sparse heap's texture (`RuntimeGap::DecodedHeapTexture`). A -//! texture without a twin (a heap's over the caller's host pages or laid out apart from the -//! heap's bytes) holds its blocks for copies alone, and a command that binds it for a read is -//! refused. A shader write and an attachment take no such image: Metal's functions write no +//! heap's texture whose image shadows the heap's bytes keeps a twin, decoded after each copy in +//! that moves its blocks (`texture/heap.rs`). A texture without a twin (a heap's over the +//! caller's host pages) holds its blocks for copies alone, and a command that binds it for a +//! read is refused. A shader write and an attachment take no such image: Metal's functions write no //! compressed texture, and no pass renders into one. use super::image_plan::{sample_count, ImageFacts, ImagePlan}; diff --git a/crates/metal2vulkan-runtime/src/pvrtc.rs b/crates/metal2vulkan-runtime/src/pvrtc.rs index 5ab123a53..76c285548 100644 --- a/crates/metal2vulkan-runtime/src/pvrtc.rs +++ b/crates/metal2vulkan-runtime/src/pvrtc.rs @@ -44,9 +44,11 @@ //! (`bind::pvrtc_decode_module`), or a host write's on the CPU. Announced //! `carried-decoded-twin` (the twin's memory and the decodes). A shader write and an attachment //! take no such image: Metal's functions write no compressed texture, and no pass renders into -//! one. A texture without a twin (memoryless, sparse, or a heap's over the caller's host pages or -//! laid out apart from the heap's bytes) holds its blocks for copies alone, and a command that -//! binds it for a read is refused (the twin's format's sampled usage, which its image lacks). +//! one. A heap's texture whose image shadows the heap's bytes keeps a twin, decoded after each +//! copy in that moves its blocks (`texture/heap.rs`). A texture without a twin (memoryless, +//! sparse, or a heap's over the caller's host pages) holds its blocks for copies alone, and a +//! command that binds it for a read is refused (the twin's format's sampled usage, which its +//! image lacks). //! - **Through handles.** A function that reads texture handles from memory may reach a texture //! without a twin made resident, or bound in a stage that reads handles, and the runtime does not //! know which of the textures it reaches the function reads: the handle's element is the neutral diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index e359959fa..2f920c0c6 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -282,6 +282,7 @@ use super::shadow_copy_back::{CopyBack, WordView}; use super::shadow_merge::{ScratchSpares, ShadowMerge, UnormView}; use super::shadow_standing::{Missed, StandingAcross}; use super::texture::copy_images::UseMaker; +use super::texture::decoded_twin::DecodePass; use super::texture::heap_tiled::{HeapTiledCopies, SampleMoves}; use super::texture::heap_two_planes::{HeapPlaneCopies, TwoPlaneHeapLayout}; use super::texture::surface_pairs::PairsConversion; @@ -298,7 +299,7 @@ use metal2vulkan::metal::PixelFormat; use std::any::Any; use std::ops::Range; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Weak}; +use std::sync::{Arc, OnceLock, Weak}; /// What a shadowed texture's copies need: its truth, its shadow, and the copies between them. pub(super) struct ShadowCopies { @@ -331,6 +332,46 @@ pub(super) struct ShadowCopies { /// `Buffer::new_tiled_texture`): when it is taken and how its later levels are made. `None` /// for every other shadow. pub(super) levels: Option, + /// Where the shadow is a carrier with a decoded twin (a heap's PVRTC, ETC2 or EAC texture on + /// a device without the format, whose image shadows the heap's bytes, `texture/heap.rs`): the + /// decode of its whole image into the twin, recorded after each copy in that moved texels + /// ([`ShadowCopy::record_gated`]), so every command after it reads the blocks the copy + /// brought as Metal's decode. Set once, as the twin is made; empty for every other shadow. + pub(super) decode: OnceLock, +} + +/// A shadowed carrier's decode into its decoded twin after each copy in +/// ([`ShadowCopies::decode`]): a pass over its whole image with a scratch of its own +/// (`texture/decoded_twin.rs`), its kernel made at the texture's first use +/// ([`ShadowCopies::prepare`]), never as it is made. One pass serves every copy in: each records +/// it behind a barrier from everything before it, the tracker orders the copies in of the +/// shadow's command buffers (each writes the shadow), and the pass's scratch lives with the +/// texture. +pub(super) struct ShadowDecode { + device: Device, + pass: DecodePass, +} + +impl ShadowDecode { + /// `pass` of the texture's image on `device`. + pub(super) fn new(device: Device, pass: DecodePass) -> ShadowDecode { + ShadowDecode { device, pass } + } + + /// Record the pass, counted (`WorkCounts::shadow_twin_decodes`). Nothing where its kernel is + /// not made, which every use that records a copy in made first. + /// + /// # Safety + /// + /// As [`DecodePass::record`]. + unsafe fn record(&self, device: &Vk, command_buffer: vk::CommandBuffer) { + if !self.pass.is_made() { + return; + } + // SAFETY: the caller's. + unsafe { self.pass.record(device, command_buffer) }; + self.device.shared().counts.shadow_twin_decode(); + } } /// A tiled texture's image of every level over a buffer's bytes (`Buffer::new_tiled_texture`), a @@ -890,10 +931,14 @@ impl ShadowCopies { /// (`PairsConversion::make`), which the command buffer of the copy's command holds until it /// completes (returned); the kernel and sets of a tiled heap texture's moves /// (`HeapTiledCopies::make`), of a heap two-plane texture's (`HeapPlaneCopies::make`), and of - /// a YCbCr write or render shadow's write-back and load (`YCbCrWriteBack::make`), which their + /// a YCbCr write or render shadow's write-back and load (`YCbCrWriteBack::make`), and of a + /// shadowed carrier's decode after its copies in ([`ShadowCopies::decode`]), which their /// making leaves to their first use (`owned_kernel::FirstUse`). Refused as the conversion's, - /// the moves' or the write-back's making is. + /// the moves', the write-back's or the decode's making is. pub(super) fn prepare(&self) -> Result>, Error> { + if let Some(decode) = self.decode.get() { + decode.pass.make(&decode.device)?; + } match &self.source { ShadowSource::Converted { conversion, buffer, .. @@ -2299,6 +2344,33 @@ impl ShadowCopy { back: Option<&RowCopies>, gate: Option>, ) { + // SAFETY: the caller's. + let moved = unsafe { self.record_moves(device, command_buffer, back, gate) }; + // A carrier's decoded twin decoded from the blocks a copy in just brought, where it moved + // any ([`ShadowCopies::decode`]). + if let (true, Step::Into, Some(decode)) = (moved, &self.step, self.copies.decode.get()) { + // SAFETY: the caller's contract: recording outside a render pass, on the encoder's + // queue (whose family runs compute: a blit's decode records there too), the texture + // (its image and twin, which the decode's pass names) live until it completes, both + // images in the `GENERAL` layout. + unsafe { decode.record(device, command_buffer) }; + } + } + + /// [`record_gated`](Self::record_gated)'s copy alone: whether it moved any texel into the + /// shadow (a copy in; a copy back answers `true` whatever it moved), `false` where its + /// rectangle holds no texel or its gate chose no region. + /// + /// # Safety + /// + /// As [`record`](Self::record). + unsafe fn record_moves( + &self, + device: &Vk, + command_buffer: vk::CommandBuffer, + back: Option<&RowCopies>, + gate: Option>, + ) -> bool { let c = &self.copies; if let (Some(value), Some(image)) = (&self.clear, c.cleared_image()) { let range = vk::ImageSubresourceRange { @@ -2319,7 +2391,7 @@ impl ShadowCopy { &[range], ); } - return; + return true; } let moves = self.moves.as_deref(); let into_shadow = match &self.step { @@ -2327,11 +2399,13 @@ impl ShadowCopy { Step::Back => false, // SAFETY: the caller's contract, which the merge's records take. Step::Keep(merge) => { - return unsafe { merge.record_keep(device, command_buffer, (c, moves)) } + unsafe { merge.record_keep(device, command_buffer, (c, moves)) }; + return false; } // SAFETY: as above. Step::Merge(merge) => { - return unsafe { merge.record_merge(device, command_buffer, (c, moves)) } + unsafe { merge.record_merge(device, command_buffer, (c, moves)) }; + return false; } }; let (buffer, target) = match &c.source { @@ -2352,7 +2426,7 @@ impl ShadowCopy { } } } - return; + return into_shadow; } ShadowSource::YCbCrWrite { buffer, @@ -2387,7 +2461,7 @@ impl ShadowCopy { // SAFETY: the caller's contract, which the write-back's record takes. unsafe { write_back.record(device, command_buffer, buffer.raw(), self.area) }; } - return; + return true; } ShadowSource::Image { image, @@ -2423,7 +2497,7 @@ impl ShadowCopy { &through.regions, ); } - return; + return true; } // A copy in cut to a rectangle moves its texels alone; a copy back moves every // texel (`ShadowCopies::cuts_back`). @@ -2432,7 +2506,7 @@ impl ShadowCopy { (Some(area), true, Some(region)) => match image_part_of(region, area) { Some(part) => vec![part], // The command reads no texel. - None => return, + None => return false, }, _ => regions.clone(), } @@ -2460,7 +2534,7 @@ impl ShadowCopy { ®ions, ); } - return; + return true; } }; let (image, regions, staging) = match target { @@ -2477,7 +2551,7 @@ impl ShadowCopy { match part_of(region, area, texel) { Some(part) => std::borrow::Cow::Owned(vec![part]), // The commands read or wrote no texel. - None => return, + None => return false, } } _ => std::borrow::Cow::Borrowed(regions), @@ -2505,7 +2579,7 @@ impl ShadowCopy { back, ); } - return; + return true; } ShadowTarget::Planes { image, @@ -2524,7 +2598,7 @@ impl ShadowCopy { back, ); } - return; + return true; } ShadowTarget::Tiled { image, @@ -2543,7 +2617,7 @@ impl ShadowCopy { back, ); } - return; + return true; } ShadowTarget::Buffer(staging) => { // SAFETY: the caller's contract; the copies lie in both buffers (planned when @@ -2563,7 +2637,7 @@ impl ShadowCopy { record_back(device, command_buffer, (staging, buffer), back); } } - return; + return !into_shadow || staging.into.size > 0; } }; let texels = staging.map_or(buffer, ShadowStaging::raw); @@ -2589,7 +2663,7 @@ impl ShadowCopy { &chosen, ); } - return; + return !chosen.is_empty(); } device.cmd_copy_buffer_to_image( command_buffer, @@ -2616,6 +2690,7 @@ impl ShadowCopy { } } } + true } } diff --git a/crates/metal2vulkan-runtime/src/tests/shadow.rs b/crates/metal2vulkan-runtime/src/tests/shadow.rs index 059e8e279..09fd39720 100644 --- a/crates/metal2vulkan-runtime/src/tests/shadow.rs +++ b/crates/metal2vulkan-runtime/src/tests/shadow.rs @@ -97,6 +97,7 @@ fn shadow_in( tracked: true, drops_writes: false, levels: None, + decode: Default::default(), backing: Backing::MappedBuffer, merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), @@ -1471,6 +1472,7 @@ fn view_of(image: ResourceKey, levels: Range, layers: Range) -> Arc Result<(), Error> { + let Owner::HeapShadow(shadow) = &self.owner else { + return Ok(()); + }; + let Some(pass) = self.decode_pass(&whole_regions(self.plan()), PassScratch::Own)? else { + return Ok(()); + }; + let decode = ShadowDecode::new(self.device.clone(), pass); + (shadow.copies.decode.set(decode)) + .map_err(|_| internal("a heap shadow's decode into its twin set twice")) + } + /// Start the decoded twin of the image, just made and shared, where it was made moved alone /// (`Start::Moved`, [`Device::with_decoded_twin`]): the decode of a new texture's zero /// blocks, every level's, queued for the device's decode thread (`twin_decode.rs`), which diff --git a/crates/metal2vulkan-runtime/src/texture/faces.rs b/crates/metal2vulkan-runtime/src/texture/faces.rs index a8216a0c6..daf5cbaaf 100644 --- a/crates/metal2vulkan-runtime/src/texture/faces.rs +++ b/crates/metal2vulkan-runtime/src/texture/faces.rs @@ -540,6 +540,7 @@ fn face_copies(truth: &Arc, shadow: &Arc, extent: [u32; 3]) -> Sha tracked: shadow.identity.tracked, drops_writes: false, levels: None, + decode: Default::default(), backing: Backing::PrivateImage, merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), diff --git a/crates/metal2vulkan-runtime/src/texture/heap.rs b/crates/metal2vulkan-runtime/src/texture/heap.rs index abbb510c1..8d93d6ebc 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap.rs @@ -4141,13 +4141,21 @@ impl Device { } }; // An image bound in the heap's own memory, which only the runtime's writes change, takes - // a decoded twin where its format needs one (`texture/decoded_twin.rs`); one over the - // caller's host pages, laid out apart from the heap's bytes or detached does not. + // a decoded twin where its format needs one (`texture/decoded_twin.rs`), and so does an + // image in memory of its own that shadows the heap's bytes, whose copies in bring what + // the bytes hold: decoded after each copy in that moved texels (`ShadowCopies::decode`), + // but a 4:2:2 texture's, which keeps its rows for copies alone (`chroma_pairs.rs`). One + // over the caller's host pages, laid out apart from the heap's bytes or detached takes + // none. let own = matches!( route, AliasRoute::Direct | AliasRoute::HostTransfer | AliasRoute::Linear | AliasRoute::Hidden ); - let twinned = own && !host && stand_in.is_none(); + let shadowed = matches!( + route, + AliasRoute::Shadow | AliasRoute::MemoryShadow | AliasRoute::Tiled + ) && !chroma_pairs::is_four_two_two(p.layout.pixel_format); + let twinned = (own || shadowed) && !host && stand_in.is_none(); // An image in memory of its own presents the stand-in too, keeping its own (its copies // took it), before its texture is made. if let Some(stand_in) = stand_in { @@ -4172,10 +4180,14 @@ impl Device { }; let record = ViewRecord::of_descriptor(&p.layout, descriptor); let image = image.shared(); - // It holds what its bytes held: its twin decodes all of it before any command reads it. - // Before the texture takes its ID (`resource_ids.rs`): what follows fails only on the - // runtime's own fault (`internal`). - image.decode_whole()?; + // It holds what its bytes held: its twin decodes all of it before any command reads it, + // a shadow's after each copy in, its first before any command reads the texture. Before + // the texture takes its ID (`resource_ids.rs`): what follows fails only on the runtime's + // own fault (`internal`). + match twinned && shadowed { + true => image.decode_after_copies_in()?, + false => image.decode_whole()?, + } let program = matches!(id_use, IdUse::Program(_)); let texture = Texture::made(self, Storage::Image(image), record, None, id_use); // A multisample texture's moves between its image and Metal's tiles, which name its @@ -4313,6 +4325,7 @@ impl Device { tracked: identity.tracked, drops_writes: false, levels: None, + decode: Default::default(), backing: Backing::of(bytes, false), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), @@ -4415,6 +4428,7 @@ impl Device { tracked: identity.tracked, drops_writes: false, levels: None, + decode: Default::default(), backing: Backing::of(bytes, false), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), @@ -4496,6 +4510,7 @@ impl Device { tracked: identity.tracked, drops_writes: false, levels: None, + decode: Default::default(), backing: Backing::of(bytes, false), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), diff --git a/crates/metal2vulkan-runtime/src/texture/surface_depth.rs b/crates/metal2vulkan-runtime/src/texture/surface_depth.rs index 41b014d02..8d8221d6b 100644 --- a/crates/metal2vulkan-runtime/src/texture/surface_depth.rs +++ b/crates/metal2vulkan-runtime/src/texture/surface_depth.rs @@ -166,6 +166,7 @@ impl Texture { tracked: texels.tracked(), drops_writes: false, levels: None, + decode: Default::default(), backing: texels.backing(), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), diff --git a/crates/metal2vulkan-runtime/src/texture/surface_pairs.rs b/crates/metal2vulkan-runtime/src/texture/surface_pairs.rs index 26acb55f4..5c72aea2d 100644 --- a/crates/metal2vulkan-runtime/src/texture/surface_pairs.rs +++ b/crates/metal2vulkan-runtime/src/texture/surface_pairs.rs @@ -369,6 +369,7 @@ impl Device { // Metal drops a function's writes to the texture. drops_writes: true, levels: None, + decode: Default::default(), backing: texels.backing(), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), diff --git a/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs b/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs index 043811a44..3bad8e425 100644 --- a/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs +++ b/crates/metal2vulkan-runtime/src/texture/surface_two_planes.rs @@ -238,6 +238,7 @@ impl Device { tracked: texels.tracked(), drops_writes: false, levels: None, + decode: Default::default(), backing: texels.backing(), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), diff --git a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs index 1761456ec..2ddcb9d5c 100644 --- a/crates/metal2vulkan-runtime/src/texture/view_shadow.rs +++ b/crates/metal2vulkan-runtime/src/texture/view_shadow.rs @@ -534,6 +534,7 @@ impl Device { tracked: identity.tracked, drops_writes: false, levels: None, + decode: Default::default(), backing, merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), diff --git a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs index cb12ae82a..804638f02 100644 --- a/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs +++ b/crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs @@ -395,6 +395,7 @@ impl Device { // Metal drops a function's writes to the texture. drops_writes: true, levels: None, + decode: Default::default(), backing: texels.backing(), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), @@ -732,6 +733,7 @@ impl Texture { tracked: texels.tracked(), drops_writes: false, levels: None, + decode: Default::default(), backing: texels.backing(), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), @@ -910,6 +912,7 @@ impl Texture { tracked: texels.tracked(), drops_writes: false, levels: None, + decode: Default::default(), backing: texels.backing(), merge_scratch: ScratchSpares::default(), stood: AtomicU64::new(0), diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 3ea9ae566..63863af6e 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -434,6 +434,7 @@ pub(crate) struct Counters { uncached_host_images: AtomicU64, cpu_block_decodes: AtomicU64, block_decode_passes: AtomicU64, + shadow_twin_decodes: AtomicU64, chroma_device_twins: AtomicU64, chroma_device_decodes: AtomicU64, second_twins: AtomicU64, @@ -4162,6 +4163,12 @@ impl Counters { self.block_decode_passes.fetch_add(1, Ordering::Relaxed); } + /// A shadowed carrier's decode into its decoded twin was recorded after a copy in that moved + /// texels (`shadow::ShadowDecode`). + pub(crate) fn shadow_twin_decode(&self) { + self.shadow_twin_decodes.fetch_add(1, Ordering::Relaxed); + } + /// A 4:2:2 texture's decoded twin was made to hold the device's own Y′CbCr conversion of its /// pairs (`ycbcr_device::PairsSampling`). pub(crate) fn chroma_device_twin(&self) { @@ -8652,6 +8659,11 @@ pub struct WorkCounts { /// a blit's or a copy's into a carried texture, a heap texture's start, a write through /// submissions. None for a twin that takes CPU copies, whose texels only the CPU decodes. pub block_decode_passes: u64, + /// Decodes of a shadowed carrier's whole image into its decoded twin, recorded after a copy + /// in that moved texels into the shadow (a heap's PVRTC, ETC2 or EAC texture on a device + /// without the format whose image shadows the heap's bytes, `texture/heap.rs`), one a copy in; + /// none for a use that copied nothing in. + pub shadow_twin_decodes: u64, /// 4:2:2 textures' decoded twins made to hold the device's own Y′CbCr conversion of their /// pairs, where it converts their format with Metal's reconstruction (`ycbcr_device.rs`), in /// place of Metal's decode: their writes all decode through GPU passes. @@ -12105,6 +12117,7 @@ impl Device { uncached_host_images: counters.uncached_host_images.load(Ordering::Relaxed), cpu_block_decodes: counters.cpu_block_decodes.load(Ordering::Relaxed), block_decode_passes: counters.block_decode_passes.load(Ordering::Relaxed), + shadow_twin_decodes: counters.shadow_twin_decodes.load(Ordering::Relaxed), chroma_device_twins: counters.chroma_device_twins.load(Ordering::Relaxed), chroma_device_decodes: counters.chroma_device_decodes.load(Ordering::Relaxed), second_twins: counters.second_twins.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane.rs b/crates/metal2vulkan-validation/src/runtime_lane.rs index 5820cfc57..0ffb6bd62 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane.rs @@ -551,6 +551,8 @@ mod handler_waits; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod handles; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +mod heap_carried_reads; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod heap_device_samples; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] mod heap_extended_reads; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs index 06213689e..b333cfb20 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs @@ -12,9 +12,11 @@ //! a heap element holds the write shadow of as it is made, where the device holds textures in //! argument buffers and a kernel writing through one ran before; a 4:2:2 `GBGR422` texture, which //! every device holds in a carrier with a decoded twin; a `PVRTC_RGBA_4BPP` and an `ETC2_RGB8` -//! texture in the heap, each carried with a twin whose whole decode its making stages where the -//! device lacks the format (PVRTC on every device but PowerVR's; a heap's ASTC texture is -//! refused, a heap's 4:2:2 one is a shadow without a twin); and a view of an `ASTC_4x4_LDR` +//! texture in the heap, each carried with a twin where the device lacks the format (PVRTC on +//! every device but PowerVR's; a heap's ASTC texture is refused, a heap's 4:2:2 one is a shadow +//! without a twin), whose whole decode its making stages where its image lies in the heap's +//! memory, or whose decode each copy in records where its image shadows the heap's bytes (the +//! lane's exact answers on RADV: `runtime/src/texture/heap.rs`); and a view of an `ASTC_4x4_LDR` //! texture as `ASTC_4x4_sRGB`, its second decoded twin where the device lacks ASTC), a heap's //! buffer and new buffers are made (a `Private` one with bytes among them, and a `Managed` one), //! a `Managed` buffer's `did_modify_range` is called (on a device without unified memory each @@ -28,11 +30,12 @@ //! two-plane texture and a write through the YCbCr texture's handle; a decoded twin's decode //! kernels (a 4:2:2 texture's on a device that converts its pairs, the heap textures' whole //! decodes, the view's second twin's) by the next commit, before the scheduler's section -//! (`runtime/src/texture/decoded_twin.rs`). The whole decodes the heap makings staged -//! (`WorkCounts::block_decode_passes`) are printed. +//! (`runtime/src/texture/decoded_twin.rs`), a heap shadow's decode after its copies in at its +//! first use. The decode passes the heap makings made (`WorkCounts::block_decode_passes`: a +//! staged whole decode, or a shadow's decode after its copies in) are printed. //! - **A carried heap texture read with no commit.** A `PVRTC_RGBA_4BPP` texture made in a -//! `Shared` heap, its twin's whole decode staged by its making where the device lacks PVRTC, -//! then written by `replace_region` and read by `get_bytes` with no commit between: its making +//! `Shared` heap, its twin's whole decode staged by its making where the device lacks PVRTC +//! (or, where its image shadows the heap's bytes, decoded after each copy in), then written by `replace_region` and read by `get_bytes` with no commit between: its making //! builds no kernel, and `get_bytes` reads the blocks written, any internal submission among //! the calls (where the device copies the texture through submissions) making the staged //! decode's kernel before its lock. @@ -847,7 +850,8 @@ fn new_resources_wait_for_no_gpu_work() { .new_texture(&pairs(ResourceOptions::private())) .unwrap() }); - // The carried kinds a heap's texture takes a twin of: each one's whole decode staged. + // The carried kinds a heap's texture takes a twin of: each one's decode pass made, its + // whole decode staged or its shadow's decode after copies in. let passes = device.work_counts().block_decode_passes; let carried_in_heap = [PixelFormat::PVRTCRGBA4BPP, PixelFormat::ETC2RGB8].map(|format| { calls.time(format!("new_texture in a heap ({format:?})"), || { @@ -997,7 +1001,7 @@ fn new_resources_wait_for_no_gpu_work() { let counts = device.work_counts(); println!( "FIRST-USE on {name}: heap textures tiled {}; a YCbCr texture written through a heap \ - {}; 4:2:2 twins of the device's conversion {}; whole decodes staged by the heap's \ + {}; 4:2:2 twins of the device's conversion {}; decode passes made by the heap's \ PVRTC and ETC2 makings {staged}; ASTC carried {carried}, second twins made \ {second_twins}; the makings built no kernel, the uses built {}", counts.heap_textures_tiled, @@ -1046,12 +1050,13 @@ fn new_resources_wait_for_no_gpu_work() { } /// A `PVRTC_RGBA_4BPP` texture made in a `Shared` heap, where the device lacks PVRTC a carrier -/// whose decoded twin's whole decode its making stages, then written by `replace_region` and +/// whose decoded twin's whole decode its making stages (or, where its image shadows the heap's +/// bytes, each copy in decodes), then written by `replace_region` and /// read by `get_bytes`, with no commit between (the module docs): its making builds no kernel of /// the runtime's own (`WorkCounts::owned_kernels_made`), and `get_bytes` reads the blocks /// `replace_region` wrote, as Metal's does. Any internal submission the calls make (where the /// device copies such a texture through submissions) takes the staged decode with its kernel -/// made before its lock (`Device::make_pending_decodes`); the decodes the making staged +/// made before its lock (`Device::make_pending_decodes`); the decode passes the making made /// (`WorkCounts::block_decode_passes`), the kernels each call built and the internal submissions /// are printed (`CARRIED-HEAP`). #[test] @@ -1089,7 +1094,7 @@ fn a_carried_heap_texture_reads_its_bytes_with_no_commit() { texture.get_bytes(&mut read, row, 0, region, 0, 0).unwrap(); let reading = built() - kernels; println!( - "CARRIED-HEAP {name}: whole decodes staged by the making {staged}; kernels built by \ + "CARRIED-HEAP {name}: decode passes made by the making {staged}; kernels built by \ the making {making}, replace_region {replaced}, get_bytes {reading}; internal \ submissions {}", device.work_counts().internal_submissions - submissions diff --git a/crates/metal2vulkan-validation/src/runtime_lane/heap_carried_reads.rs b/crates/metal2vulkan-validation/src/runtime_lane/heap_carried_reads.rs new file mode 100644 index 000000000..c94343375 --- /dev/null +++ b/crates/metal2vulkan-validation/src/runtime_lane/heap_carried_reads.rs @@ -0,0 +1,513 @@ +//! A heap's carried textures read and sample as the same texture outside a heap, on the device +//! the cfg selects, under the validation layer. Metal's PVRTC and ETC2 textures in a heap sample +//! and read as they do outside one; on a device without the format the runtime holds their blocks +//! in a carrier whose sampled views read a decoded twin (`runtime/src/texture/decoded_twin.rs`), in +//! a heap as outside one: bound in the heap's memory, or, where the carrier asks more of the heap +//! than the answer it is held to (`HeapAnswerPolicy::Metal` on RADV, whose carrier takes 4096 +//! bytes at 4096 where Metal answers 128 at 128), a shadow of the heap's bytes whose whole twin is +//! decoded after each copy in that moved texels (`runtime/src/texture/heap.rs`, `shadow.rs`). +//! +//! Under both heap answer policies, for a `PVRTC_RGBA_4BPP` and an `ETC2_RGB8` texture, 16 and 64 +//! texels square, in a `Private` and a `Shared` automatic heap, beside a texture of the same +//! descriptor outside the heap, each step done to both: +//! +//! - **Filled** by a blit of the same seeded blocks; a kernel's reads (twice, in two encoders of +//! one command buffer) and a sampler's samples of the first 16 x 16 texels equal the other's. +//! - **Written** by a blit of other blocks; the samples equal the other's and differ from before. +//! - **Written by the CPU** (a `Shared` heap's): `replaceRegion` of a third set of blocks; the +//! samples after the next copy in equal the other's and differ from before. +//! - **Read back**: a blit of its blocks into a buffer, and a `Shared` one's `getBytes`, equal the +//! other's. +//! +//! Each case prints a `HEAPDECODE` line: the heap's answer, whether its image shadows the heap's +//! bytes (`shadowed-texture` at its making, each kind announced at each texture, +//! `DeviceOptions::announce_each`), and for each use the shadow's copies its encoders planned +//! (`WorkCounts::shadow_copies`) and the decodes recorded after copies in +//! (`WorkCounts::shadow_twin_decodes`). The two reads in one command buffer take one copy in, the +//! second encoder carrying the image the first left: a shadowed texture's read decodes once, as +//! many times as its copies in, and a texture bound in the heap's memory never. + +use super::astc_textures::{reader, texels_of}; +use super::degrade_notices::on_device_with; +use super::{at_plan, buffer_with, read_buffer, Messages, WAIT}; +use crate::air_library::AirLibrary; +use metal2vulkan::bind::SamplerDescriptor; +use metal2vulkan::device::HeapAnswerPolicy; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; +use metal2vulkan_devtools::{engine_dir, llvm_assemble}; +use metal2vulkan_runtime::{ + BlitCommandEncoder, BlitOption, Buffer, CommandBufferStatus, ComputePipelineState, Degradation, + Device, DeviceOptions, Error, HeapDescriptor, HeapType, Origin, PipelineOptions, Region, + ResourceOptions, SamplerState, Size, StorageMode, Texture, TextureDescriptor, WorkCounts, +}; + +/// The carried formats a heap's texture holds in a carrier with a decoded twin where the device +/// lacks them (every device but PowerVR's lacks PVRTC; desktop GPUs and lavapipe lack ETC2). +const FORMATS: [PixelFormat; 2] = [PixelFormat::PVRTCRGBA4BPP, PixelFormat::ETC2RGB8]; + +/// The textures' sides: the readers' own, and the side the first-use lane's heap makings take. +const SIDES: [u64; 2] = [16, 64]; + +/// The side of the region the readers read (`format_scout.ll`'s kernels, rows of 16 texels). +const READ: u64 = 16; + +/// The route kinds a heap texture's making announces, each at each texture. +const ROUTES: [Degradation; 5] = [ + Degradation::ShadowedTexture, + Degradation::HeapTextureHostTransfer, + Degradation::HeapTextureLinear, + Degradation::HeapTextureLargerThanMetal, + Degradation::HeapTextureUntiledLayout, +]; + +/// `n` bytes of a seeded xorshift: random blocks of every mode. +fn seeded(seed: u64, n: usize) -> Vec { + let mut x = seed | 1; + let mut out = Vec::with_capacity(n + 8); + while out.len() < n { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + out.extend_from_slice(&x.wrapping_mul(0x2545_f491_4f6c_dd1d).to_le_bytes()); + } + out.truncate(n); + out +} + +/// A square 2D texture of `pf`, `side` texels, read by shaders, of `options`. +fn descriptor(pf: PixelFormat, side: u64, options: ResourceOptions) -> TextureDescriptor { + let mut d = TextureDescriptor::texture_2d(pf, side, side, false); + d.usage = TextureUsage::SHADER_READ; + d.resource_options = options; + d +} + +/// The option a blit of `pf`'s blocks row by row takes: PVRTC's row-linear option. +fn rows(pf: PixelFormat) -> BlitOption { + match pf { + PixelFormat::PVRTCRGBA4BPP => BlitOption::RowLinearPVRTC, + _ => BlitOption::None, + } +} + +/// The format scout's `scout_sample_f` on `device`, which samples each texel of a 16 x 16 region +/// a quarter and three quarters of the way into it. +fn sampling(device: &Device) -> ComputePipelineState { + let bitcode = llvm_assemble(&engine_dir().join("format_scout.ll")).unwrap(); + let library = device.new_library_with_air(&bitcode).unwrap(); + let function = library.new_function_with_name("scout_sample_f").unwrap(); + device + .new_compute_pipeline_state( + &ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())), + &PipelineOptions::default(), + ) + .unwrap() +} + +/// `error` as a line. +fn said(error: Error) -> String { + format!("{error:?}") +} + +/// The device's two readers and a nearest sampler. +struct Readers { + read: ComputePipelineState, + sample: ComputePipelineState, + sampler: SamplerState, +} + +/// One use's counts: the shadow copies its encoders planned and the decodes after copies in. +#[derive(Clone, Copy, Debug)] +struct Counted { + copies: u64, + decodes: u64, +} + +impl Counted { + /// What happened between `before` and `after`. + fn between(before: &WorkCounts, after: &WorkCounts) -> Counted { + Counted { + copies: after.shadow_copies - before.shadow_copies, + decodes: after.shadow_twin_decodes - before.shadow_twin_decodes, + } + } +} + +/// One command buffer of the blit `encode` records, committed and waited for: its error, or the +/// command buffer's where it did not complete. +fn blit( + device: &Device, + encode: impl FnOnce(&mut BlitCommandEncoder) -> Result<(), Error>, +) -> Result<(), String> { + let queue = device.new_command_queue().map_err(said)?; + let command_buffer = queue.command_buffer().map_err(said)?; + let mut encoder = command_buffer.blit_command_encoder().map_err(said)?; + let recorded = encode(&mut encoder); + encoder.end_encoding().map_err(said)?; + command_buffer.commit().map_err(said)?; + command_buffer.wait_until_completed_for(WAIT).unwrap(); + recorded.map_err(said)?; + match command_buffer.status() { + CommandBufferStatus::Completed => Ok(()), + status => Err(format!("{status:?}: {:?}", command_buffer.error())), + } +} + +/// Copy `blocks` (`row` bytes a row of blocks) into the whole `side`-texel level of `texture`. +fn put( + device: &Device, + texture: &Texture, + blocks: &[u8], + side: u64, + row: u64, +) -> Result<(), String> { + let pf = texture.pixel_format(); + let source = buffer_with(device, blocks).unwrap(); + let size = Size::new(side, side, 1); + let image = blocks.len() as u64; + blit(device, |encoder| { + let at = Origin::new(0, 0, 0); + encoder.copy_from_buffer_to_texture( + &source, + 0, + row, + image, + size, + texture, + 0, + 0, + at, + rows(pf), + ) + }) +} + +/// The blocks of the whole `side`-texel level of `texture`, blitted into a buffer `row` bytes a +/// row of blocks: `length` bytes. +fn get( + device: &Device, + texture: &Texture, + side: u64, + row: u64, + length: u64, +) -> Result, String> { + let pf = texture.pixel_format(); + let out: Buffer = buffer_with(device, &vec![0; length as usize]).unwrap(); + let size = Size::new(side, side, 1); + blit(device, |encoder| { + let at = Origin::new(0, 0, 0); + encoder.copy_from_texture_to_buffer(texture, 0, 0, at, size, &out, 0, row, length, rows(pf)) + })?; + Ok(read_buffer(&out, 0, length).unwrap()) +} + +/// The `float4` texels of the first [`READ`] x [`READ`] texels of `texture` as `state` reads them +/// (through `sampler` where given), each of `encoders` encoders of one command buffer reading +/// them once into its own buffer: its error where a call refused the read. +fn texels( + device: &Device, + state: &ComputePipelineState, + sampler: Option<&SamplerState>, + texture: &Texture, + encoders: usize, +) -> Result>, String> { + let length = 16 * READ * READ; + let outs: Vec = (0..encoders) + .map(|_| buffer_with(device, &vec![0; length as usize]).unwrap()) + .collect(); + let queue = device.new_command_queue().map_err(said)?; + let command_buffer = queue.command_buffer().map_err(said)?; + let mut recorded = Ok(()); + for out in &outs { + let mut encoder = command_buffer.compute_command_encoder().map_err(said)?; + let read = (|| { + encoder.set_compute_pipeline_state(state)?; + encoder.set_texture(Some(texture), 0)?; + if let Some(sampler) = sampler { + encoder.set_sampler_state(Some(sampler), 0)?; + } + encoder.set_buffer(Some(out), 0, 0)?; + encoder.dispatch_threads(Size::new(READ, READ, 1), Size::new(READ, READ, 1)) + })(); + encoder.end_encoding().map_err(said)?; + if recorded.is_ok() { + recorded = read; + } + } + command_buffer.commit().map_err(said)?; + command_buffer.wait_until_completed_for(WAIT).unwrap(); + recorded.map_err(|error| format!("refused: {error:?}"))?; + match command_buffer.status() { + CommandBufferStatus::Completed => {} + status => return Err(format!("{status:?}: {:?}", command_buffer.error())), + } + Ok((outs.iter()) + .map(|out| texels_of(&read_buffer(out, 0, length).unwrap())) + .collect()) +} + +/// What a case found: a line of evidence, and its failures. +struct Case { + line: String, + wrong: Vec, +} + +/// A case's failures so far, and the per-use counts for its line. +struct Checks<'a> { + what: &'a str, + device: &'a Device, + wrong: Vec, + uses: Vec, +} + +impl Checks<'_> { + /// Run `step` (a use of the heap's texture), counting what its shadow did, and answer what it + /// answered with the counts; `name` labels them on the line. + fn counted(&mut self, name: &str, step: impl FnOnce() -> T) -> (T, Counted) { + let before = self.device.work_counts(); + let answer = step(); + let counted = Counted::between(&before, &self.device.work_counts()); + self.uses.push(format!( + "{name} copies {} decodes {}", + counted.copies, counted.decodes + )); + (answer, counted) + } + + /// The heap texture's texels `got` (each encoder's) against the other texture's `want`, both + /// read as `how` says: the other's texels, where both reads ran. + fn alike( + &mut self, + how: &str, + got: Result>, String>, + want: Result>, String>, + ) -> Option> { + let what = self.what; + let (got, want) = match (got, want) { + (Ok(got), Ok(want)) => (got, want), + (got, want) => { + if let Err(error) = got { + self.wrong.push(format!("{what}: {how}: {error}")); + } + if let Err(error) = want { + self.wrong + .push(format!("{what}: {how} outside a heap: {error}")); + } + return None; + } + }; + let want = want.into_iter().next()?; + for (encoder, got) in got.iter().enumerate() { + let differ = (got.iter().zip(&want)).filter(|(a, b)| a != b).count(); + if differ > 0 { + self.wrong.push(format!( + "{what}: {how} (encoder {encoder}): {differ} of {} texels otherwise than \ + outside a heap", + READ * READ + )); + } + } + Some(want) + } + + /// Texels `now` differ from `before` somewhere: a write's new texels show. + fn changed(&mut self, how: &str, before: Option<&[[f32; 4]]>, now: Option<&[[f32; 4]]>) { + if let (Some(before), Some(now)) = (before, now) { + if before == now { + let what = self.what; + self.wrong + .push(format!("{what}: {how}: the samples did not change")); + } + } + } +} + +/// One case on `device`: a texture of `pf`, `side` texels, in an automatic heap of `options`, +/// against the same texture outside a heap (the module docs), its blocks seeded by `seed`. +fn case( + device: &Device, + messages: &Messages, + readers: &Readers, + (pf, side, options): (PixelFormat, u64, ResourceOptions), + seed: u64, +) -> Case { + let name = device.name(); + let storage = options.storage_mode().unwrap(); + let what = format!("{pf:?} {side}x{side} {storage:?}"); + let d = descriptor(pf, side, options); + let answer = device.heap_texture_size_and_align(&d); + let heap = device + .new_heap(&HeapDescriptor::new(HeapType::Automatic, 1 << 20, options)) + .unwrap(); + messages.take_notices(); + let made = heap.new_texture(&d); + let routes: Vec = (messages.take_notices().iter()) + .filter_map(|m| m.degradation.as_ref().map(|n| n.degradation)) + .filter(|kind| ROUTES.contains(kind)) + .collect(); + let shadowed = routes.contains(&Degradation::ShadowedTexture); + let in_heap = match made { + Ok(texture) => texture, + Err(error) => { + let line = format!("HEAPDECODE {name} {what}: answer {answer:?}; making refused"); + let wrong = vec![format!("{what}: refused its making in the heap: {error:?}")]; + return Case { line, wrong }; + } + }; + let own = device.new_texture(&d).unwrap(); + let mut checks = Checks { + what: &what, + device, + wrong: Vec::new(), + uses: Vec::new(), + }; + let across = side / 4; + let row = across * 8; + let image = row * across; + let both = [&in_heap, &own]; + let (read, sample, sampler) = (&readers.read, &readers.sample, Some(&readers.sampler)); + + // Filled by a blit; read twice in one command buffer, then sampled. + let filled = seeded(seed, image as usize); + for texture in both { + if let Err(error) = put(device, texture, &filled, side, row) { + checks + .wrong + .push(format!("{what}: a blit into it: {error}")); + } + } + let (got, reads) = checks.counted("read x2", || texels(device, read, None, &in_heap, 2)); + let want = texels(device, read, None, &own, 1); + checks.alike("its kernel's reads", got, want); + // A shadow's copies in (the reads write nothing, so no copy back), each decoded once; no + // decode for an image in the heap's memory. + let decoded = match shadowed { + true => reads.copies >= 1 && reads.decodes == reads.copies, + false => reads.decodes == 0, + }; + if !decoded { + checks.wrong.push(format!( + "{what}: two reads in one command buffer, shadowed {shadowed}: {reads:?}" + )); + } + let (got, _) = checks.counted("sample", || texels(device, sample, sampler, &in_heap, 1)); + let want = texels(device, sample, sampler, &own, 1); + let first = checks.alike("its samples", got, want); + + // Written by a blit of other blocks: the samples show them. + let blitted = seeded(seed ^ 0xb11e, image as usize); + for texture in both { + if let Err(error) = put(device, texture, &blitted, side, row) { + checks + .wrong + .push(format!("{what}: a second blit into it: {error}")); + } + } + let (got, _) = checks.counted("blit+sample", || { + texels(device, sample, sampler, &in_heap, 1) + }); + let want = texels(device, sample, sampler, &own, 1); + let second = checks.alike("its samples after a blit", got, want); + checks.changed("after a blit", first.as_deref(), second.as_deref()); + + // A `Shared` one written by the CPU (PVRTC's whole level in Metal's CPU order, at a pitch of + // 0): the samples after the next copy in show it. + let pitch = match pf { + PixelFormat::PVRTCRGBA4BPP => 0, + _ => row, + }; + let region = Region::new_2d(0, 0, side, side); + if storage == StorageMode::Shared { + let written = seeded(seed ^ 0xc0de, image as usize); + for texture in both { + if let Err(error) = texture.replace_region(region, 0, 0, &written, pitch, 0) { + checks + .wrong + .push(format!("{what}: replaceRegion: {error:?}")); + } + } + let (got, cpu) = checks.counted("replace+sample", || { + texels(device, sample, sampler, &in_heap, 1) + }); + let want = texels(device, sample, sampler, &own, 1); + let third = checks.alike("its samples after replaceRegion", got, want); + checks.changed("after replaceRegion", second.as_deref(), third.as_deref()); + if shadowed && cpu.decodes == 0 { + checks.wrong.push(format!( + "{what}: a sample after replaceRegion decoded nothing: {cpu:?}" + )); + } + } + + // Read back: a blit of its blocks, and a `Shared` one's CPU copy. + let blocks = both.map(|texture| get(device, texture, side, row, image)); + match &blocks { + [Ok(a), Ok(b)] if a == b => {} + [Ok(_), Ok(_)] => (checks.wrong).push(format!( + "{what}: a blit out reads other blocks than outside a heap" + )), + [a, b] => (checks.wrong).push(format!( + "{what}: a blit out: {:?} / {:?}", + a.as_ref().err(), + b.as_ref().err() + )), + } + if storage == StorageMode::Shared { + let mut got = [vec![0xee; image as usize], vec![0xdd; image as usize]]; + let results: Vec> = (both.iter().zip(got.iter_mut())) + .map(|(texture, bytes)| texture.get_bytes(bytes, pitch, 0, region, 0, 0)) + .collect(); + let alike = got[0] == got[1]; + if !(alike && results.iter().all(Result::is_ok)) { + (checks.wrong).push(format!("{what}: getBytes {results:?}, alike {alike}")); + } + } + let line = format!( + "HEAPDECODE {name} {what}: answer {answer:?}; shadowed {shadowed}; route notices \ + {routes:?}; per use {}", + checks.uses.join(", ") + ); + let wrong = checks.wrong; + drop((in_heap, own, heap)); + Case { line, wrong } +} + +/// A heap's carried textures read and sample as the same texture outside a heap, under both heap +/// answer policies (the module docs). +#[test] +fn a_heap_s_carried_textures_read_as_outside_a_heap() { + let mut wrong = Vec::new(); + for answers in [HeapAnswerPolicy::Metal, HeapAnswerPolicy::Device] { + let each = |options: &mut DeviceOptions| { + at_plan(options); + options.policy.heap_answers = answers; + options.announce_each = ROUTES.into(); + }; + on_device_with(each, |device, messages| { + let readers = Readers { + read: reader(device), + sample: sampling(device), + sampler: device.new_sampler_state(&SamplerDescriptor::new()).unwrap(), + }; + let mut seed = 0x5eed_0000; + for pf in FORMATS { + for side in SIDES { + for options in [ResourceOptions::private(), ResourceOptions::shared()] { + seed += 1; + let found = case(device, messages, &readers, (pf, side, options), seed); + println!("{answers:?} {}", found.line); + let name = device.name(); + (wrong).extend( + found + .wrong + .into_iter() + .map(|w| format!("{answers:?} {name}: {w}")), + ); + } + } + } + }); + } + assert!(wrong.is_empty(), "\n{}", wrong.join("\n")); +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index c5af00f3f..504368e40 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2381; +pub const RUNTIME_VERSION: u32 = 2382; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 6997b87d7..461df9676 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3645,6 +3645,7 @@ field metal2vulkan-runtime::WorkCounts.shadow_texels_unskipped_stood pub shadow_ field metal2vulkan-runtime::WorkCounts.shadow_texels_unskipped_truth_written pub shadow_texels_unskipped_truth_written: u64 field metal2vulkan-runtime::WorkCounts.shadow_texels_unskipped_unnamed_since pub shadow_texels_unskipped_unnamed_since: u64 field metal2vulkan-runtime::WorkCounts.shadow_texels_unskipped_unstanding pub shadow_texels_unskipped_unstanding: u64 +field metal2vulkan-runtime::WorkCounts.shadow_twin_decodes pub shadow_twin_decodes: u64 field metal2vulkan-runtime::WorkCounts.shadowed_textures pub shadowed_textures: u64 field metal2vulkan-runtime::WorkCounts.shadows_left_unmade pub shadows_left_unmade: u64 field metal2vulkan-runtime::WorkCounts.shadows_made_at_use pub shadows_made_at_use: u64 diff --git a/docs/API.md b/docs/API.md index 4330b4912..64da7c0a9 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3793,7 +3793,10 @@ bound. the linear and sRGB forms); an ASTC sRGB texture's, its own 8-bit codes, read the same way; an ASTC HDR texture's, Metal's halves, exact (its error blocks' NaN included). It is decoded after each write into it (a PVRTC texture's whole levels, since each texel's - colors come from the blocks around it). An ASTC texture's first view in its other colour + colors come from the blocks around it); a heap's such texture whose image is a shadow of the + heap's bytes (where its carrier asks more of the heap than Metal's answer it is held to, as + under `HeapAnswerPolicy::Metal`), its whole twin after each copy in that moves its blocks + (`WorkCounts::shadow_twin_decodes`), and not after a use that copies nothing in. An ASTC texture's first view in its other colour space (its sRGB form as LDR, or the other way) gives it a second twin of that form's decode, kept in step by GPU passes its command buffers' submissions record. Also a texture of a 4:2:2 format (`GBGR422`, `BGRG422`) on every device, whose Vulkan formats are viewed only through a sampler @@ -3813,7 +3816,9 @@ bound. two for an ASTC texture viewed in both colour spaces, and a decode after each write into it: a pass on the GPU for a blit, a copy from a texture or a CPU copy through a submission; on the CPU, on the - device's decode thread, where its CPU copies go on the host or the staging queue. + device's decode thread, where its CPU copies go on the host or the staging queue; and a pass on + the GPU after each copy in that moves the blocks of a heap's texture whose image shadows the + heap's bytes. - `metal2vulkan-degrade-decoded-texel-precision` (precision). `DecodedTexelPrecision`: A texture with an ASTC LDR decoded twin of 8-bit codes, or an EAC 11-bit one (`R11`, `RG11`) of 16-bit normalized codes; or a 4:2:2 texture (`GBGR422`, `BGRG422`) whose twin holds the device's own diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 9f493dddf..07e435fcb 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -1433,13 +1433,14 @@ driver's. Each is open work. (`metal::format::word` has no entry for the format meanwhile). Six committed profiles render it directly (RADV, lavapipe and ANV), where the measured write conversion applies. - **PVRTC textures on a device without PVRTC.** One without a decoded twin (a sparse heap's, or a - heap's over the caller's host pages or laid out apart from its bytes) holds its blocks for copies - alone: a command that reads it is refused. + heap's over the caller's host pages) holds its blocks for copies alone: a command that reads it + is refused. A heap's texture whose image shadows the heap's bytes keeps a twin, decoded after + each copy in. - **ETC2 and EAC textures on a device without them.** A sparse heap's such texture (`RuntimeGap::DecodedHeapTexture`) and a view of another decode (an EAC 11-bit format's other - signedness) are refused; one without a decoded twin (a heap's over the caller's host pages or - laid out apart from its bytes) holds its blocks for copies alone, and a command that reads it is - refused. + signedness) are refused; one without a decoded twin (a heap's over the caller's host pages) + holds its blocks for copies alone, and a command that reads it is refused. A heap's texture + whose image shadows the heap's bytes keeps a twin, decoded after each copy in. - **A level the shader computes from derivatives.** An extended-range texture's fragment sample at an implicit level or with explicit gradients takes Vulkan's level of detail computed in the shader on every device, where Metal's is not measured, announced as `DeviceSampleLevel`.