Copied host buffers copy in again as a batch waits out an event its commit came before

A commit copies into each copied host buffer the bytes the CPU changed in
its pages, before any of the command buffer's work is submitted. A batch
that waits for an event runs its commands only once the event reaches
the value, and on Metal those commands read the pages as they stand
then. So a CPU write made after the commit and before the host's signal
(or before a later command buffer's signal) never reached the copy, and
the waiting command buffer read the bytes from before it.

The commit now notes, before its copy in, the batches that wait for an
event value not yet reached (CopiesAgain::unreached, from each event's
timeline). When the scheduler submits such a batch, which it does only
once the wait is met, submit_batch first copies in again
(copy_in_again): the copies the command buffer reaches, as at the
commit, take the CPU's changes since. This runs with no lock of the
command buffer held, since a copy over logged pages waits for the log's
publication. A batch with no wait, or whose every wait was already
reached at the commit, copies nothing more. The new counter is
WorkCounts::copied_copy_ins_after_waits.

The same mechanism serves a reader held by an event across queues: the
signal of a batch submitted while a copy is live is seen only at its
completion turn, after the merge back. The FAST-PATHS gap that listed
event-ordered reads across queues as stale now says the held reader
copies in again; that case is expected from the code and not run.

Docs: copied.rs (Coherence, the two-memories bullet, copy_in),
dirty_pages.rs (stamps), HOWTO (copied host buffers), FAST-PATHS (cost
row and gap), api_signatures.tsv (the new field).

Verified: waited_reads in the jobs named in the report. The copied leg
fails at cae2e24b4d and passes here; the no-wait copied leg makes 0
copies in again.
This commit is contained in:
Anees Iqbal committed 2026-11-11 22:35:50 -08:00
1 parent 388c2c0d14
commit 84b6b4295b
10 files changed
+181 -28

No files matched your search

@@ -0,0 +1,100 @@
//! Copied host buffers copied in again after an event wait (`copied.rs`, **Coherence**).
//!
//! A commit copies into each copy its commands reach the bytes the CPU changed in its pages,
//! before any of its work is submitted. A batch that waits for an event runs its commands once
//! the event reaches the value, and Metal's reads there see the pages as they stand then: a CPU
//! write made after the commit and before the signal (the host's, or a command buffer's committed
//! after it) is read. So a batch whose wait the commit found not reached, as it stood before the
//! commit's copy in, copies in again as it is submitted, which the scheduler does only once the
//! wait is met: the copies the command buffer's commands reach, as at the commit, take the bytes
//! the CPU changed since. Counted: `WorkCounts::copied_copy_ins_after_waits`.
//!
//! A batch with no wait, and one whose every wait the commit found reached, copies in nothing
//! more: every CPU write before its commands may run was made before the commit's copy in. A wait
//! a GPU signal meets that a copy's merge back must come before is held on the host until that
//! merge (`event_timeline.rs`), so the copy in again after it takes the merged bytes too.
use super::batches::Batch;
use super::{lock, recording_error, CommandBufferShared};
use crate::copied::CopiesReached;
use crate::error::{CommandBufferError, Error, MemoryKind};
use crate::event::EventShared;
use crate::event_timeline::WaitFor;
use ash::vk;
use std::sync::Arc;
/// The batches of a committed command buffer that copy in again, and the copies its commands
/// reach.
pub(super) struct CopiesAgain {
/// The batches, by index, not yet submitted.
batches: Vec<usize>,
/// The copies its commands may read, and those they may write, as the commit found them
/// (`CopiedBuffers::copy_in`).
reached: Arc<(CopiesReached, CopiesReached)>,
}
impl CopiesAgain {
/// The indices of `batches` that wait for an event value not reached now.
pub(super) fn unreached(batches: &[Batch<Arc<EventShared>, vk::Semaphore>]) -> Vec<usize> {
(batches.iter().enumerate())
.filter(|(_, batch)| {
(batch.waits.iter())
.any(|(event, value)| event.wait(*value) != Some(WaitFor::Reached))
})
.map(|(index, _)| index)
.collect()
}
/// The copies in again of `batches`, reaching `reached`; `None` where there are none.
pub(super) fn new(
batches: Vec<usize>,
reached: (CopiesReached, CopiesReached),
) -> Option<CopiesAgain> {
(!batches.is_empty()).then(|| CopiesAgain {
batches,
reached: Arc::new(reached),
})
}
}
impl CommandBufferShared {
/// Copy in again for batch `index`, where its commit left one for it, once: as it is
/// submitted, its waits met. Copied with no lock of the command buffer's held, as a copy over
/// logged pages waits for the log's publication; where the host has no memory for a copy's
/// base, the command buffer fails as out of memory, as its commit would have.
pub(super) fn copy_in_again(&self, index: usize) -> Result<(), CommandBufferError> {
let reached = {
let mut state = lock(&self.state);
let Some(again) = &mut state.copies_again else {
return Ok(());
};
let Some(at) = again.batches.iter().position(|&batch| batch == index) else {
return Ok(());
};
again.batches.swap_remove(at);
let reached = Arc::clone(&again.reached);
if again.batches.is_empty() {
state.copies_again = None;
}
reached
};
let device = &self.device;
let shared = device.shared();
let (used, written) = &*reached;
let copied_in = shared.copied.copy_in(
&shared.counts,
shared.dirty.tally(),
(used, written),
|| shared.dirty.in_flight(),
&mut |length| device.copied_base(length),
);
if copied_in.is_err() {
return Err(recording_error(
device,
Error::OutOfMemory(MemoryKind::Host),
));
}
shared.counts.copied_copy_ins_after_waits();
Ok(())
}
}
@@ -34,6 +34,7 @@
pub(super) mod batches;
pub(super) mod checks;
pub(super) mod completion;
mod copies_again;
pub(super) mod fences;
mod first_submission;
pub(super) mod follow;
@@ -52,6 +53,7 @@ mod storage_form;
mod submit;
pub(super) use completion::Completion;
use copies_again::CopiesAgain;
pub(super) use first_submission::{NotedTable, ReplayTable};
use follow::{Follow, Release};
pub(super) use group::{Group, GroupEnd, GROUP_BATCHES};
@@ -898,6 +900,9 @@ pub(super) struct State {
/// Why a host step failed: the batch it recorded for is not submitted, and the command buffer
/// finishes with it.
step_failure: Option<CommandBufferError>,
/// The batches that copy copied host buffers in again as they are submitted, after an event
/// wait their commit's copy in came before (`copies_again.rs`).
copies_again: Option<CopiesAgain>,
/// The refusal of a host step that failed so (`CommandBufferError::Refused`).
refusal: Option<Error>,
/// The first dispatch's pipeline whose making failed, which a host step met
@@ -2293,6 +2298,7 @@ impl CommandBuffer {
faults: ReplayFaults::default(),
placed: 0,
step_failure: None,
copies_again: None,
refusal: None,
failed_pipeline: None,
dropped_draw: None,
@@ -3619,13 +3625,17 @@ impl CommandBuffer {
// Each such copy its commands may write takes a base of the bytes it then holds, before
// any of its work is submitted; where the host has no memory for one, the command
// buffer runs nothing (`copied.rs`, "A base once it may").
// A batch that waits for an event value not reached before this copy in copies in again
// as it is submitted, after the wait (`copies_again.rs`).
let mut copies_again = None;
if shared.copied.any() {
let (mut used, mut written) = (CopiesReached::default(), CopiesReached::default());
let unnoted = self.0.unnoted.load(Ordering::Relaxed);
// The state's lock goes before the dirty log's is taken.
let (reaches, writes) = {
let (reaches, writes, unreached) = {
let state = self.state();
(state.reaches_unnamed, state.writes_unnamed)
let unreached = CopiesAgain::unreached(state.batches.all());
(state.reaches_unnamed, state.writes_unnamed, unreached)
};
match unnoted || reaches {
true => used.reached_all(),
@@ -3646,10 +3656,12 @@ impl CommandBuffer {
self.state().committing = false;
return Err(Error::OutOfMemory(MemoryKind::Host));
}
copies_again = CopiesAgain::new(unreached, (used, written));
}
let (waits, away, reaches, unreplayable, reset) = {
let mut state = self.state();
state.committing = false;
state.copies_again = copies_again;
if let Some(failure) = failure {
state.fail(failure);
}
@@ -428,6 +428,9 @@ impl CommandBufferShared {
if device.is_lost() {
return Err(CommandBufferError::DeviceLost);
}
// A batch that waits for an event value its commit's copy in came before copies the
// copied host buffers in again, its wait met (`copies_again.rs`).
self.copy_in_again(index)?;
let shared = device.shared();
let raw = shared.vk();
let queue = self.queue.vk_queue();
+15 -9
View File
@@ -31,7 +31,11 @@
//! changed in the pages since then is written into each copy its commands use, or into every copy
//! where one may reach memory no use names (a function that reaches buffers through addresses,
//! work on the GPU alone; [`CopiedBuffers::copy_in`]): a copy the command buffer does not use
//! takes the CPU's writes at the first commit that uses it. At each batch's completion, before
//! takes the CPU's writes at the first commit that uses it. A batch that waits for an event value
//! not reached before that copy in runs its commands after the wait, where Metal's read the
//! pages as they stand then: it copies in again the same way as it is submitted, its wait met
//! (`command_buffer/copies_again.rs`, `WorkCounts::copied_copy_ins_after_waits`), so a CPU
//! write made before the signal reaches it. At each batch's completion, before
//! its events are seen signaled, the scheduler is told, its handlers run or a waiter returns,
//! every byte the GPU changed in the copy is written back into the pages, where the CPU did not
//! change that byte since ([`CopiedBuffers::merge_back`]): a byte both changed keeps the CPU's,
@@ -128,10 +132,10 @@
//! bytes for the other storage mode's class (a `Managed` buffer's import, then a `Shared`
//! buffer's copy where the gate refused its own), are two memories, which agree only through
//! the pages: at the writer's completion (its merge back, or its writes in place) and at the
//! reader's commit (its copy in). A read committed before the write completed reads the bytes
//! as of its commit, wherever the tracker orders it after the write: in one command buffer, in
//! one queue's command buffers in flight together, and across queues an event orders, as the
//! held reader is not copied in again when the event releases it. Of two such copies written in
//! reader's commit (its copy in), or a batch's submission after an event wait its commit came
//! before (its copy in again, above). A read committed before the write completed reads the
//! bytes as of its commit, wherever the tracker orders it after the write: in one command
//! buffer, and in one queue's command buffers in flight together. Of two such copies written in
//! flight, the second's merge back takes a byte the first merged for the CPU's write, which a
//! merge keeps, so the first write stays where Metal keeps the later.
//! - **Event signals.** A batch's event signals, submitted while a copy is live, are seen at its
@@ -1155,10 +1159,12 @@ impl CopiedBuffers {
}
}
/// At a commit: write into each copy the command buffer's commands may reach (`used`: the
/// keys they used, `DirtyCommit::copies_used`, or every copy where one may reach memory no
/// use names) the bytes the CPU changed in its pages since they last agreed, before any of
/// the command buffer's work is submitted. A copy none of them reaches is neither compared nor
/// At a commit, before any of the command buffer's work is submitted, and again as a batch
/// that waits for an event value not reached before the commit's copy in is submitted
/// (`command_buffer/copies_again.rs`): write into each copy the command buffer's commands may
/// reach (`used`: the keys they used, `DirtyCommit::copies_used`, or every copy where one may
/// reach memory no use names) the bytes the CPU changed in its pages since they last agreed.
/// A copy none of them reaches is neither compared nor
/// asked of its logs, and keeps the stamp it last synced to, so the first commit whose
/// commands reach it takes every write since: a command buffer reads only the resources its
/// commands use, as Metal's GPU reaches only those (counted:
@@ -11,8 +11,10 @@
//! its copies takes the pages again, and waits for that publication as the batch that holds
//! the copy is submitted, which records the copy then (`shadow::GatedCopyIn`,
//! [`DirtyPages::wait`]); a copied host buffer (`copied.rs`), whose copy in is the commit's
//! own, asks and waits at the commit, one stamp of each log for every copy. A copy then syncs
//! to that stamp: every write made after it is stamped later.
//! own, asks and waits at the commit, one stamp of each log for every copy, and again as a batch
//! that waits for an event value not reached before that copy in is submitted
//! (`command_buffer/copies_again.rs`). A copy then syncs to that stamp: every write made after
//! it is stamped later.
//! - **The pages changed** ([`DirtyPages::changed_except`]) since the stamp a copy synced to, by
//! any writer but that copy's own, are the only bytes it may lack: they are copied in, the rest
//! skipped. Copied host buffers ask once per log and stamp for all of them, every writer's
@@ -13,8 +13,10 @@
//! CPU writes a second pattern (told to the log), and the host signals: both blits must read the
//! second.
//!
//! And the same rounds over a copy with no wait, the second pattern written before the second
//! command buffer's commit: what each commit copies in.
//! Over a copy, each waiting command buffer copies in again as its batch is submitted after the
//! wait (`command_buffer/copies_again.rs`, `WorkCounts::copied_copy_ins_after_waits`): one a
//! round. The same rounds over a copy with no wait, the second pattern written before the second
//! command buffer's commit, copy in again never: only at each commit.
//!
//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects.
@@ -116,10 +118,11 @@ fn first_wrong(out: &Buffer, value: u8) -> Option<(&'static str, usize, u8)> {
Some((read, at % SPAN as usize, bytes[at]))
}
/// What the rounds moved: (copied bytes copied in, logged copies in gated, logged copies in
/// whole).
fn moved(before: &WorkCounts, after: &WorkCounts) -> [u64; 3] {
/// What the rounds moved: (copied copies in again after waits, copied bytes copied in, logged
/// copies in gated, logged copies in whole).
fn moved(before: &WorkCounts, after: &WorkCounts) -> [u64; 4] {
[
after.copied_copy_ins_after_waits - before.copied_copy_ins_after_waits,
after.copied_copy_in_bytes - before.copied_copy_in_bytes,
after.dirty_copies_in_gated - before.dirty_copies_in_gated,
after.dirty_copies_in_whole - before.dirty_copies_in_whole,
@@ -180,17 +183,23 @@ fn run(case: &str, home: Home, waits: bool) {
failures.push(format!("round {round}: the read after: {wrong:x?}"));
}
}
let moved = moved(&before, &device.work_counts());
eprintln!(
"WAITED-READS {case} on {}: {} wrong reads of {}; (copied bytes copied in, logged copies \
in gated, whole) {:?} over {} commits; first {:?}",
"WAITED-READS {case} on {}: {} wrong reads of {}; (copied copies in again after waits, \
copied bytes copied in, logged copies in gated, whole) {moved:?} over {} commits; first \
{:?}",
device.name(),
failures.len(),
2 * ROUNDS,
moved(&before, &device.work_counts()),
2 * ROUNDS,
failures.first()
);
assert!(failures.is_empty(), "{case}: {failures:?}");
let again = match (home, waits) {
(Home::Copied, true) => ROUNDS,
_ => 0,
};
assert_eq!(moved[0], again, "{case}: copies in again after waits");
}
#[test]
@@ -387,6 +387,7 @@ pub(crate) struct Counters {
copied_copy_in_bytes: AtomicU64,
copied_copy_in_bytes_skipped: AtomicU64,
copied_copy_ins_unused: AtomicU64,
copied_copy_ins_after_waits: AtomicU64,
copied_merge_back_bytes: AtomicU64,
copied_merges_compared: AtomicU64,
copied_merges_skipped: AtomicU64,
@@ -3599,6 +3600,12 @@ impl Counters {
(self.copied_copy_ins_unused).fetch_add(copies, Ordering::Relaxed);
}
/// A batch whose event wait its commit's copy in came before copied the copied host buffers
/// in again as it was submitted (`command_buffer/copies_again.rs`).
pub(crate) fn copied_copy_ins_after_waits(&self) {
(self.copied_copy_ins_after_waits).fetch_add(1, Ordering::Relaxed);
}
/// A batch's completion merged `bytes` the GPU changed back into the caller's pages
/// (`copied.rs`).
pub(crate) fn copied_merged_back(&self, bytes: u64) {
@@ -7350,6 +7357,11 @@ pub struct WorkCounts {
/// name), so neither their bytes nor their pages' logs were asked; the first commit that uses
/// one takes every write since.
pub copied_copy_ins_unused: u64,
/// The copies in again of copied host buffers, one per batch: a batch that waits for an event
/// value its command buffer's commit found not reached, before the commit's copy in, copies
/// in again as it is submitted, after the wait, so its commands read the CPU's writes made
/// before the signal, as Metal's do. A command buffer with no such wait makes none.
pub copied_copy_ins_after_waits: u64,
/// The bytes the GPU changed in copied host buffers' copies that batches' completions merged
/// back into the caller's pages.
pub copied_merge_back_bytes: u64,
@@ -9397,6 +9409,8 @@ impl Device {
copied_copy_in_bytes_skipped: (counters.copied_copy_in_bytes_skipped)
.load(Ordering::Relaxed),
copied_copy_ins_unused: counters.copied_copy_ins_unused.load(Ordering::Relaxed),
copied_copy_ins_after_waits: (counters.copied_copy_ins_after_waits)
.load(Ordering::Relaxed),
copied_merge_back_bytes: counters.copied_merge_back_bytes.load(Ordering::Relaxed),
copied_merges_compared: counters.copied_merges_compared.load(Ordering::Relaxed),
copied_merges_skipped: counters.copied_merges_skipped.load(Ordering::Relaxed),
@@ -2680,6 +2680,7 @@ field metal2vulkan-runtime::WorkCounts.copied_bases_refused pub copied_bases_ref
field metal2vulkan-runtime::WorkCounts.copied_compare_threads pub copied_compare_threads: u64
field metal2vulkan-runtime::WorkCounts.copied_copy_in_bytes pub copied_copy_in_bytes: u64
field metal2vulkan-runtime::WorkCounts.copied_copy_in_bytes_skipped pub copied_copy_in_bytes_skipped: u64
field metal2vulkan-runtime::WorkCounts.copied_copy_ins_after_waits pub copied_copy_ins_after_waits: u64
field metal2vulkan-runtime::WorkCounts.copied_copy_ins_unused pub copied_copy_ins_unused: u64
field metal2vulkan-runtime::WorkCounts.copied_dropped_bytes pub copied_dropped_bytes: u64
field metal2vulkan-runtime::WorkCounts.copied_heaps_made pub copied_heaps_made: u64
Can't render this file because it is too large.
+8 -4
View File
@@ -603,7 +603,10 @@ driver's. Each is open work.
copies the texels in before each command buffer that uses the texture and merges them back
after each write.
- **A copied host buffer costs O(its size) at every batch's completion that may have written it, and
at every commit where its pages carry no log** (`copied.rs`, `copied-host-pages`): until a command
at every commit where its pages carry no log** (`copied.rs`, `copied-host-pages`), and again at
the submission of each batch that waits for an event value its commit found not reached
(`command_buffer/copies_again.rs`, `copied_copy_ins_after_waits`; none for a command buffer
without such a wait): until a command
buffer that may write the copy is committed, a commit compares the pages with the copy a page at a
time; from then on each comparison reads one side whole (the pages at a commit, the copy at a
completion) and compares each 1 KiB block's tag with its base's (below), reading the other side's
@@ -695,9 +698,10 @@ driver's. Each is open work.
the same bytes for the other storage mode (a `Managed` buffer's import, then a `Shared` buffer
over them whose import the gate refused). The writer's bytes reach the pages
at its completion, and the reader's copy at its commit, so a read committed before the write
completed reads the bytes from before it: in one command buffer, in one queue's command buffers
in flight together, and across queues an event orders (the held reader is not copied in again
when the event releases it). Of two such copies written in flight, the first's write stays where
completed reads the bytes from before it: in one command buffer, and in one queue's command
buffers in flight together. A reader held by an event wait its commit found not reached copies in
again once the wait is met (`command_buffer/copies_again.rs`). Of two such copies written in
flight, the first's write stays where
Metal keeps the later. Buffers over exactly the bytes a live copy covers lie in that copy and are
one memory (`copied_host_buffers_shared`).
- **A copied host buffer's merge keeps the CPU's byte where the CPU and the GPU both wrote it**
+5 -3
View File
@@ -544,9 +544,11 @@ with buffers another thread makes on the same device.
The copy is host-visible memory of the device's own; the buffer's `contents` is still the pointer.
Each commit writes into the copy every byte the CPU changed in the pages since the copy and the
pages last agreed, and each batch's completion writes back every byte the GPU changed, before its
handlers run or a waiter returns, keeping a byte the CPU changed since (`copied_copy_in_bytes`,
`copied_merge_back_bytes`). Until a command buffer that may write the copy is committed, the copy
pages last agreed, and so does the submission of a batch that waits for an event value not reached
at the commit, once the wait is met (`copied_copy_ins_after_waits`), as Metal's commands after the
wait read the pages as they stand then. Each batch's completion writes back every byte the GPU
changed, before its handlers run or a waiter returns, keeping a byte the CPU changed since
(`copied_copy_in_bytes`, `copied_merge_back_bytes`). Until a command buffer that may write the copy is committed, the copy
itself holds the bytes the pages and it agree on, and nothing else is kept: a copy the GPU only
reads costs its own length and no more. At the first such commit the copy takes a base
(`copied_bases_made`): a 128-bit tag of each 1 KiB block in host memory (a 64th of the copy's