Runtime: a copy from a buffer that writes a whole subresource moves it from undefined

A copy from a buffer into a texture whose region starts at the level's first texel and reaches
its edge on every axis (a 3D level's depth included; a compressed level's edge as place clamps
the region), of every aspect of the image, moves that level and layer to TRANSFER_DST_OPTIMAL
from VK_IMAGE_LAYOUT_UNDEFINED in place of its home layout. Only the old layout changes: the
barrier's range is the one level and layer the copy writes (all slices of a 3D level, which the
copy then writes whole), and its source scope stays ALL_COMMANDS, MEMORY_WRITE over every earlier
access of the image, so the copy is still ordered after every earlier read and write. A copy of
one aspect of a depth-stencil image, a region short of the level on any axis, and an image whose
bytes another reaches (in place over a buffer, a surface plane's, an import's) keep the old form.
A heap-placed texture takes the form as a texture of its own memory does. Copies between
textures are not touched.

Both upload entries share it: the blit encoder's copy from a buffer into a texture
(copyFromBuffer:...toTexture:, record_buffer_copies) and the staged upload of replaceRegion and
a Managed texture's writes (TextureInner::record), each through TextureInner::away_into.

Why it is right for Metal: a copy that writes the whole level and slice leaves none of the
earlier contents for a program to see, so discarding them first is unobservable. Why Vulkan
allows it, vkspec 1.4.366 line 9241: "The old layout must either be VK_IMAGE_LAYOUT_UNDEFINED,
or match the current layout of the image subresource range. If the old layout matches the
current layout of the image subresource range, the transition preserves the contents of that
range. If the old layout is VK_IMAGE_LAYOUT_UNDEFINED, the contents of that range may be
discarded." The range is the subresource the copy then writes whole. For a heap-placed texture,
line 32552: "If the first alias is not host-accessible, then the bytes affected are those
overlapped by the image subresources that were written": the copy writes those bytes in any
form, so the discard leaves nothing undefined that the copy's write would not.

Why: on the Radeon 780M (RADV PHOENIX, Mesa 26.2.6, kernel 7.3.3), a buffer-to-image copy that
refilled an R8 1920 x 1080 DCC-compressed image in place left one whole aligned 4x2 cell of the
previous contents in about 2 to 4 of 1000 refills, measured on R8 at 1920 x 1080; no layout of
the copy and no barrier stopped it (GENERAL 6 of 3000, no move between refills 11 of 3000, job
m3-max-76144), and the validation layer 1.4.363.0 with synchronization validation reported
nothing while it reported a hazard planted for it. A pure C repro of the calls (job
m3-max-76150, 4000 repeats an arm): the move from home 7 stale, from undefined 0,
RADV_DEBUG=nodcc 0, without COLOR_ATTACHMENT 0. Through ash in job m3-max-76165 (archives of
build m3-max-76163): the same image refilled with the move from undefined 0 of 4000, beside the
move from home 14 of 4000; through rt with this form, CONTROL, W2048 and H (the consumer's
shapes) 0 of 4000 each. Mesa's source was not read for this change.

whole_copy_in.rs holds the move's old layout for whole and short regions, levels past the
first, a 3D level's depth, one aspect of depth and stencil, and a texture over a buffer; and
1000 whole refills of an R8 1920 x 1080 render target through rt, each read back whole and
compared byte for byte.
This commit is contained in:
Anees Iqbal committed 2026-11-26 23:59:13 -08:00
1 parent 56a94f060d
commit 7d86d8f128
4 files changed
+310 -5

No files matched your search

+8 -4
View File
@@ -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(&copy.placed, copy.unit.aspect),
false => texture.away(&copy.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(&copy.placed, layout, access)];
away_one = [away_of(copy)];
back_one = [texture.back(&copy.placed, layout)];
(&away_one, &back_one)
}
_ => {
away_each = (copies.iter())
.map(|copy| texture.away(&copy.placed, layout, access))
.collect::<Vec<_>>();
away_each = copies.iter().map(away_of).collect::<Vec<_>>();
back_each = (copies.iter())
.map(|copy| texture.back(&copy.placed, layout))
.collect::<Vec<_>>();
@@ -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
@@ -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:?}"
);
}
+59 -1
View File
@@ -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(&copy.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(&copy.placed, copy.unit.aspect)],
false => [self.away(&copy.placed, layout, access)],
};
let home = [self.back(&copy.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> {