diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 3891aeacf..efa344c8b 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -637,19 +637,23 @@ impl BlitCommandEncoder { ), }; let earlier = [memory_barrier(Reach::Commands)]; + // A copy into the image that writes its whole subresource moves it from undefined + // (`TextureObject::away_into`). + let away_of = |copy: &BufferCopy| match into_image { + true => texture.away_into(©.placed, copy.unit.aspect), + false => texture.away(©.placed, layout, access), + }; // One copy, a copy call's, takes its barriers on the stack; a synchronize's of each level // and slice, in lists. let (away_one, back_one, away_each, back_each); let (away, back): (&[_], &[_]) = match copies { [copy] => { - away_one = [texture.away(©.placed, layout, access)]; + away_one = [away_of(copy)]; back_one = [texture.back(©.placed, layout)]; (&away_one, &back_one) } _ => { - away_each = (copies.iter()) - .map(|copy| texture.away(©.placed, layout, access)) - .collect::>(); + away_each = copies.iter().map(away_of).collect::>(); back_each = (copies.iter()) .map(|copy| texture.back(©.placed, layout)) .collect::>(); diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index fad06b2b3..c0acbf47f 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -143,6 +143,8 @@ mod view; mod viewports; mod visibility; mod wg_lattice; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod whole_copy_in; /// This crate's directory: the test process's `CARGO_MANIFEST_DIR` where it holds the crate's /// sources (cargo and nextest set it for each test, and an archive run elsewhere remaps it to the diff --git a/crates/metal2vulkan-runtime/src/tests/whole_copy_in.rs b/crates/metal2vulkan-runtime/src/tests/whole_copy_in.rs new file mode 100644 index 000000000..34bff94ac --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/whole_copy_in.rs @@ -0,0 +1,241 @@ +//! A copy from a buffer that writes a whole subresource moves that level and layer from undefined +//! (`TextureObject::away_into`), and every other copy into a texture moves it from home. +//! +//! - The move's old layout: undefined for a region from the level's first texel to its edge on +//! every axis of every aspect, at the first level and past it, a 3D level's depth whole; home +//! for a region short of the level on any axis (a 3D level's depth among them), one aspect of a +//! depth and stencil format, and a texture in place over a buffer, whose bytes the buffer keeps. +//! The move's range and its source scope are the old form's either way. +//! - Whole refills through rt: an R8Unorm 1920 x 1080 texture of ShaderRead and RenderTarget, +//! refilled [`REFILLS`] times on one queue by a copy from a Shared staging buffer into a Private +//! one and from that into the texture, then read back whole to Shared memory, each read +//! compared byte for byte with what the host wrote; every byte of a refill differs from the one +//! before it. With the move from home, a Radeon 780M under RADV (Mesa 26.2.6) left one aligned +//! 4 x 2 cell of the previous refill in about 2 of 1000 such refills (7 of 4000 in a pure Vulkan +//! repro of the same calls), and none with the move from undefined. + +use crate::tests::command::on_device::{each_device, finished}; +use crate::texture::{Placed, TextureObject}; +use crate::{ + BufferLayout, CommandBufferStatus, Device, IndexClass, MemoryClass, PixelFormat, StorageMode, + Texture, TextureDescriptor, TexturePlace, TextureType, TextureUsage, +}; +use ash::vk; + +/// The refills of the repeat test. +const REFILLS: u64 = 1000; + +const WIDTH: u32 = 1920; +const HEIGHT: u32 = 1080; + +fn private(pf: PixelFormat, [w, h, d]: [u32; 3], usage: TextureUsage) -> TextureDescriptor { + let kind = match d { + 1 => TextureType::Type2D, + _ => TextureType::Type3D, + }; + let mut descriptor = TextureDescriptor::new(kind, pf, w, h); + descriptor.depth = d; + descriptor.usage = usage; + descriptor.storage_mode = StorageMode::Private; + descriptor +} + +/// The old layout of the move before a copy of `aspect` into `origin` and `size` of `level` of +/// `texture`'s first layer. +fn from( + texture: &Texture, + aspect: vk::ImageAspectFlags, + level: u32, + (origin, size): ([u32; 3], [u32; 3]), +) -> vk::ImageLayout { + let placed = Placed { + level, + layer: 0, + origin, + size, + }; + texture.away_into(&placed, aspect).old_layout +} + +#[test] +fn the_move_before_a_copy_in_starts_from_undefined_for_a_whole_subresource() { + each_device("whole_copy_in_moves", |name, _, device| { + let _grant = (device.grant_indices(IndexClass::Texture, 1, 8)).expect("indices"); + let read = TextureUsage::SHADER_READ; + let make = |d: &TextureDescriptor, index: u32| { + (device.new_texture(d, Some(index))) + .unwrap_or_else(|error| panic!("{name}: a texture: {error}")) + }; + let colour = vk::ImageAspectFlags::COLOR; + let undefined = vk::ImageLayout::UNDEFINED; + // R8, 64 x 32, three levels: level 1 is 32 x 16. + let mut d = private(PixelFormat::R8Unorm, [64, 32, 1], read); + d.mipmap_level_count = 3; + let flat = make(&d, 1); + assert_eq!( + from(&flat, colour, 0, ([0; 3], [64, 32, 1])), + undefined, + "{name}" + ); + assert_eq!( + from(&flat, colour, 1, ([0; 3], [32, 16, 1])), + undefined, + "{name}" + ); + for short in [ + ([0, 0, 0], [63, 32, 1]), + ([0, 0, 0], [64, 31, 1]), + ([1, 0, 0], [63, 32, 1]), + ([0, 1, 0], [64, 31, 1]), + ([0, 0, 0], [64, 16, 1]), + ] { + assert_ne!( + from(&flat, colour, 0, short), + undefined, + "{name}: {short:?}" + ); + } + assert_ne!( + from(&flat, colour, 1, ([0; 3], [64, 32, 1])), + undefined, + "{name}" + ); + // A 3D level: its depth whole, and short. + let volume = make(&private(PixelFormat::R8Unorm, [16, 16, 8], read), 2); + assert_eq!( + from(&volume, colour, 0, ([0; 3], [16, 16, 8])), + undefined, + "{name}" + ); + assert_ne!( + from(&volume, colour, 0, ([0; 3], [16, 16, 7])), + undefined, + "{name}" + ); + assert_ne!( + from(&volume, colour, 0, ([0, 0, 1], [16, 16, 7])), + undefined, + "{name}" + ); + // One aspect of depth and stencil, and both. + let both = private( + PixelFormat::Depth32FloatStencil8, + [64, 32, 1], + TextureUsage::RENDER_TARGET, + ); + if let Ok(both) = device.new_texture(&both, Some(3)) { + let whole = ([0; 3], [64, 32, 1]); + let all = vk::ImageAspectFlags::DEPTH | vk::ImageAspectFlags::STENCIL; + assert_eq!(from(&both, all, 0, whole), undefined, "{name}"); + for one in [vk::ImageAspectFlags::DEPTH, vk::ImageAspectFlags::STENCIL] { + assert_ne!(from(&both, one, 0, whole), undefined, "{name}: {one:?}"); + } + } + // A texture in place over a buffer keeps the buffer's bytes. + let align = (device.minimum_linear_texture_alignment(PixelFormat::R8Unorm)) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let pitch = align.max(256); + let block = (device.take_block(MemoryClass::Shared, 64 * pitch)).expect("a block"); + let buffer = (device.new_buffer(block.id, 0, 64 * pitch, None)).expect("a buffer"); + let mut d = TextureDescriptor::new(TextureType::Type2D, PixelFormat::R8Unorm, 256, 64); + d.usage = read; + let over = (buffer.new_texture(&d, Some(4), 0, pitch)).expect("a texture over the buffer"); + if over.copied_over().is_none() { + assert_ne!( + from(&over, colour, 0, ([0; 3], [256, 64, 1])), + undefined, + "{name}" + ); + } + }); +} + +/// The byte at column `x` of row `y` in refill `r`: 37 more each refill. +fn pattern(r: u64, x: u32, y: u32) -> u8 { + (u64::from((x * 3) ^ (y * 5)) + r * 37) as u8 +} + +#[test] +fn whole_refills_of_a_render_target_each_read_back_whole() { + each_device("whole_copy_in_refills", |name, _, device| { + let _grant = (device.grant_indices(IndexClass::Texture, 1, 1)).expect("indices"); + let usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + let d = private(PixelFormat::R8Unorm, [WIDTH, HEIGHT, 1], usage); + let texture = (device.new_texture(&d, Some(1))).expect("the texture"); + refill(name, &device, &texture); + }); +} + +fn refill(name: &str, device: &Device, texture: &Texture) { + let bytes = u64::from(WIDTH * HEIGHT); + let room = bytes.next_multiple_of(1 << 20); + let shared = (device.take_block(MemoryClass::Shared, 2 * room)).expect("a Shared block"); + let private = (device.take_block(MemoryClass::Private, room)).expect("a Private block"); + let buffer = |block: &crate::Block, offset: u64| { + (device.new_buffer(block.id, offset, bytes, None)).expect("a buffer") + }; + let (staging, back, local) = ( + buffer(&shared, 0), + buffer(&shared, room), + buffer(&private, 0), + ); + let host = |buffer: &crate::Buffer| buffer.contents().expect("a Shared buffer's contents"); + let queue = device.new_command_queue(4).expect("a queue"); + let layout = BufferLayout { + offset: 0, + bytes_per_row: u64::from(WIDTH), + bytes_per_image: bytes, + }; + let place = TexturePlace { + slice: 0, + level: 0, + origin: [0; 3], + }; + let mut want = vec![0u8; bytes as usize]; + let mut stale = Vec::new(); + for r in 1..=REFILLS { + for (at, byte) in want.iter_mut().enumerate() { + let (x, y) = (at as u32 % WIDTH, at as u32 / WIDTH); + *byte = pattern(r, x, y); + } + // SAFETY: the staging buffer is mapped for `bytes`, and no work uses it now. + unsafe { + std::ptr::copy_nonoverlapping(want.as_ptr(), host(&staging).as_ptr(), want.len()) + }; + let fill = queue.command_buffer().expect("a command buffer"); + let mut e = fill.blit_command_encoder().expect("an encoder"); + (e.copy_from_buffer_to_buffer(&staging, 0, &local, 0, bytes)).expect("the staging copy"); + (e.copy_from_buffer(&local, layout, [WIDTH, HEIGHT, 1], texture, place)) + .expect("the copy in"); + e.end_encoding(); + fill.commit().expect("a commit"); + let read = queue.command_buffer().expect("a command buffer"); + let mut e = read.blit_command_encoder().expect("an encoder"); + (e.copy_from_texture_to_buffer(texture, place, [WIDTH, HEIGHT, 1], &back, layout)) + .expect("the read"); + e.end_encoding(); + read.commit().expect("a commit"); + for (what, cb) in [("read", &read), ("fill", &fill)] { + finished(name, cb); + assert_eq!( + cb.status(), + CommandBufferStatus::Completed, + "{name}: the {what}" + ); + } + // SAFETY: the read-back is mapped for `bytes`, and its work has completed. + let got = unsafe { std::slice::from_raw_parts(host(&back).as_ptr(), bytes as usize) }; + if got != want.as_slice() { + let wrong = got.iter().zip(&want).filter(|(g, w)| g != w).count(); + let first = got.iter().zip(&want).position(|(g, w)| g != w).unwrap_or(0); + let (x, y) = (first as u32 % WIDTH, first as u32 / WIDTH); + stale.push(format!( + "refill {r}: {wrong} bytes, the first at ({x}, {y})" + )); + } + } + assert!( + stale.is_empty(), + "{name}: refills whose read-back differs from what the host wrote, of {REFILLS}: {stale:?}" + ); +} diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index f2f909ee3..1788a7cb6 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -3912,6 +3912,48 @@ impl TextureInner { .dst_access_mask(access) } + /// The barrier that moves `placed`'s level and layer, every aspect, from home to the copy + /// layout of `TRANSFER_DST_OPTIMAL` for a copy of `aspect` from a buffer into it: `away`'s, + /// its scopes over every earlier access of the image, from undefined where the copy writes + /// every texel the barrier names ([`writes_whole`](Self::writes_whole)). Vulkan discards the + /// contents of that range alone, which the copy then writes whole, so no earlier texel is + /// left for a program to see. + fn away_into( + &self, + placed: &Placed, + aspect: vk::ImageAspectFlags, + ) -> vk::ImageMemoryBarrier2<'static> { + let away = self.away( + placed, + vk::ImageLayout::TRANSFER_DST_OPTIMAL, + vk::AccessFlags2::TRANSFER_WRITE, + ); + match self.writes_whole(placed, aspect) { + true => away.old_layout(vk::ImageLayout::UNDEFINED), + false => away, + } + } + + /// Whether a copy of `aspect` into `placed` writes every texel of the range its barrier names + /// (one level, its one layer, every aspect): `aspect` is every aspect of the image, and the + /// region starts at the level's first texel and reaches its edge on every axis, a 3D level's + /// depth included (its barrier names every slice), a compressed level's edge as + /// [`place`] clamps the region to it. Only an image whose contents are its own, in memory of + /// its own or placed in a heap: one in place over a buffer, a surface plane's and an + /// import's keep the bytes another reaches, and a copy into them never discards. + fn writes_whole(&self, placed: &Placed, aspect: vk::ImageAspectFlags) -> bool { + let image = self.imaged(); + let own = image.first == vk::ImageLayout::UNDEFINED + && !image.surface() + && image.foreign.is_none(); + let Some(level) = placed.level.checked_sub(self.base()[0]) else { + return false; + }; + let d = &self.descriptor; + let extent = [d.width, d.height, d.depth].map(|e| (e >> level).max(1)); + own && aspect == image.aspects && placed.origin == [0; 3] && placed.size == extent + } + /// The barrier that moves `placed`'s level and layer back home from the copy layout of /// `layout` once a copy has run, its writes (a copy into the image, whose transfer layout is /// `TRANSFER_DST_OPTIMAL`, or within one subresource, in `GENERAL`) visible to every later @@ -4045,7 +4087,12 @@ impl TextureInner { ), false => (vk::ImageLayout::TRANSFER_SRC_OPTIMAL, Access::TRANSFER_READ), }; - let away = [self.away(©.placed, layout, access)]; + // A copy into the image that writes its whole subresource moves it from undefined + // (`away_into`). + let away = match to_image { + true => [self.away_into(©.placed, copy.unit.aspect)], + false => [self.away(©.placed, layout, access)], + }; let home = [self.back(©.placed, layout)]; let image = self.imaged(); let named = image.copy_layout(layout); @@ -5523,6 +5570,17 @@ pub(crate) trait TextureObject { TextureInner::away(self.object(), placed, layout, access) } + /// The barrier that moves `placed` from home to `TRANSFER_DST_OPTIMAL` for a copy of `aspect` + /// from a buffer into it, after every earlier command's writes: from undefined where the copy + /// writes the whole subresource (`TextureInner::away_into`). + fn away_into( + &self, + placed: &Placed, + aspect: vk::ImageAspectFlags, + ) -> vk::ImageMemoryBarrier2<'static> { + TextureInner::away_into(self.object(), placed, aspect) + } + /// The barrier that moves `placed` back home from the copy layout of the transfer `layout` /// once a copy has run, its writes visible to every later command. fn back(&self, placed: &Placed, layout: vk::ImageLayout) -> vk::ImageMemoryBarrier2<'static> {