Runtime: a host write into a stale heap texture moves it in its upload, so its next GPU write keeps the texels

What: Texture::replace_region into a heap texture that takes part in
crate::alias settles the alias state in the upload's own command buffer,
under the work lock, ahead of its copy (alias::host_write). A stale
texture moves from undefined in alias::record's barrier, after every
earlier command's writes, counted in heap_moves and barriers. Its
staleness clears and its texture links turn stale. That state change is
Placement::written, which alias::stage now shares: one write path. A
texture in no heap, or one that takes no part, pays one test and records
nothing. A linked texture that is not stale records no command. No state
is added beyond what the alias module holds.

Why: a host write marked nothing, so a texture that a write over its bytes
had left stale stayed stale through it. Its next GPU write (its mipmaps, a
blit into another region, a pass that loads it, a draw's or a dispatch's
write) then moved its whole image from undefined, and the texels the host
wrote were lost, where Metal keeps them. upload_region reaches no heap
texture (it has no named bytes; the test asserts the refusal), and no
other work.upload caller writes one.

Ordering, by reading submit.rs: three things hold the work lock: the
call's settle, a segment's staging (alias::stage in WorkState::step,
where its checks read the staleness and its writes store it), and the
close of the submission that takes the upload (take_uploads). The upload
is numbered N, the next commit. It runs ahead of every segment of the
first submission whose last leading command buffer has seq >= N, or of
the next submission after a flush.
1. X committed after the call (seq >= N): staged after the settle, and
   run after the upload. Its checks see the host write. Right.
2. X committed before the call and submitted before it, which includes
   every X the program waited for: staged before the settle, and run
   before the upload. The settle sees its stores. Right.
3. X committed before the call, not submitted when the call is made, and
   writing T or a resource over T's bytes:
   (a) staged before the settle, in a held group that a later commit
       joins or a flush sends: the upload runs ahead of X, X overwrites
       the host's texels, and T's next write misses its move;
   (b) staged after the settle, and submitted alone before the upload's
       submission: X runs first. The settle missed X's store, so where T
       was fresh its copy goes in with no move after X's write. X's store
       lands after the clear, so T's next write moves T;
   (c) staged after the settle, in the upload's submission or a later
       one: the upload runs ahead of X, X overwrites the texels, and T's
       next write moves it.
In 3a to 3c, X has not completed at the call. Apple's page for
replace(region:mipmapLevel:slice:withBytes:bytesPerRow:bytesPerImage:),
as fetched on 11-25 and relayed by main: "This method runs on the CPU
and immediately copies the pixel data into the texture. It doesn't
synchronize against any GPU memory operations to the texture. Ensure all
operations that write or render to the texture complete before reading
the texture's contents..." So order 3 is the program's race on a Mac too,
and owner rule 1 does not emulate it. The docs state it as the program's
race and say what the runtime does then. The other side, ordering the
upload after earlier commits, was ruled out: it changes the order of
every upload, or adds a second form for heap ones, and blocks the host on
queue room. When a Mac reuses a heap's bytes is unaudited.

Docs: the alias module's "A use that writes" paragraph,
Metrics::heap_moves, replace_region's doc, and the runtime README's heap
paragraph. No refusal or public item changed.

Verified so far: the new test fails at the base on lavapipe (job
m3-max-74235, msi-laptop, llvmpipe): heap_moves (host write, GPU write)
= (0, 1) for mipmaps, blit and load, against (1, 0) wanted. The tip's
lavapipe run, the gates and the device suites are reported to main as
they read.
This commit is contained in:
Anees Iqbal committed 2026-11-25 15:20:16 -08:00
1 parent 358a78fcf3
commit ca3d489bcd
4 files changed
+75 -16

No files matched your search

+5 -2
View File
@@ -1613,8 +1613,11 @@ made, with no lock, and never rewritten for layouts.
`Device::new_heap_texture(descriptor, index, heap, offset)` binds the texture's image at that
offset in the heap, where the consumer's own placement put it: no allocation and no texture
block, the bytes those the memory holds, as Metal does not zero heap textures. Textures may
alias one another and the heap's buffers. 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
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
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
the block, so a released block goes back to the pool only once its textures' images are gone.
`Device::new_heap_buffer(heap, offset, length)` is `newBufferWithLength:options:offset:` of a
+49 -10
View File
@@ -17,7 +17,14 @@
//! 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.
//! 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.
//!
//! 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
@@ -249,6 +256,20 @@ impl Placement {
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.
fn written(&self) {
self.stale.store(false, Relaxed);
let links = lock(&self.links);
for link in links.textures.iter() {
link.stale.store(true, Relaxed);
}
if !links.take_part() && self.linked.swap(false, Relaxed) {
self.heap.linked(false);
}
}
}
impl Drop for Placement {
@@ -431,15 +452,7 @@ pub(crate) fn stage(
.filter_map(|place| place.moved.map(Moved::barrier))
.collect();
for place in &part.writes {
place.stale.store(false, Relaxed);
let links = lock(&place.links);
for link in links.textures.iter() {
link.stale.store(true, Relaxed);
}
// A texture that took part only for the move it owed takes none once written.
if !links.take_part() && place.linked.swap(false, Relaxed) {
place.heap.linked(false);
}
place.written();
}
if moves.is_empty() {
return Ok(None);
@@ -473,6 +486,32 @@ pub(crate) fn stage(
Ok(Some(command))
}
/// A host write of the heap texture placed as `place` (`Texture::replace_region`), recorded into
/// `command`, its upload's, under the work lock, ahead of the write's copy: where the texture is
/// stale, as the submit thread has staged the segments, its move from undefined, as [`record`]
/// records it, counted (`Metrics::heap_moves`); then its write ([`Placement::written`]). Nothing
/// where it takes no part.
///
/// # Safety
///
/// `command` is recording outside a rendering, under the work lock, and its upload keeps the
/// texture until it retires.
pub(crate) unsafe fn host_write(core: &Core, command: vk::CommandBuffer, place: &Placement) {
if !place.linked() {
return;
}
if let Some(moved) = place.moved.filter(|_| place.owes_move()) {
let counters = &core.counters;
// SAFETY: the caller's contract.
unsafe {
record(&core.device, command, &[moved.barrier()], &mut |m| {
counters.count(m)
})
};
}
place.written();
}
/// Records `moves`, heap textures' moves from undefined ([`Marks::used`]), into `command`, the
/// current segment's, in one barrier that orders every earlier command before them and every
/// later one after, each counted (`Metrics::heap_moves`).
+7 -4
View File
@@ -2964,10 +2964,13 @@ pub struct Metrics {
pub overlapping_copies_refused: u64,
/// Heap textures' images moved from undefined to their home layout before a command that
/// writes them (a dispatch's slot or declared write, a pass's attachment, a draw's write, a
/// blit's destination), because a write over their bytes through another resource of their
/// heap left them stale since their last write (Vulkan's memory aliasing): in place, or in a
/// command buffer of its own that leads the command's part of its command buffer. No Metal
/// counterpart.
/// blit's destination) or a host write's copy ([`Texture::replace_region`]), because a write
/// over their bytes through another resource of their heap left them stale since their last
/// write (Vulkan's memory aliasing): in place, in a command buffer of its own that leads the
/// command's part of its command buffer, or in the host write's upload ahead of its copy. No
/// Metal counterpart.
///
/// [`Texture::replace_region`]: crate::Texture::replace_region
pub heap_moves: u64,
/// On a device without `VK_EXT_shader_stencil_export`, the draws recorded beyond a draw's
/// own for a pipeline state whose fragment function writes `[[stencil]]`: one for each
@@ -4574,6 +4574,14 @@ impl Texture {
/// buffer committed after it, so the call is ordered as Metal's CPU write is. Where the region has no room, the call first waits for the oldest copy in it to
/// complete. Counted in [`Metrics::bytes_copied`]. An empty region copies nothing.
///
/// A heap texture ([`Device::new_heap_texture`]) whose bytes another resource of its heap
/// wrote since its last write moves from undefined ahead of the copy, counted in
/// [`Metrics::heap_moves`], so its next write keeps the texels the call wrote; the heap's
/// other textures over its bytes move before their next writes. A call while a command buffer
/// committed before it, and not yet completed, writes the texture's bytes or another
/// resource's over them is the program's race, as Metal's makes it: the upload may run ahead
/// of that command buffer, and the texture's next write may move it.
///
/// A Managed texture with named bytes ([`Device::new_managed_texture`]) takes them there
/// instead, as Metal writes a Managed texture's CPU copy, and then
/// [`Texture::upload_region`] copies them into the image; nothing is staged or counted. A
@@ -4591,6 +4599,7 @@ impl Texture {
/// [`Buffer::did_modify_range`] returns.
///
/// [`Metrics::bytes_copied`]: crate::Metrics::bytes_copied
/// [`Metrics::heap_moves`]: crate::Metrics::heap_moves
pub fn replace_region(
&self,
region: Region,
@@ -4647,6 +4656,11 @@ impl Texture {
[Held::Texture(Arc::clone(inner.imaged()))],
// SAFETY: recording under the work lock, the upload holding the image and the stage.
|device, command| unsafe {
// A heap texture an alias's write left stale moves from undefined before the
// copy, and the textures over its bytes are left stale (`crate::alias`).
if let Some(place) = inner.placement() {
crate::alias::host_write(core, command, place);
}
let region = copy.buffer_image_copy(stage.offset(), 0, 0);
inner.record(
device,