Keep a shadow's standing across command buffers where only the runtime's commands write its truth

A texture over a tracked Private buffer the runtime made (an IOSurface plane's
device copy among them) copied its truth in again at every command buffer's
first use, as if the CPU could have written it since the last commit. Only the
runtime's commands write such a buffer, so whether the image still holds the
truth is known exactly in the scheduler's order, the order the tracker orders
tracked work in across queues.

shadow_standing.rs: a command buffer's last batch, holding its last encoder,
with nothing failed or reaching memory unnamed, records each shadow its end
left holding every texel (ShadowCarry::held_whole) as standing at the write
counts of its keys (the truth's, the host memory it joined, the image's).
Each submitted batch's tracked writes count against those keys; a command
buffer that may reach memory no use names (root tables, executions resolved
from records, unnoted) counts against all. A command buffer's first copy in
of such a shadow, before its encoder wrote what it reads, goes to its batch's
submission (GatedCopyIn with CopyGate::Standing) and moves nothing where the
shadow stands and no earlier encoder of the command buffer wrote its keys. A
buffer whose VkBuffer was handed out never stands (Buffer::vk_buffer's doc
says so). Counted: WorkCounts::shadow_copies_in_against_standing,
shadow_copies_in_skipped_by_standing, shadow_texels_skipped_by_standing.

Verified: to build and run on the M3 (tests::shadow_standing_device: a later
read skips; another queue's fill lets go and reaches the texture; a write
through the texture reaches the buffer, its gaps kept; a fill earlier in the
same command buffer copies in; a handed-out VkBuffer never stands).

(cherry picked from commit 255f77bc0efcdc166031aadec328669d77e6075e)
This commit is contained in:
Anees Iqbal committed 2026-11-05 13:14:46 -08:00
1 parent b38f83b466
commit 3928b662ca
20 files changed
+669 -23

No files matched your search

+17
View File
@@ -94,6 +94,10 @@ struct BufferShared {
bytes: Bytes,
/// The encoder core that holds it from an argument table's retain (`retained::HeldBy`).
held_by: HeldBy,
/// Its `VkBuffer` was handed out (`Buffer::vk_buffer`): the caller's own work may write its
/// bytes, so no shadow over them keeps a standing across command buffers
/// (`shadow_standing.rs`).
handed_out: Arc<AtomicBool>,
}
/// Where a buffer's bytes are.
@@ -2593,6 +2597,7 @@ impl Device {
attributes: ResourceAttributes::new(),
bytes: Bytes::Own(own),
held_by: HeldBy::default(),
handed_out: Arc::default(),
}))
}
@@ -2789,6 +2794,7 @@ impl Heap {
aliasable: AtomicBool::new(self.heap_type() == HeapType::Placement),
}),
held_by: HeldBy::default(),
handed_out: Arc::default(),
}))
}
}
@@ -2965,6 +2971,17 @@ impl Buffer {
self.at_for(offset, ReadApart::Binding)
}
/// Whether its `VkBuffer` was handed out, shared with what watches it
/// (`shadow_standing::Standing`).
pub(super) fn handed_out(&self) -> Arc<AtomicBool> {
Arc::clone(&self.0.handed_out)
}
/// Note that its `VkBuffer` was handed out (`Buffer::vk_buffer`).
pub(super) fn hand_out(&self) {
self.0.handed_out.store(true, Ordering::Release);
}
/// [`Buffer::at`] for `reason`, which a no-copy buffer's import counts its read apart for
/// (`HostImport::note_read_apart`).
pub(super) fn at_for(&self, offset: u64, reason: ReadApart) -> (vk::Buffer, u64) {
@@ -49,6 +49,7 @@ use super::shadow::{
use super::shadow_copy_back::WordView;
use super::shadow_merge::ScratchSpares;
use super::shadow_merge::UnormView;
use super::shadow_standing::Standing;
use super::texture::surface_two_planes;
use super::texture::{IdUse, Texture};
use super::texture_descriptor::{
@@ -1183,6 +1184,7 @@ impl Texels {
backing: self.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
})
}
@@ -1352,6 +1354,7 @@ impl Texels {
backing: texels.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
};
texels.staged = Some(Arc::new(copies));
let (offset, alignment) = (
@@ -1481,6 +1484,7 @@ impl Texels {
backing: self.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Standing::over(&self.buffer),
})
}
@@ -217,6 +217,7 @@ use crate::gpu_time;
use crate::release;
use crate::resource::ResourceKey;
use crate::scheduler;
use crate::shadow::ShadowCopies;
use crate::sparse::bind::{bind_batch, BindFailure, Bound};
use crate::sparse::encoder::SparseUpdate;
use crate::texture::decoded_twin::{SecondDecode, TwinWrite};
@@ -226,6 +227,7 @@ use crate::tracker::{Barrier, Point, Summary};
use crate::work_counts::Begun;
use ash::vk;
use std::collections::BTreeSet;
use std::sync::atomic::Ordering;
use std::sync::Arc;
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
use {crate::tracker::Footprint, std::sync::Mutex};
@@ -1154,6 +1156,23 @@ impl CommandBufferShared {
let handlers = (schedules && !state.submission.is_empty()) || forms;
state.submitting = handlers;
scheduler.tracker.apply(plan);
// The standings across command buffers, in the order the tracker took the batch
// (`shadow_standing.rs`): its writes let go of those they meet; then, where it ends the
// command buffer with its last encoder and nothing failed it or reached memory unnamed,
// the shadows its end left holding every texel of their truth stand.
let unnamed = state.reaches_unnamed || self.unnoted.load(Ordering::Relaxed);
let clean = state.failure.is_none()
&& state.fails_from.is_none()
&& state.faulted.is_empty()
&& state.hang.is_none()
&& !rebound;
let ends = last && start < end && end == state.recorded.len() && clean && !unnamed;
let held = match (ends, &state.shadow_carry) {
(true, Some(carry)) => carry.held_whole(),
_ => Vec::new(),
};
let summaries = (state.recorded[start..end].iter()).map(|recorded| &recorded.summary);
shared.standings.submitted(summaries, unnamed, &held);
held_moves.submitted();
shared.counts.held_depths_released(held_moves.released);
let several = shared.queues.len() > 1;
@@ -1411,6 +1430,13 @@ impl CommandBufferShared {
continue;
}
}
// A copy in its shadow's standing decides moves nothing where the image stands now
// (`shadow_standing.rs`).
let standing = match &work {
Deferred::GatedCopyIn(copy) => copy.standing(),
_ => None,
};
let stands = standing.is_some_and(|copies| self.stands(state, encoder, copies));
let raw = self.record_raw(state, |state, buffer| {
match &work {
// SAFETY: the command buffer is recording; the texture is live (its encoder's
@@ -1425,7 +1451,7 @@ impl CommandBufferShared {
// shadowed texture is live (its encoder's command buffer holds it), its
// image in `GENERAL`.
Deferred::GatedCopyIn(copy) => unsafe {
copy.record(device.shared().vk(), buffer)
copy.record(device.shared().vk(), buffer, stands)
},
// SAFETY: the command buffer is recording, outside a render pass; the merge,
// its images and its scratch are held until it completes (its pass's encoder
@@ -1445,10 +1471,25 @@ impl CommandBufferShared {
})?;
state.recorded[encoder].segments[at].recorded =
Some(RecordedSegment::submitted(vec![raw]));
if let (Some(_), Deferred::GatedCopyIn(copy)) = (standing, &work) {
(device.shared().counts).shadow_copy_in_against_standing(stands, copy.texels());
}
}
Ok(())
}
/// Whether `copies`' image stands across command buffers (`shadow_standing.rs`) for a copy
/// in of encoder `encoder`, submitted now: it stands, no earlier encoder of the command
/// buffer wrote the truth or the image, and none of its commands may reach memory no use
/// names.
fn stands(&self, state: &State, encoder: usize, copies: &ShadowCopies) -> bool {
let keys = copies.standing_keys();
let unnamed = state.reaches_unnamed || self.unnoted.load(Ordering::Relaxed);
let wrote =
(state.recorded[..encoder].iter()).any(|recorded| recorded.summary.writes_any(&keys));
!unnamed && !wrote && self.device.shared().standings.stands(copies)
}
/// Record the decodes into ASTC carriers' second decoded twins (`texture/decoded_twin.rs`) of
/// the batch of encoders `range`, a batch with work: those queued (as each twin was made,
/// and after host calls wrote its carrier), in one command buffer before the first part's
@@ -485,6 +485,9 @@ pub(super) struct DeviceShared {
/// The logs of its shadows over host pages a consumer logs the writes to
/// (`dirty_pages.rs`).
pub(super) dirty: super::dirty_pages::DirtyShadows,
/// The writes that let go of its shadows' standings across command buffers
/// (`shadow_standing.rs`).
pub(super) standings: super::shadow_standing::Standings,
/// The new textures that read zero where Metal reads its pattern, until a command observes
/// or covers that (`fresh_unwritten.rs`).
pub(super) fresh: super::fresh_unwritten::FreshUnwritten,
@@ -2039,6 +2042,7 @@ impl Device {
#[cfg(test)]
linear_rule_forced: Default::default(),
dirty: Default::default(),
standings: Default::default(),
fresh: Default::default(),
owners: Default::default(),
live_buffers: Default::default(),
+17 -8
View File
@@ -33,7 +33,6 @@ use super::churn_counts::KeepBy;
use super::command_buffer::rebound_use::Unlogged;
use super::command_buffer::{recording_error, CommandBuffer};
use super::deferred::{Deferred, StepInputs};
use super::dirty_pages::CopyInGate;
use super::error::{internal, invalid, vulkan, CommandBufferError, Error, Problem};
use super::execution::Execution;
use super::fresh_unwritten::{FreshRead, FreshUnwritten};
@@ -55,7 +54,7 @@ use super::resource::ResourceKey;
use super::retained::Retained;
use super::row_copies::RowCopies;
use super::shadow::{
CopyCause, GatedCopyIn, ShadowCopies, ShadowCopy, ShadowSync, ShadowUse, Step, Within,
CopyCause, CopyGate, GatedCopyIn, ShadowCopies, ShadowCopy, ShadowSync, ShadowUse, Step, Within,
};
use super::shadow_copy_in::CopyIn;
use super::shadow_merge::{MergeLease, ShadowMerge};
@@ -1872,13 +1871,23 @@ impl EncoderCore {
),
};
// A copy in over host pages a consumer logs takes the regions its gate decides as its
// batch is submitted (`dirty_pages.rs`, `shadow::GatedCopyIn`).
// batch is submitted (`dirty_pages.rs`, `shadow::GatedCopyIn`); a command buffer's
// first copy in of a shadow that may stand across command buffers, before any command
// of the encoder wrote what it reads, moves nothing where the image stands then
// (`shadow_standing.rs`).
let gate = match &dispatched {
Some(_) => None,
None => copy.gate_log(&device).map(|(log, texel)| {
let shadows = &device.shared().dirty;
(self.open.command_buffer.dirty()).gate((log, &copy.copies, texel), shadows)
}),
None => match copy.gate_log(&device) {
Some((log, texel)) => {
let shadows = &device.shared().dirty;
let dirty = self.open.command_buffer.dirty();
Some(CopyGate::Log(
dirty.gate((log, &copy.copies, texel), shadows),
))
}
None => (copy.left_to_standing() && !self.uses.written(&uses))
.then_some(CopyGate::Standing),
},
};
// A keep may copy the staging buffer its copy in filled only where that copy in
// copies the texture's bytes whole: recorded here, ungated.
@@ -1973,7 +1982,7 @@ impl EncoderCore {
/// ahead of the pass's draws that read the copy. Recorded whole here instead inside a
/// predicated loop's laying, which its check may submit again, or where no new
/// `VkCommandBuffer` can be made.
fn defer_copy_in(&mut self, copy: &ShadowCopy, gate: Arc<CopyInGate>) {
fn defer_copy_in(&mut self, copy: &ShadowCopy, gate: CopyGate) {
let laying = (self.open.command_buffer.state().predication_mut()).laying();
let next = match laying {
true => None,
@@ -194,12 +194,16 @@ impl Buffer {
/// buffer bound below an unaligned pointer. No Metal counterpart: an interop hook. A buffer the
/// runtime placed in its own memory has no `SHADER_DEVICE_ADDRESS` usage of its own (it takes
/// its address from its memory block's buffer), so the caller asks it for no device address.
/// Once it was handed out, a shadowed texture over a `Private` buffer's bytes copies them in
/// at each command buffer's first use, as one over the CPU's bytes does: the caller's own
/// work may write them.
///
/// # Safety
///
/// The `VkBuffer` stays the runtime's: the caller does not destroy it, and uses it only while
/// the buffer lives, ordered against the runtime's work on it.
pub unsafe fn vk_buffer(&self) -> (vk::Buffer, u64) {
self.hand_out();
self.at_for(0, ReadApart::VkBuffer)
}
+1
View File
@@ -213,6 +213,7 @@ mod shadow;
mod shadow_copy_back;
mod shadow_copy_in;
mod shadow_merge;
mod shadow_standing;
mod shadow_stencil;
mod shards;
mod sharing;
+79 -13
View File
@@ -23,7 +23,10 @@
//! its batch's earlier encoder left holding the truth and copies nothing in ([`ShadowCarry`]); an
//! encoder that starts another batch, after a signal, a wait or a host step, copies in again
//! before its first command that uses the texture, which runs after the commands before it; and
//! a later command buffer copies in the bytes Metal would read there. A copy in
//! a later command buffer copies in the bytes Metal would read there, but where only the
//! runtime's commands write them (a tracked `Private` buffer's, `shadow_standing.rs`): there
//! its first copy in moves nothing where the image an earlier command buffer's end left
//! holding them still holds them as its batch is submitted. A copy in
//! of a one-level, one-slice texture's image moves only the texels inside the rectangle its
//! command reads and writes them in, where the command bounds that ([`ShadowUse::loads`]: a
//! pass's attachment it loads and takes no other way, inside its draws' scissors). The image's
@@ -228,6 +231,7 @@ use super::rotated::{RotatedCopies, Turn};
use super::row_copies::RowCopies;
use super::shadow_copy_back::{CopyBack, WordView};
use super::shadow_merge::{ScratchSpares, ShadowMerge, UnormView};
use super::shadow_standing::Standing;
use super::texture::copy_images::UseMaker;
use super::texture::heap_tiled::{HeapTiledCopies, SampleMoves};
use super::texture::heap_two_planes::{HeapPlaneCopies, TwoPlaneHeapLayout};
@@ -269,6 +273,9 @@ pub(super) struct ShadowCopies {
/// serve is counted as one an earlier command buffer's standing stands behind, or as one of a
/// shadow that never held a standing ([`CarryTally`]).
pub(super) stood: AtomicU64,
/// Where only the runtime's commands write the truth, the image's standing across command
/// buffers (`shadow_standing.rs`).
pub(super) standing: Standing,
}
/// The texels of a texture over an IOSurface's plane from which its shadow's copies in count
@@ -882,6 +889,23 @@ impl ShadowCopies {
}
}
/// Whether the image may keep a standing across command buffers (`shadow_standing.rs`): a
/// shadow of a buffer's bytes that only the runtime's commands write
/// ([`only_commands_write`](Self::only_commands_write)), whose writes reach them, over a
/// buffer of the runtime's own whose `VkBuffer` was never handed out.
pub(super) fn stands_across(&self) -> bool {
let bytes = matches!(self.source, ShadowSource::Bytes { .. });
bytes && self.only_commands_write() && !self.drops_writes && self.standing.may_stand()
}
/// The keys a write of which lets go of the image's standing across command buffers: the
/// truth's, the host memory it joined, and the image's own.
pub(super) fn standing_keys(&self) -> Vec<ResourceKey> {
let mut keys = vec![self.truth().0, self.shadow_key];
keys.extend(self.alias());
keys
}
/// Whether what the commands write through the shadow goes back into its truth as a merge
/// (`shadow_merge.rs`): a buffer's bytes that another writer may write beside the commands'
/// writes while a command buffer runs, whose writes to texels the commands left Metal keeps;
@@ -1126,34 +1150,65 @@ pub(super) enum Step<M> {
Merge(M),
}
/// A shadow's copy in over host pages a consumer logs (`dirty_pages.rs`), left by its encoder
/// to its batch's submission (`Deferred::GatedCopyIn`): the commit asks the log for a stamp, and
/// A shadow's copy in left by its encoder to its batch's submission (`Deferred::GatedCopyIn`):
/// over host pages a consumer logs (`dirty_pages.rs`), the commit asks the log for a stamp, and
/// the copy's regions are those the log says changed once that stamp is published, which only a
/// recording after the commit can know. Recorded in a command buffer of its own between the
/// encoder's, behind a barrier from everything before it and before one to everything after it,
/// so it keeps its place among the encoder's commands.
/// recording after the commit can know; a command buffer's first copy in of a shadow that may
/// stand across command buffers (`shadow_standing.rs`) moves nothing where the image stands as
/// the batch is submitted, in the scheduler's order. Recorded in a command buffer of its own
/// between the encoder's, behind a barrier from everything before it and before one to
/// everything after it, so it keeps its place among the encoder's commands.
pub(super) struct GatedCopyIn {
copy: ShadowCopy,
gate: Arc<CopyInGate>,
gate: CopyGate,
}
/// What decides a copy in as its batch is submitted.
pub(super) enum CopyGate {
/// Its regions: those its log says changed (`dirty_pages.rs`).
Log(Arc<CopyInGate>),
/// Whether it moves anything: nothing where the image stands across command buffers
/// (`shadow_standing.rs`).
Standing,
}
impl GatedCopyIn {
/// `copy`, its regions decided by `gate`.
pub(super) fn new(copy: ShadowCopy, gate: Arc<CopyInGate>) -> GatedCopyIn {
/// `copy`, decided by `gate`.
pub(super) fn new(copy: ShadowCopy, gate: CopyGate) -> GatedCopyIn {
GatedCopyIn { copy, gate }
}
/// Record it into `command_buffer`, its regions decided now.
/// The shadow whose standing decides it, where that does.
pub(super) fn standing(&self) -> Option<&Arc<ShadowCopies>> {
matches!(self.gate, CopyGate::Standing).then_some(&self.copy.copies)
}
/// The texels it moves where it moves any.
pub(super) fn texels(&self) -> u64 {
self.copy.texels_copied_in()
}
/// Record it into `command_buffer`, decided now: nothing of a copy its standing decides
/// where the image `stands`.
///
/// # Safety
///
/// `command_buffer` is recording, outside a render pass; the copy's texture is live (its
/// encoder's command buffer holds it), its image in the `GENERAL` layout.
pub(super) unsafe fn record(&self, device: &Vk, command_buffer: vk::CommandBuffer) {
pub(super) unsafe fn record(
&self,
device: &Vk,
command_buffer: vk::CommandBuffer,
stands: bool,
) {
let gate = match &self.gate {
CopyGate::Log(gate) => Some(Arc::clone(gate)),
CopyGate::Standing if stands => return,
CopyGate::Standing => None,
};
// SAFETY: the caller's.
unsafe {
Barrier::everything().record(device, command_buffer);
let gate = Some(Arc::clone(&self.gate));
self.copy.record_gated(device, command_buffer, None, gate);
Barrier::everything().record(device, command_buffer);
}
@@ -1327,6 +1382,15 @@ fn image_copy_texels(region: &vk::ImageCopy) -> u64 {
}
impl ShadowCopy {
/// Whether the copy goes to its batch's submission, there to move nothing where the image
/// stands across command buffers (`shadow_standing.rs`): an encoder's first copy in of a
/// shadow that may stand, moving the truth's texels (no clear, no heap tile moves).
pub(super) fn left_to_standing(&self) -> bool {
let first = matches!(self.cause, Some(CopyCause::First));
let moves = self.clear.is_none() && self.moves.is_none();
matches!(self.step, Step::Into) && first && moves && self.copies.stands_across()
}
/// The log of a copy in of every texel of a tracked 2D texture's image straight from a
/// buffer over host pages a consumer logs (`dirty_pages.rs`), made or kept by `device`, and
/// the bytes of one texel: what may decide the copy's regions as its batch is submitted
@@ -2795,7 +2859,9 @@ pub(super) struct CarryTally {
pub(super) carried_large: u64,
/// The texels an encoder's first copy in of a large plane moved where the image's last
/// standing was an earlier command buffer's: Metal shows a later command buffer a CPU write
/// made since the commit, so it requires this one.
/// made since the commit, so it requires this one where the CPU may write the plane; where
/// only the runtime's commands do, the standing across command buffers may take it off as
/// the batch is submitted (`shadow_standing.rs`).
pub(super) stood_earlier_large: u64,
/// The texels an encoder's first copy in of a large plane moved where the image never held a
/// standing: unavoidable under any rule.
@@ -0,0 +1,178 @@
//! A shadow's standing across command buffers: where only the runtime's commands write a
//! shadowed texture's truth (`ShadowCopies::only_commands_write`: a tracked `Private` buffer's
//! bytes the runtime made, an IOSurface plane's among them), an image that a command buffer's end
//! left holding every texel of the truth still holds it at a later command buffer's first use
//! unless a command written since wrote the truth or the image. That first copy in then moves
//! nothing (`WorkCounts::shadow_copies_in_skipped_by_standing`).
//!
//! - **The order.** Every decision and every write it counts is taken as a batch is submitted,
//! in the scheduler's order over all queues (`command_buffer/submit.rs`), which is the order
//! the tracker orders tracked work in: a write submitted before a copy in that reads what it
//! wrote runs before it, and one submitted after it runs after it. So the copy in reads the
//! truth as every write before it in that order left it, as Metal's does.
//! - **What a command buffer leaves.** Its last batch, where it holds the command buffer's last
//! encoder and nothing failed it, records each shadow its end left holding every texel of the
//! truth, none stale (`ShadowCarry::held_whole`), as standing at what the writes counted so far
//! leave: the batch's own writes counted first, its copies back among them.
//! - **What lets go.** A batch's tracked write of the truth's buffer or of the shadow's image (its
//! key, whatever the range) lets go of the standing: another shadow's copy back over the same
//! bytes, a blit's or a pass's write, a copy in that a command buffer's end did not leave
//! standing. So does any batch of a command buffer whose commands may reach memory no use names
//! (a root table, an execution resolved from records: `State::reaches_unnamed`, or one that
//! noted nothing as it encoded), for every shadow. A shadow over a buffer whose `VkBuffer` was
//! handed out (`Buffer::vk_buffer`), which the caller's own work may write, never stands.
//! - **The copy in.** A command buffer's first copy in of such a shadow, before any command of
//! its encoder wrote what it reads, goes to its batch's submission (`shadow::GatedCopyIn`), and
//! copies nothing there where the shadow stands and no earlier encoder of the command buffer
//! wrote the truth or the image, and the command buffer reaches nothing unnamed. Every other
//! copy is as the module `shadow.rs` states.
use super::buffer::Buffer;
use super::key_hash::KeyMap;
use super::resource::ResourceKey;
use super::shadow::ShadowCopies;
use super::tracker::Summary;
use super::values::StorageMode;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, Weak};
/// The device's count of the writes that let go of its shadows' standings.
#[derive(Default)]
pub(super) struct Standings(Mutex<Watched>);
#[derive(Default)]
struct Watched {
/// The keys a standing was recorded against: how many batches wrote each, and the shadows
/// that stood against it, held weakly.
keys: KeyMap<ResourceKey, Key>,
/// How many batches of command buffers that may reach memory no use names were submitted.
unnamed: u64,
/// `keys`' length when its dead shadows were last let go of.
pruned: usize,
}
#[derive(Default)]
struct Key {
written: u64,
shadows: Vec<Weak<ShadowCopies>>,
}
/// A shadow's standing across command buffers: what the writes counted stood at as a command
/// buffer's end last left its image holding every texel of the truth; and, for a shadow over a
/// buffer of the runtime's own, whether its `VkBuffer` was handed out.
#[derive(Default)]
pub(super) struct Standing {
stood: Mutex<Option<Stood>>,
handed_out: Option<Arc<AtomicBool>>,
}
/// The writes counted against each of a shadow's keys, and the unnamed ones, as it stood.
struct Stood {
written: Vec<(ResourceKey, u64)>,
unnamed: u64,
}
impl Standing {
/// The standing of a shadow over `buffer`'s bytes: one that may stand where the buffer is a
/// `Private` or `Memoryless` buffer the runtime made of its own (not a heap's, nor over the
/// caller's memory), until its `VkBuffer` is handed out; none for any other.
pub(super) fn over(buffer: &Buffer) -> Standing {
let private = matches!(
buffer.resource_options().storage_mode(),
Ok(StorageMode::Private | StorageMode::Memoryless)
);
let own = buffer.caller_memory().is_none() && buffer.heap().is_none();
Standing {
stood: Mutex::new(None),
handed_out: (private && own).then(|| buffer.handed_out()),
}
}
/// Whether the shadow may stand at all: its buffer's `VkBuffer` was never handed out.
pub(super) fn may_stand(&self) -> bool {
(self.handed_out.as_ref()).is_some_and(|out| !out.load(Ordering::Acquire))
}
fn stood(&self) -> MutexGuard<'_, Option<Stood>> {
self.stood.lock().unwrap_or_else(|p| p.into_inner())
}
}
impl Standings {
fn watched(&self) -> MutexGuard<'_, Watched> {
self.0.lock().unwrap_or_else(|p| p.into_inner())
}
/// Whether `copies`' image holds every texel of its truth at a copy in submitted now: it
/// stood, and no write counted since let go of it (the module docs).
pub(super) fn stands(&self, copies: &ShadowCopies) -> bool {
if !copies.stands_across() {
return false;
}
let watched = self.watched();
let stood = copies.standing.stood();
let Some(stood) = stood.as_ref() else {
return false;
};
stood.unnamed == watched.unnamed
&& (stood.written.iter()).all(|(key, written)| {
(watched.keys.get(key)).is_some_and(|known| known.written == *written)
})
}
/// A batch whose encoders' `summaries` these are was submitted: each key its tracked uses
/// write, of those a standing was recorded against, counts one write more, and every one
/// counts where the batch's command buffer may reach memory no use names (`unnamed`). Then
/// each of `held` that may stand stands at what the counts reach: those a command buffer's end
/// left holding every texel of their truth, where this batch ends it (the module docs).
pub(super) fn submitted<'a>(
&self,
summaries: impl Iterator<Item = &'a Summary<ResourceKey>>,
unnamed: bool,
held: &[Arc<ShadowCopies>],
) {
let held: Vec<&Arc<ShadowCopies>> = (held.iter())
.filter(|copies| copies.stands_across())
.collect();
let mut watched = self.watched();
if watched.keys.is_empty() && held.is_empty() {
return;
}
if unnamed {
watched.unnamed += 1;
}
if !watched.keys.is_empty() {
for key in summaries.flat_map(Summary::written_keys) {
if let Some(known) = watched.keys.get_mut(&key) {
known.written += 1;
}
}
}
for copies in held {
let keys = copies.standing_keys();
let mut written = Vec::with_capacity(keys.len());
for key in keys {
let known = watched.keys.entry(key).or_default();
let weak = Arc::downgrade(copies);
if !(known.shadows.iter()).any(|shadow| Weak::ptr_eq(shadow, &weak)) {
known.shadows.retain(|shadow| shadow.strong_count() > 0);
known.shadows.push(weak);
}
written.push((key, known.written));
}
*copies.standing.stood() = Some(Stood {
written,
unnamed: watched.unnamed,
});
}
// The keys of shadows that are gone go once the map doubled since it was last swept, so
// it holds about as many keys as live shadows stood against.
if watched.keys.len() > 2 * watched.pruned.max(32) {
watched.keys.retain(|_, known| {
known.shadows.retain(|shadow| shadow.strong_count() > 0);
!known.shadows.is_empty()
});
watched.pruned = watched.keys.len();
}
}
}
@@ -341,6 +341,8 @@ mod shadow_host_writes;
mod shadow_merge_read;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod shadow_runs;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod shadow_standing_device;
mod shadow_stencil;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod shadow_twins;
@@ -97,6 +97,7 @@ fn shadow_in(
backing: Backing::MappedBuffer,
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
})
}
@@ -1454,6 +1455,7 @@ fn view_of(image: ResourceKey, levels: Range<u32>, layers: Range<u32>) -> Arc<Sh
backing: Backing::Image,
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
})
}
@@ -0,0 +1,256 @@
//! A shadowed texture over a `Private` buffer the device made (an IOSurface plane's, rows padded
//! so that no image holds them on any device) keeps its image's standing across command buffers
//! (`shadow_standing.rs`): a later command buffer's first copy in moves nothing where nothing
//! written since met the truth or the image, and every write that did reaches what the texture
//! reads, and every write through the texture reaches the buffer.
//!
//! Each leg checks both halves: the bytes read are the buffer's as every write left them, and
//! the counts say which copies in moved nothing (`WorkCounts::shadow_copies_in_skipped_by_standing`).
//! A standing that never held leaves the bytes right and the counts wrong; one that held over a
//! write leaves the counts right and the bytes wrong.
//!
//! 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. Blits alone: no function.
use super::blit_holds::{device, Scratch, WAIT};
use crate::{
BlitOption, Buffer, CommandQueue, Device, IoSurfacePlane, Origin, ResourceOptions, Size,
Texture, TextureDescriptor, WorkCounts,
};
use metal2vulkan::metal::{PixelFormat, TextureUsage};
/// The plane: `WIDTH` texels a row, `HEIGHT` rows, rows of `PITCH` bytes, 64 past each row's
/// texels.
const WIDTH: u64 = 64;
const HEIGHT: u64 = 16;
const PITCH: u64 = WIDTH * 4 + 64;
const LENGTH: u64 = PITCH * HEIGHT;
/// The plane's texture over a `Private` buffer, and a `Shared` buffer its reads land in.
struct Plane {
device: Device,
queue: CommandQueue,
buffer: Buffer,
texture: Texture,
read: Buffer,
}
impl Plane {
fn new(device: Device) -> Plane {
let queue = device.new_command_queue().unwrap();
let buffer = (device.new_buffer(LENGTH, ResourceOptions::private())).unwrap();
let mut descriptor =
TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, WIDTH, HEIGHT, false);
descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET;
let plane = IoSurfacePlane::new(0, PITCH, true);
let texture = buffer.new_texture_with_iosurface_plane(&descriptor, plane);
let texture = texture.unwrap();
assert!(texture.shadow().is_some(), "padded rows make a shadow");
let read = (device.new_buffer(LENGTH, ResourceOptions::shared())).unwrap();
let plane = Plane {
device,
queue,
buffer,
texture,
read,
};
plane.fill(0..LENGTH, 0x11, &plane.queue);
plane
}
/// A fill of the buffer's `bytes` with `value` in a command buffer of its own on `queue`.
fn fill(&self, bytes: std::ops::Range<u64>, value: u8, queue: &CommandQueue) {
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.fill_buffer(&self.buffer, bytes, value).unwrap();
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
}
/// The texture's texels as a command buffer of its own reads them, row after row, and the
/// counts it moved.
fn texels(&self) -> (Vec<u8>, Stood) {
let before = self.device.work_counts();
let command_buffer = self.queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
let size = Size::new(WIDTH, HEIGHT, 1);
let at = Origin::new(0, 0, 0);
let row = WIDTH * 4;
let none = BlitOption::None;
(blit.copy_from_texture_to_buffer(
&self.texture,
0,
0,
at,
size,
&self.read,
0,
row,
0,
none,
))
.unwrap();
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
let bytes = self.read_back((WIDTH * 4 * HEIGHT) as usize);
(bytes, stood(&before, &self.device.work_counts()))
}
/// The buffer's own bytes, as a copy into the read buffer moves them.
fn bytes(&self) -> Vec<u8> {
let command_buffer = self.queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
(blit.copy_from_buffer_to_buffer(&self.buffer, 0, &self.read, 0, LENGTH)).unwrap();
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
self.read_back(LENGTH as usize)
}
fn read_back(&self, len: usize) -> Vec<u8> {
let bytes = self.read.contents().unwrap().as_ptr();
// SAFETY: the read buffer's first `len` bytes, which no command writes now.
unsafe { std::slice::from_raw_parts(bytes, len) }.to_vec()
}
/// A write of `value` into every texel through the texture, from a `Shared` buffer.
fn write_through(&self, value: u8) {
let row = WIDTH * 4;
let source = (self
.device
.new_buffer(row * HEIGHT, ResourceOptions::shared()))
.unwrap();
let bytes = source.contents().unwrap().as_ptr();
// SAFETY: the source's bytes, which no command uses yet.
unsafe { std::ptr::write_bytes(bytes, value, (row * HEIGHT) as usize) };
let command_buffer = self.queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
let size = Size::new(WIDTH, HEIGHT, 1);
let at = Origin::new(0, 0, 0);
let none = BlitOption::None;
(blit.copy_from_buffer_to_texture(&source, 0, row, 0, size, &self.texture, 0, 0, at, none))
.unwrap();
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
}
}
/// The standing's counts between two snapshots of a device's.
struct Stood {
against: u64,
skipped: u64,
texels: u64,
}
fn stood(before: &WorkCounts, after: &WorkCounts) -> Stood {
Stood {
against: after.shadow_copies_in_against_standing - before.shadow_copies_in_against_standing,
skipped: after.shadow_copies_in_skipped_by_standing
- before.shadow_copies_in_skipped_by_standing,
texels: after.shadow_texels_skipped_by_standing - before.shadow_texels_skipped_by_standing,
}
}
/// Every texel's bytes `value`.
fn all(bytes: &[u8], value: u8) -> bool {
bytes.iter().all(|&byte| byte == value)
}
/// A second command buffer's read of the texture moves nothing in; a fill of the buffer by
/// another queue's command buffer since lets go of the standing, and the read after it takes the
/// fill; a write through the texture reaches the buffer's bytes, and the read after it holds it.
#[test]
fn a_private_plane_s_image_stands_until_a_command_writes_the_buffer_or_the_texture() {
let scratch = Scratch::new("shadow-standing");
let plane = Plane::new(device(&scratch.0));
let (first, counts) = plane.texels();
assert!(all(&first, 0x11), "the first read takes the buffer's bytes");
assert_eq!(counts.against, 1);
assert_eq!(counts.skipped, 0, "nothing stood yet");
let (second, counts) = plane.texels();
assert!(all(&second, 0x11));
assert_eq!(counts.skipped, 1, "the image stood");
assert_eq!(counts.texels, WIDTH * HEIGHT, "every texel");
// A host's transfer queue fills the buffer: the next read copies in again.
let transfer = plane.device.new_command_queue().unwrap();
plane.fill(PITCH..3 * PITCH, 0x5A, &transfer);
let (filled, counts) = plane.texels();
let row = (WIDTH * 4) as usize;
assert!(
all(&filled[row..3 * row], 0x5A),
"the fill reached the texture"
);
assert!(all(&filled[..row], 0x11) && all(&filled[3 * row..], 0x11));
assert_eq!(counts.skipped, 0, "the fill let go");
let (_, counts) = plane.texels();
assert_eq!(counts.skipped, 1, "and it stood again");
// A write through the texture reaches the buffer, leaving the bytes between rows.
plane.write_through(0xC3);
let bytes = plane.bytes();
for y in 0..HEIGHT as usize {
let at = y * PITCH as usize;
assert!(all(&bytes[at..at + row], 0xC3), "row {y}'s texels");
let gap = if (1..3).contains(&y) { 0x5A } else { 0x11 };
assert!(
all(&bytes[at + row..at + PITCH as usize], gap),
"row {y}'s gap"
);
}
let (written, counts) = plane.texels();
assert!(all(&written, 0xC3), "the read holds the write");
assert_eq!(counts.skipped, 1, "the write's end left the image standing");
}
/// A command buffer that fills the buffer and then reads the texture in a later encoder copies
/// in, the fill included; so does every command buffer once the buffer's `VkBuffer` was handed
/// out, which the caller's own work may write.
#[test]
fn a_private_plane_copies_in_after_its_own_command_buffer_s_write_and_once_handed_out() {
let scratch = Scratch::new("shadow-standing-own");
let plane = Plane::new(device(&scratch.0));
let _ = plane.texels();
let (_, counts) = plane.texels();
assert_eq!(counts.skipped, 1, "the image stood");
let before = plane.device.work_counts();
let command_buffer = plane.queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.fill_buffer(&plane.buffer, 0..PITCH, 0x77).unwrap();
blit.end_encoding().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
let size = Size::new(WIDTH, HEIGHT, 1);
let at = Origin::new(0, 0, 0);
let row = WIDTH * 4;
let none = BlitOption::None;
(blit.copy_from_texture_to_buffer(
&plane.texture,
0,
0,
at,
size,
&plane.read,
0,
row,
0,
none,
))
.unwrap();
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
let counts = stood(&before, &plane.device.work_counts());
let read = plane.read_back((row * HEIGHT) as usize);
assert!(
all(&read[..row as usize], 0x77),
"the read took its own command buffer's fill"
);
assert!(all(&read[row as usize..], 0x11));
assert_eq!(counts.skipped, 0);
// SAFETY: the handle is only read; no work of the caller's uses it.
let _ = unsafe { plane.buffer.vk_buffer() };
let _ = plane.texels();
let (_, counts) = plane.texels();
assert_eq!(counts.against, 0, "handed out, it never stands");
}
@@ -3438,6 +3438,7 @@ impl Device {
backing: Backing::of(bytes, false),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
};
Owner::HeapShadow(Box::new(HeapShadow {
placement,
@@ -3537,6 +3538,7 @@ impl Device {
backing: Backing::of(bytes, false),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
};
Owner::HeapShadow(Box::new(HeapShadow {
placement,
@@ -3613,6 +3615,7 @@ impl Device {
backing: Backing::of(bytes, false),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
};
Owner::HeapShadow(Box::new(HeapShadow {
placement,
@@ -170,6 +170,7 @@ impl Texture {
backing: texels.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
};
let storage = Storage::Shadow {
image: image.shared(),
@@ -239,6 +239,7 @@ impl Device {
backing: texels.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
};
self.degrade(Degradation::ShadowedTexture, || {
let [width, height, _] = layout.extent;
@@ -485,6 +485,7 @@ impl Device {
backing: Backing::Image,
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
};
Owner::ViewShadow(Box::new(ViewShadow {
placement,
@@ -389,6 +389,7 @@ impl Device {
backing: texels.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
};
Ok(Storage::Shadow {
image: image.shared(),
@@ -701,6 +702,7 @@ impl Texture {
backing: texels.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
};
Ok((image, copies))
}
@@ -868,6 +870,7 @@ impl Texture {
backing: texels.backing(),
merge_scratch: ScratchSpares::default(),
stood: AtomicU64::new(0),
standing: Default::default(),
};
let storage = Storage::Shadow {
image: image.shared(),
@@ -2118,6 +2118,18 @@ impl<K: Copy + Ord> Summary<K> {
self.uses.iter().map(|used| used.key)
}
/// The resources the tracked uses write, in order, each once per range written.
pub(super) fn written_keys(&self) -> impl Iterator<Item = K> + '_ {
(self.uses.iter())
.filter(|used| !used.write.is_empty())
.map(|used| used.key)
}
/// Whether a tracked use writes one of `keys`.
pub(super) fn writes_any(&self, keys: &[K]) -> bool {
self.written_keys().any(|key| keys.contains(&key))
}
/// Join `other`, the summary of work recorded apart that runs inside the same encoder (an
/// indirect command buffer's commands, recorded at commit): its stages, fences and tracked
/// uses, one per resource and range. A resource past [`ENTRIES_PER_KEY`] ranges takes a new
+39 -1
View File
@@ -406,6 +406,9 @@ pub(crate) struct Counters {
new_buffer_bytes_cleared: AtomicU64,
new_buffer_zero_fills: AtomicU64,
shadow_copies: AtomicU64,
shadow_copies_in_against_standing: AtomicU64,
shadow_copies_in_skipped_by_standing: AtomicU64,
shadow_texels_skipped_by_standing: AtomicU64,
shadow_texels_copied_in: AtomicU64,
shadow_texels_first_copied_in: AtomicU64,
shadow_texels_first_copied_in_images: AtomicU64,
@@ -2922,6 +2925,17 @@ impl Counters {
.fetch_add(texels_back, Ordering::Relaxed);
}
/// A command buffer's first copy in of a shadow that may stand across command buffers was
/// decided as its batch was submitted (`shadow_standing.rs`): it moved nothing where the
/// image stood (`skipped`), its `texels` with it.
pub(crate) fn shadow_copy_in_against_standing(&self, skipped: bool, texels: u64) {
(self.shadow_copies_in_against_standing).fetch_add(1, Ordering::Relaxed);
if skipped {
(self.shadow_copies_in_skipped_by_standing).fetch_add(1, Ordering::Relaxed);
(self.shadow_texels_skipped_by_standing).fetch_add(texels, Ordering::Relaxed);
}
}
/// An encoder planned `copy`, a copy in of a shadowed texture: its texels
/// (`shadow::ShadowCopy::texels_copied_in`) counted by why it is made
/// (`shadow::ShadowCopy::cause`, a change of the truth by its reason), by what holds the truth
@@ -5781,6 +5795,18 @@ pub struct WorkCounts {
/// texture that merges back (`shadow_merge.rs`). Each is a command of its encoder over the
/// texture's texels.
pub shadow_copies: u64,
/// Of the copies in of `shadow_copies`, command buffers' first ones of a shadow whose truth
/// only the runtime's commands write (a tracked `Private` buffer's bytes the device made, an
/// IOSurface plane's among them), decided as their batches were submitted against the
/// image's standing across command buffers (`shadow_standing.rs`).
pub shadow_copies_in_against_standing: u64,
/// Of those, the ones that moved nothing: the image held every texel of the truth, as an
/// earlier command buffer's end left it, and nothing submitted since wrote the truth or the
/// image.
pub shadow_copies_in_skipped_by_standing: u64,
/// The texels those would have moved; they are among `shadow_texels_copied_in` and its
/// split, which count every copy in as it is planned.
pub shadow_texels_skipped_by_standing: u64,
/// The texels those copies in move from a 2D texture's buffer's bytes to its image (a texture
/// over a buffer, a no-copy buffer or an IOSurface plane): every texel, or those inside the
/// rectangle bounding a pass's draws' scissors over an attachment it loads and takes in no
@@ -5835,7 +5861,10 @@ pub struct WorkCounts {
pub shadow_texels_first_copy_in_carried_large_surfaces: u64,
/// The second: the texels an encoder's first copy in of such a plane moved where the image's
/// last standing was an earlier command buffer's. Metal shows a later command buffer a CPU
/// write made since the commit, so it requires these and no rule removes them.
/// write made since the commit, so it requires these where the CPU may write the plane;
/// where only the runtime's commands write it, those the image's standing across command
/// buffers took off as their batches were submitted are counted here too, and apart in
/// `shadow_texels_skipped_by_standing`.
pub shadow_texels_first_copied_in_large_surfaces_stood_earlier: u64,
/// The third: the texels an encoder's first copy in of such a plane moved where the image
/// never held a standing of any command buffer. Unavoidable under any rule.
@@ -6961,6 +6990,15 @@ impl Device {
own_pixel_reads: counters.own_pixel_reads.load(Ordering::Relaxed),
shadows_zeroed: counters.shadows_zeroed.load(Ordering::Relaxed),
shadow_copies: counters.shadow_copies.load(Ordering::Relaxed),
shadow_copies_in_against_standing: counters
.shadow_copies_in_against_standing
.load(Ordering::Relaxed),
shadow_copies_in_skipped_by_standing: counters
.shadow_copies_in_skipped_by_standing
.load(Ordering::Relaxed),
shadow_texels_skipped_by_standing: counters
.shadow_texels_skipped_by_standing
.load(Ordering::Relaxed),
shadow_texels_copied_in: counters.shadow_texels_copied_in.load(Ordering::Relaxed),
shadow_texels_first_copied_in: counters
.shadow_texels_first_copied_in
@@ -2970,7 +2970,9 @@ field metal2vulkan-runtime::WorkCounts.shadow_attachment_tiles_bounded pub shado
field metal2vulkan-runtime::WorkCounts.shadow_attachment_tiles_covered pub shadow_attachment_tiles_covered: u64
field metal2vulkan-runtime::WorkCounts.shadow_copies pub shadow_copies: u64
field metal2vulkan-runtime::WorkCounts.shadow_copies_back_dispatched pub shadow_copies_back_dispatched: u64
field metal2vulkan-runtime::WorkCounts.shadow_copies_in_against_standing pub shadow_copies_in_against_standing: u64
field metal2vulkan-runtime::WorkCounts.shadow_copies_in_dispatched pub shadow_copies_in_dispatched: u64
field metal2vulkan-runtime::WorkCounts.shadow_copies_in_skipped_by_standing pub shadow_copies_in_skipped_by_standing: u64
field metal2vulkan-runtime::WorkCounts.shadow_keeps pub shadow_keeps: super::churn_counts::ShadowKeeps
field metal2vulkan-runtime::WorkCounts.shadow_keeps_from_staging pub shadow_keeps_from_staging: u64
field metal2vulkan-runtime::WorkCounts.shadow_merge_copies_dispatched pub shadow_merge_copies_dispatched: u64
@@ -3017,6 +3019,7 @@ field metal2vulkan-runtime::WorkCounts.shadow_texels_recopied_in_large_surfaces
field metal2vulkan-runtime::WorkCounts.shadow_texels_recopied_in_mapped_buffers pub shadow_texels_recopied_in_mapped_buffers: u64
field metal2vulkan-runtime::WorkCounts.shadow_texels_recopied_in_private_buffers pub shadow_texels_recopied_in_private_buffers: u64
field metal2vulkan-runtime::WorkCounts.shadow_texels_recopied_in_surfaces pub shadow_texels_recopied_in_surfaces: u64
field metal2vulkan-runtime::WorkCounts.shadow_texels_skipped_by_standing pub shadow_texels_skipped_by_standing: u64
field metal2vulkan-runtime::WorkCounts.shadowed_textures pub shadowed_textures: u64
field metal2vulkan-runtime::WorkCounts.shadows_over_fresh_pages pub shadows_over_fresh_pages: u64
field metal2vulkan-runtime::WorkCounts.shadows_sharing_truth pub shadows_sharing_truth: u64
Can't render this file because it is too large.