Merge a shadow over logged host pages back by its changes: words, or whole blocks where Metal rewrites them

Over host pages whose consumer logs every write, a pass replacing every texel takes the gated
merge, stored in whole 256-byte blocks; a loading, storing pass's attachment merges in whole
blocks of its area's rows; a kernel's and a blit's partial writes stay word by word, and
docs/FAST-PATHS.md says why.

One work packet, landed as 6 commits on archive/development-linear-2026-10-29, in order:

* Merge back a pass replacing every texel of a shadow over logged host pages (3b5b3b9b51)

A command that replaces every texel of a shadowed texture (ShadowUse::overwrites,
a cleared pass among them) took no copy in and no keep, and its copy back wrote
every texel it moved into the buffer's bytes: on a discrete GPU, 6 MB per
host_ab drag frame across PCIe for the 23 cleared 256x256 surfaces, whatever
changed. Over host pages whose consumer logs every write to them
(ShadowCopies::logged), such a command now takes the merge a command that
leaves texels in place takes: its gated copy in (only the rows the log reports
changed since the image's last copy, every row where the log cannot say), the
keep, the command, and the merge, which stores only the words the command
changed against the keep (shadow.rs, overwrites_unkept, and the module's
**Overwrites over logged pages**).

Metal's bytes: the gated copy in is decided once the log published the stamp
the command buffer asked at its commit, so the image and the keep hold the host
bytes as of the commit, every CPU write before it included, and a word the
merge leaves already holds the value the command wrote. A byte another writer
writes after the commit is one the command writes too, a race Metal leaves
unordered. Without a log the image may lag the CPU's writes, so there the copy
back stays a plain copy, as before. No switch: no byte differs from Metal's.

RUNTIME_VERSION development's 1692 + 1 = 1693 (renumbered at landing).

Verified on the M3 Max (MoltenVK), tests::dirty_pages_device:
- a_pass_replacing_a_logged_render_target_merges_back_the_words_it_changed:
  frame 1, 0 texels copied back and 1 merge; frame 2, the gated copy in takes
  the told row alone (256 bytes), the told CPU row the pass clears back to the
  image's old black ends black (Metal's), and a CPU row the log left out, which
  the pass clears to the black the keep held, keeps the CPU's 0x50 bytes: only
  changed words are stored.
- a_pass_replacing_an_unlogged_render_target_copies_it_back: 4096 texels copied
  back plainly and no merge, two frames.
Sabotage 1 (overwrites_unkept ignoring the log): the logged test fails (4096
texels copied back, 0 merges). Sabotage 2 (keep and merge without the copy in):
it fails on Metal's bytes (row 0 [16,16,0,16], want [255,0,0,255]). Restored:
dirty_pages_device, shadow, shadow_host_writes, shadow_merge_read,
shadow_carried_read, render::shadows and degradation tests 57/57 under
--cfg m2v_gpu; clippy plain and --cfg m2v_gpu (runtime) clean; rustdoc
-D warnings for the runtime clean.

* Store an overwriting pass's merge over logged pages in whole 256-byte blocks (d34f373d52)

Over host pages whose consumer logs every write to them, a command that
replaces every texel of a shadow (ShadowUse::overwrites, a cleared pass among
them) is merged back word by word since 3b5b3b9b51: only the words it changed
against the keep are stored. Where those changes are scattered, every warp's
store leaves gaps between words, which an RTX 5080 storing into host memory
over PCIe charges hundreds of times for (bind::shadow_merge's module docs:
590 ms against 0.85 ms per 8 MiB), where the plain copy back it replaced stored
every texel without gaps.

The merge kernels (bind::shadow_merge_module, shadow_merge_image_module and
its kept-image form) take a store form, bind::ShadowMergeStores { Words,
Blocks }. In the block form, the 64 words a workgroup takes in one step are one
256-byte block (ShadowMergeModule::BLOCK_BYTES), marked in workgroup memory
where a word of it changed (clear, barrier, atomic or, barrier); a marked block
is stored whole, a word it left as read, and no other block is read or written.

The form is chosen by structure, with no switch: blocks exactly for the merge
of a command that replaces every texel, cut to the texels' rows (so every word
it examines is texels' bytes, none between rows or past the last texel); every
other merge (partial writes, two ways, a linear attachment's) keeps the words.
That is Metal's answer: the command wrote every byte of every such block, as
the plain copy back stored them all, so a word it left is stored with the value
the merge reads, which differs from the command's only by another writer's
write since the commit, a race with the command's own write. A scratch made for
one kind of command is kept again only for the same kind; a command of the
other kind merges it and takes a new one. WorkCounts gains
shadow_merge_dispatches_in_blocks. RUNTIME_VERSION 1693 + 1 = 1694.

Public API: bind::ShadowMergeStores (new), shadow_merge_module /
shadow_merge_image_module / shadow_merge_kept_image_module take it,
ShadowMergeModule::BLOCK_BYTES, WorkCounts::shadow_merge_dispatches_in_blocks
(api_signatures re-blessed, api_surface lists the enum).

Verified on the M3 Max (MoltenVK):
- tests::dirty_pages_device::a_scattered_overwrite_of_logged_pages_merges_back_in_whole_blocks:
  a 1024x1024 target over 4 MiB of logged pages, the CPU's texels (told to the
  log) grey at every other texel; a pass clearing to black (one pixel drawn
  red) merges 8 of 8 dispatches in whole blocks and leaves the pass's bytes, the
  CPU's grey texels black; a pass loading and drawing black everywhere changes
  the same words and merges in words (0 of 8 in blocks), same bytes. GPU time
  median: blocks 1.318 ms (4 MiB stored), words 1.096 ms (2 MiB stored).
- Sabotage (never choose blocks): that test fails (0 of 8 in blocks).
- Device tests dirty_pages_device, owned_pushes, shadow, shadow_host_writes,
  shadow_merge_read, shadow_carried_read, render::shadows: 42/42.
- Interpreter tests of both forms (ported from the measurement branch): equal
  bytes in both forms and orders, two barriers per invocation in blocks, and a
  current buffer holding only the first block, so any access to an unchanged
  block traps; bind::shadow_merge*, owned_divisions, api_surface,
  api_signatures 26/26.
- clippy workspace plain and runtime --cfg m2v_gpu, rustdoc -D warnings.

* Re-pin the runtime sources at the landing tip (44c96cfdf8)

* Merge a loading, storing pass's attachment back in whole blocks of its area's rows (2fcdb470fe)

A render pass that loads a shadowed color attachment and stores it, changing
it only inside its draws' scissors (ShadowUse::area), merged back to the
buffer's bytes word by word: only the words it changed against the keep. Where
those changes are scattered, a GPU storing into host memory over PCIe pays for
every separate run of words in a 64-byte host line (about 180 ns each on an RTX
5080, serialized: 88 to 102 ms for every other word over 4 MiB, against 0.4 ms
in whole blocks).

Metal itself rewrites such texels. Measured on this M3 Max's Metal (macOS
27.0.1, an ObjC harness, not MoltenVK): a 512x256 RGBA8Unorm texture over a
no-copy Shared buffer, 300 passes each loading and storing it and drawing one
pixel (a long fragment loop, about 2.9 ms of GPU time each), while a CPU thread
wrote a fresh value to every other texel over and over and checked that each
read back its last write. For points at (70,70), (200,130), (10,10) and
(100,33), the other 1023 texels of the 32x32 tile holding the point reverted to
an older value in 157 to 229 of the 300 passes each; no texel of any other
tile reverted, inside the render area (renderTargetWidth 384) or past it. A
kernel writing the same texel reverted none (0 of about 1.1e9 checks). So a CPU
write to a texel such a pass leaves inside its render area, made while it runs,
is not kept on Metal either.

ShadowUse gains tile_stores: a color the pass loads and stores inside its
bounded area (render/shadows.rs), joined like area (a draw's write through the
texture another way clears it, a read keeps it). shadow::stores_blocks takes it
with the overwrites rule, and MergeFor::overwrites becomes MergeFor::blocks
(KeptArea::for_overwrite -> in_blocks, ShadowMerge's flag alike): the merge of
such a pass, when its keep is the pass's area, is cut to that rectangle's rows
and stores whole 256-byte blocks (bind::ShadowMergeStores::Blocks), each
holding a changed word as one store, no other block, nothing outside the rows.
Over any merged-back bytes, logged or not: a block's unchanged words are stored
with the value the merge reads, so only a write between that read and the
store is undone, a shorter window than a tile's load to store. A block can
reach past the tiles the draws reach (64 RGBA8 texels of a row, two 32-texel
tiles), never past the rectangle. Docs: shadow.rs **Stored attachments**,
shadow_merge.rs, bind::shadow_merge, WorkCounts::shadow_merge_dispatches_in_blocks,
API.md (shadowed-texture entry), FAST-PATHS known gap (now the partial writes
of kernels and blits). RUNTIME_VERSION 1695 + 1 = 1696.

Verified on the M3 Max (MoltenVK):
- tests::shadow::a_pass_storing_its_loaded_area_merges_in_whole_blocks (new):
  blocks for a bounded loaded-and-stored pass; words unbounded, without tile
  stores, or joined with a draw's write; a read keeps them. Sabotage (never
  tile stores): FAIL; restored: PASS.
- tests::dirty_pages_device::a_scattered_overwrite_of_logged_pages_merges_back_in_whole_blocks:
  the Load pass drawing every texel now merges 8 of 8 in blocks (the old form
  asserted 0), same bytes; GPU time median 1.078 ms (clear leg 1.860 ms).
- tests::dirty_pages_device::a_pass_storing_its_loaded_area_keeps_a_cpu_write_beside_it
  (new): a Load pass drawing a 64x64 square over 4 MiB of logged pages while a
  CPU thread writes three texels beside it (the next block of its rows, far
  right, below) from before the commit to after the completion: 8 of 8 in
  blocks, 12.4 million CPU writes, each texel ending with the CPU's last write,
  every other byte Metal's.
- Device tests dirty_pages_device, shadow*, owned_pushes, render::shadows: 45/45.

RUNTIME_VERSION 1696 -> 1697 (renumbered at landing). Metal's own tile stores measured on the Apple M3 Max with an ObjC harness: 300 Load+Store passes drawing one point while a CPU thread rewrote every other texel; the 1023 other texels of the drawn 32x32 tile reverted in 157-229 of 300 passes, no texel in any other tile did, and a compute kernel writing the same texel reverted none in ~1.1e9 checks. A 256-byte block can reach the neighbouring tile within the scissor rectangle (64 RGBA8 texels), never beyond the rectangle: documented in shadow.rs's "Stored attachments".

* Re-pin the runtime sources at the landing tip (3da7eb9189)

* Say why a kernel's and a blit's partial writes merge back word by word, never in blocks (2e2e238346)

The owner decided (10-29) to keep whole-block merges out of kernels' and
blits' partial writes. Blocks rewrite the unchanged bytes inside each
256-byte block with the value the merge read, undoing a CPU write made
meanwhile. Metal keeps such a write beside a kernel's write: on the M3 Max
(macOS 27.0.1, an ObjC harness over a no-copy Shared buffer), a kernel
writing one texel lost none of a CPU thread's writes to the texels around
it in about 1.1e9 checks. A pass that loads and stores its attachment
rewrites the whole 32x32 tile it draws in (157 to 229 of 300 passes), which
is why only those passes, and commands that write every texel, take blocks.
Blits weren't measured; they keep the kernel's rule.

FAST-PATHS' known gap for the word-by-word merge now says so. Docs only: no
runtime source changes, so the runtime-sources pin doesn't move.
This commit is contained in:
Anees Iqbal committed 2026-10-29 15:43:51 +02:00
1 parent 3ec4a69763
commit df2bbfc3ab
22 files changed
+1272 -155

No files matched your search

+2
View File
@@ -290,6 +290,8 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
the writes to a no-copy object's pages, by which every copy of them into memory of the device's
own (a shadow of a texture over them) copies in only the pages changed since its last copy, on
every device. The runtime's own writes into the pages are reported back, naming their writer.
A command that replaces every texel of such a shadow is merged back, as one that leaves some is:
copied in (the changed pages), kept, and only the words it changed written into the pages.
- `HostMemory::with_import_gate` and its `ImportGate` (with `ImportRequest`): the consumer's
gate over a no-copy buffer's, heap's or rebind's import of its pages; a refusal makes a copy of
them.
+3 -2
View File
@@ -1403,8 +1403,9 @@ impl EncoderCore {
let leases = &mut self.kept_leases;
let planned = self
.shadows
.before(shadows, uses, |copies, two_ways, area| {
let (merge, lease) = ShadowMerge::new(&device, copies, (two_ways, area), images)?;
.before(shadows, uses, |copies, made_for, area| {
let merging = (made_for.two_ways, made_for.blocks, area);
let (merge, lease) = ShadowMerge::new(&device, copies, merging, images)?;
leases.extend(lease);
Ok(Arc::new(merge))
});
@@ -60,7 +60,7 @@ use super::tracker::{Access, Barrier, Use};
use super::Device;
use crate::device::functions::Vk;
use ash::vk;
use metal2vulkan::bind::ShadowMergeModule;
use metal2vulkan::bind::{ShadowMergeModule, ShadowMergeStores};
/// What the offsets of the bindings are rounded to: a multiple of every
/// `minStorageBufferOffsetAlignment`.
@@ -231,7 +231,7 @@ impl LinearMerge {
}
}
(device.shared().counts).shadow_merge_planned(dispatches.len(), examined);
let kernel = device.owned_kernel(OwnedModule::ShadowMerge)?;
let kernel = device.owned_kernel(OwnedModule::ShadowMerge(ShadowMergeStores::Words))?;
let binds = OwnedBinds::new(device, &kernel, &sets)?;
let levels = backing.level..backing.level + 1;
let backing_layers = backing.layer..backing.layer + backing.layers.max(1);
+43 -32
View File
@@ -36,8 +36,8 @@ use crate::device::functions::Vk;
use crate::shader_cache::driver::Making;
use ash::vk;
use metal2vulkan::bind::{
MipmapFilterKernel, RewritePhase, RewriteProgram, ShadowMergeRead, ShadowTexelView,
TessellationScanKernel, YCbCrCodes, YCbCrConversion,
MipmapFilterKernel, RewritePhase, RewriteProgram, ShadowMergeRead, ShadowMergeStores,
ShadowTexelView, TessellationScanKernel, YCbCrCodes, YCbCrConversion,
};
use metal2vulkan::metal::format::ExtendedRange;
use std::collections::HashMap;
@@ -81,9 +81,10 @@ pub(super) enum OwnedModule {
/// flat variant, from Metal's arguments (`indirect_dispatch.rs`). No descriptor: it reaches
/// memory by device address.
FlatDispatch,
/// `bind::shadow_merge_module`: a shadowed texture's writes merged into its buffer's bytes
/// after a command that also wrote them another way (`shadow_merge.rs`).
ShadowMerge,
/// `bind::shadow_merge_module` storing in one form (`ShadowMergeStores`): a shadowed
/// texture's writes merged into its buffer's bytes (`shadow_merge.rs`), or a linear
/// attachment's pass into its surface's (`linear_merge.rs`).
ShadowMerge(ShadowMergeStores),
/// `bind::shadow_copy_back_module` of one view of a texel (`ShadowTexelView`): a shadowed
/// texture's texels stored back into its buffer's rows by a dispatch, where the device copies
/// back faster so (`shadow_copy_back.rs`). Its shadow's unsigned-integer view is its sampled
@@ -96,11 +97,11 @@ pub(super) enum OwnedModule {
/// texture's writes merged into its buffer's bytes, reading its shadow's texels through its
/// unsigned-integer view or its own 8-bit unsigned normalized view, its sampled image
/// (`shadow_merge.rs`).
ShadowMergeImage(ShadowMergeRead),
ShadowMergeImage(ShadowMergeRead, ShadowMergeStores),
/// `bind::shadow_merge_kept_image_module` of one view of a texel (`ShadowTexelView`): as
/// [`OwnedModule::ShadowMergeImage`], the texels before the commands read from an image copy
/// of the shadow, its second sampled image (`shadow_merge.rs`).
ShadowMergeKeptImage(ShadowTexelView),
ShadowMergeKeptImage(ShadowTexelView, ShadowMergeStores),
/// `bind::shadow_copy_in_module` of one view of a texel (`ShadowTexelView`): a merged
/// shadowed texture's texels copied in from its buffer's rows and kept in its merge's scratch
/// by one dispatch (`shadow_copy_in.rs`). Its shadow's unsigned-integer view is its storage
@@ -195,8 +196,8 @@ impl OwnedModule {
fn images(self) -> u32 {
match self {
OwnedModule::MipmapFilter(kernel) => u32::from(kernel.fetches()),
OwnedModule::ShadowCopyBack(_) | OwnedModule::ShadowMergeImage(_) => 1,
OwnedModule::ShadowMergeKeptImage(_) => 2,
OwnedModule::ShadowCopyBack(_) | OwnedModule::ShadowMergeImage(..) => 1,
OwnedModule::ShadowMergeKeptImage(..) => 2,
// The combined image sampler of the planes' (or pairs') image.
OwnedModule::YCbCrSample(..) | OwnedModule::ChromaSample(_) => 1,
_ => 0,
@@ -213,9 +214,9 @@ impl OwnedModule {
OwnedModule::RowsCopy
| OwnedModule::ShadowCopyBack(_)
| OwnedModule::ShadowCopyIn(_)
| OwnedModule::ShadowMerge
| OwnedModule::ShadowMergeImage(_)
| OwnedModule::ShadowMergeKeptImage(_)
| OwnedModule::ShadowMerge(_)
| OwnedModule::ShadowMergeImage(..)
| OwnedModule::ShadowMergeKeptImage(..)
) && device.shared().vk().push_descriptor().is_some()
}
@@ -310,9 +311,10 @@ impl OwnedModule {
let push_bytes = metal2vulkan::bind::FlatDispatchModule::PUSH_BYTES;
Ok((module.spirv.to_vec(), 0, push_bytes))
}
OwnedModule::ShadowMerge => {
let module = metal2vulkan::bind::shadow_merge_module(device.compile_device())
.map_err(Error::Compile)?;
OwnedModule::ShadowMerge(stores) => {
let module =
metal2vulkan::bind::shadow_merge_module(device.compile_device(), stores)
.map_err(Error::Compile)?;
let push_bytes = metal2vulkan::bind::ShadowMergeModule::PUSH_BYTES;
Ok((module.spirv.to_vec(), 3, push_bytes))
}
@@ -329,17 +331,21 @@ impl OwnedModule {
let push_bytes = metal2vulkan::bind::RowsCopyModule::PUSH_BYTES;
Ok((module.spirv.to_vec(), 2, push_bytes))
}
OwnedModule::ShadowMergeImage(read) => {
let module =
metal2vulkan::bind::shadow_merge_image_module(device.compile_device(), read)
.map_err(Error::Compile)?;
OwnedModule::ShadowMergeImage(read, stores) => {
let module = metal2vulkan::bind::shadow_merge_image_module(
device.compile_device(),
read,
stores,
)
.map_err(Error::Compile)?;
let push_bytes = metal2vulkan::bind::ShadowMergeImageModule::PUSH_BYTES;
Ok((module.spirv.to_vec(), 2, push_bytes))
}
OwnedModule::ShadowMergeKeptImage(view) => {
OwnedModule::ShadowMergeKeptImage(view, stores) => {
let module = metal2vulkan::bind::shadow_merge_kept_image_module(
device.compile_device(),
view,
stores,
)
.map_err(Error::Compile)?;
let push_bytes = metal2vulkan::bind::ShadowMergeImageModule::PUSH_BYTES;
@@ -535,9 +541,10 @@ pub(super) struct OwnedKernels {
draw_merge_starts: Option<OwnedKernel>,
flat_dispatch: Option<OwnedKernel>,
shadow_merge: Option<OwnedKernel>,
shadow_merge_blocks: Option<OwnedKernel>,
shadow_copy_backs: HashMap<ShadowTexelView, OwnedKernel>,
shadow_merge_images: HashMap<ShadowMergeRead, OwnedKernel>,
shadow_merge_kept_images: HashMap<ShadowTexelView, OwnedKernel>,
shadow_merge_images: HashMap<(ShadowMergeRead, ShadowMergeStores), OwnedKernel>,
shadow_merge_kept_images: HashMap<(ShadowTexelView, ShadowMergeStores), OwnedKernel>,
shadow_copy_ins: HashMap<ShadowTexelView, OwnedKernel>,
mipmap_filters: HashMap<MipmapFilterKernel, OwnedKernel>,
mesh_scan: Option<OwnedKernel>,
@@ -587,6 +594,7 @@ impl OwnedKernels {
self.draw_merge_starts,
self.flat_dispatch,
self.shadow_merge,
self.shadow_merge_blocks,
self.mesh_scan,
self.mesh_object_arguments,
self.mesh_arguments_mesh,
@@ -649,9 +657,11 @@ impl OwnedKernels {
fn get(&mut self, which: OwnedModule) -> Option<OwnedKernel> {
match which {
OwnedModule::ShadowCopyBack(view) => self.shadow_copy_backs.get(&view).copied(),
OwnedModule::ShadowMergeImage(read) => self.shadow_merge_images.get(&read).copied(),
OwnedModule::ShadowMergeKeptImage(view) => {
self.shadow_merge_kept_images.get(&view).copied()
OwnedModule::ShadowMergeImage(read, stores) => {
self.shadow_merge_images.get(&(read, stores)).copied()
}
OwnedModule::ShadowMergeKeptImage(view, stores) => {
self.shadow_merge_kept_images.get(&(view, stores)).copied()
}
OwnedModule::ShadowCopyIn(view) => self.shadow_copy_ins.get(&view).copied(),
OwnedModule::MipmapFilter(kernel) => self.mipmap_filters.get(&kernel).copied(),
@@ -679,11 +689,11 @@ impl OwnedKernels {
OwnedModule::ShadowCopyBack(view) => {
self.shadow_copy_backs.insert(view, kernel);
}
OwnedModule::ShadowMergeImage(read) => {
self.shadow_merge_images.insert(read, kernel);
OwnedModule::ShadowMergeImage(read, stores) => {
self.shadow_merge_images.insert((read, stores), kernel);
}
OwnedModule::ShadowMergeKeptImage(view) => {
self.shadow_merge_kept_images.insert(view, kernel);
OwnedModule::ShadowMergeKeptImage(view, stores) => {
self.shadow_merge_kept_images.insert((view, stores), kernel);
}
OwnedModule::ShadowCopyIn(view) => {
self.shadow_copy_ins.insert(view, kernel);
@@ -746,10 +756,11 @@ impl OwnedKernels {
&mut self.draw_merge_starts
}
OwnedModule::FlatDispatch => &mut self.flat_dispatch,
OwnedModule::ShadowMerge => &mut self.shadow_merge,
OwnedModule::ShadowMerge(ShadowMergeStores::Words) => &mut self.shadow_merge,
OwnedModule::ShadowMerge(ShadowMergeStores::Blocks) => &mut self.shadow_merge_blocks,
OwnedModule::ShadowCopyBack(_)
| OwnedModule::ShadowMergeImage(_)
| OwnedModule::ShadowMergeKeptImage(_)
| OwnedModule::ShadowMergeImage(..)
| OwnedModule::ShadowMergeKeptImage(..)
| OwnedModule::ShadowCopyIn(_)
| OwnedModule::MipmapFilter(_)
| OwnedModule::IndexRewrite(..)
@@ -726,6 +726,7 @@ impl RenderLowering {
kept: false,
area: None,
loads: None,
tile_stores: false,
};
shadow::join(&mut shadows, &used);
}
@@ -491,6 +491,7 @@ fn attachment_shadows(
kept: false,
area: None,
loads: None,
tile_stores: false,
};
shadow::join(&mut shadows, &used);
}
@@ -509,6 +510,7 @@ fn attachment_shadows(
kept: false,
area: None,
loads: None,
tile_stores: false,
};
shadow::join(&mut shadows, &used);
}
@@ -538,6 +540,9 @@ fn attachment_shadows(
kept: !reached,
area: area.map(|area| instance.unwrap_or(area)),
loads: area,
// A color it loads and stores inside its draws' scissors: Metal's store
// writes back each tile its draws reach whole (`shadow.rs`).
tile_stores: stores && area.is_some(),
};
shadow::join(&mut shadows, &used);
}
@@ -556,6 +561,7 @@ fn attachment_shadows(
kept: false,
area: None,
loads: None,
tile_stores: false,
};
shadow::join(&mut shadows, &used);
}
+120 -10
View File
@@ -67,6 +67,48 @@
//! wrote; that copy back goes before the keep of a later command that writes through the
//! texture, since the merge after the keep takes only the words changed since it. The keeps'
//! scratch is the encoder's, one per texture and rectangle.
//! - **Overwrites over logged pages** ([`ShadowCopies::logged`]: host pages whose consumer logs
//! every write to them, `dirty_pages.rs`). A command that replaces every texel of such a shadow
//! takes the merge instead of the plain copy back: its copy in (which moves only the rows the
//! log reports changed since the image's last copy, and every row where the log cannot say),
//! the keep, the command, and the merge, which stores only the words the command changed
//! against the keep. The bytes are Metal's: the copy in is a gated one, decided once the log
//! published the stamp the command buffer asked at its commit (`DirtyPages::wait`), so the image
//! and then the keep hold the host bytes as of the commit, every write before it (the CPU's
//! among them) included, and a word the merge leaves already holds the value the command wrote
//! there. A byte another writer writes after the commit is one the command also writes, a race
//! Metal leaves unordered. Over host pages with no log the image may lag the CPU's writes, and a
//! word the command writes with the image's stale value would keep the CPU's: there the copy
//! back stays a plain copy of every texel the command wrote.
//! Where the merge is cut to the texels' rows (its words are texels' bytes alone, none of the
//! bytes between rows or past the last texel), it stores whole 256-byte blocks
//! (`bind::ShadowMergeStores::Blocks`, `WorkCounts::shadow_merge_dispatches_in_blocks`): each
//! block holding a changed word as one store without gaps, a block with none not at all. That
//! too is Metal's: the command wrote every byte of every such block, as the plain copy back
//! wrote them all, so a word it left as the keep held it is stored as the merge reads it, the
//! same value but for another writer's write since the commit, which races the command's own.
//! The scratch of such a merge is kept again only for another command whose merge stores whole
//! blocks; one whose merge does not takes a merge of the words alone, after the blocks' merge.
//! - **Stored attachments** ([`ShadowUse::tile_stores`]). A render pass that loads a color
//! attachment and stores it, and changes it only inside its draws' scissors
//! (`render/shadows.rs`: the rectangle [`ShadowUse::area`], inside the render area), merges
//! back in whole 256-byte blocks of the rectangle's rows too, over any merged-back bytes, logged
//! or not: each block holding a changed word as one store, a block with none not at all, and no
//! word outside the rectangle's rows (each widened to whole words). Metal's own store of such a
//! pass writes back every texel of each tile its draws reach, those no fragment changed among
//! them: on an M3 Max under macOS 27.0.1, a pass loading and storing a linear `RGBA8Unorm`
//! texture over a no-copy buffer and drawing one pixel rewrote the other 1023 texels of the
//! 32x32 tile holding the pixel with the values it loaded, so a CPU thread writing every texel
//! over and over through the passes lost its writes to each of them in 157 to 229 of 300 passes,
//! and to no texel of any other tile, inside the render area or past it; a kernel writing the
//! same pixel lost none of them. So a CPU write to a texel such a pass leaves inside its render
//! area, made while the pass runs, is no write Metal keeps, and a block stored with the value
//! the merge reads there is as Metal's answer. A block can reach past the tiles the draws reach
//! (a 256-byte block of a row holds 64 such texels, two of those tiles), never past the
//! rectangle; and the merge undoes only a write made between its read of the block and its
//! store, a shorter window than a tile's from its load to its store. A use joined with another
//! that writes through the texture otherwise (a draw's write to it as a bound texture) stores
//! the words alone.
//! - **Ordering.** A copy is a command of the encoder with uses of both the buffer's bytes and the
//! image, so the tracker orders it against the encoder's other commands and other encoders'
//! like any use: the texture and its buffer are one resource to it. In an encoder whose
@@ -2063,7 +2105,8 @@ impl Covered {
/// Mark the shadows of `shadows` a command with `uses` replaces ([`ShadowUse::overwrites`]): it
/// writes through the shadow, reads none of its texels, and writes every texel it holds inside
/// the boxes `covered` ([`ShadowCopies::covered_by`]), so it takes no copy in and no keep, and
/// its copy back moves the texels it wrote.
/// its copy back moves the texels it wrote; but over logged host pages, a copy in, a keep and a
/// merge ([`overwrites_unkept`]).
pub(super) fn overwritten(
shadows: &mut [ShadowUse],
uses: &[Use<ResourceKey>],
@@ -2083,7 +2126,24 @@ pub(super) fn overwritten(
/// ([`ShadowCopies::merges_back`]): kept and merged back (the module's rules), as a command that
/// writes them two ways too ([`two_ways`]) is.
fn merged_back(shadow: &ShadowUse) -> bool {
shadow.writes && !shadow.overwrites && shadow.copies.merges_back()
shadow.writes && !overwrites_unkept(shadow) && shadow.copies.merges_back()
}
/// Whether the merge after a command that writes through `shadow` and merges back, keeping the
/// texels inside `kept` (`None` every texel), stores whole blocks where it is cut to the texels'
/// rows (`shadow_merge.rs`): the command replaces every texel ([`ShadowUse::overwrites`], over
/// logged pages, as [`merged_back`] takes it), or writes through it only by a render pass's
/// stores of the tiles of its area ([`ShadowUse::tile_stores`]) and the keep is that area.
fn stores_blocks(shadow: &ShadowUse, kept: Option<[u32; 4]>) -> bool {
shadow.overwrites || (shadow.tile_stores && kept.is_some() && kept == shadow.area)
}
/// Whether a command that replaces every texel of `shadow` ([`ShadowUse::overwrites`]) takes no
/// copy in and no keep, its copy back a plain copy of the texels it wrote: every such shadow but
/// one over logged host pages ([`ShadowCopies::logged`]), which is copied in, kept and merged back
/// as a command that leaves texels in place is (the module's **Overwrites over logged pages**).
fn overwrites_unkept(shadow: &ShadowUse) -> bool {
shadow.overwrites && !shadow.copies.logged()
}
/// Whether a command that uses the shadowed textures `shadows` and has `uses` writes the bytes
@@ -2149,15 +2209,17 @@ pub(super) fn copies_used<'a>(
kept: false,
area: None,
loads: None,
tile_stores: false,
});
}
shadows
}
/// Add `shadow` to `shadows`: once per shadowed texture, writing through it when either use
/// writes (where both write, inside the rectangle bounding both areas), reading its texels inside
/// the rectangle bounding where both read them (anywhere where either does not bound that), and
/// overwriting it, or leaving its texels in place, only when both do.
/// writes (where both write, inside the rectangle bounding both areas, and by tile stores alone
/// only where both do), reading its texels inside the rectangle bounding where both read them
/// (anywhere where either does not bound that), and overwriting it, or leaving its texels in
/// place, only when both do.
pub(super) fn join(shadows: &mut Vec<ShadowUse>, shadow: &ShadowUse) {
match shadows
.iter_mut()
@@ -2169,6 +2231,11 @@ pub(super) fn join(shadows: &mut Vec<ShadowUse>, shadow: &ShadowUse) {
(false, true) => shadow.area,
(_, false) => other.area,
};
other.tile_stores = match (other.writes, shadow.writes) {
(true, true) => other.tile_stores && shadow.tile_stores,
(false, true) => shadow.tile_stores,
(_, false) => other.tile_stores,
};
other.loads = bounding(other.loads, shadow.loads);
other.writes |= shadow.writes;
other.overwrites &= shadow.overwrites;
@@ -2181,6 +2248,7 @@ pub(super) fn join(shadows: &mut Vec<ShadowUse>, shadow: &ShadowUse) {
kept: shadow.kept,
area: shadow.area,
loads: shadow.loads,
tile_stores: shadow.tile_stores,
}),
}
}
@@ -2322,6 +2390,12 @@ pub(super) struct ShadowUse {
/// its draws' scissors and read the attachment at their own pixel alone,
/// `render/shadows.rs`); `None` for anywhere. Its copy in moves only those texels.
pub(super) loads: Option<[u32; 4]>,
/// The command writes through the texture only as a render pass's color attachment it loads
/// and stores inside `area` (`render/shadows.rs`): Metal's own store of such a pass writes
/// back every texel of each tile its draws reach, those no fragment changed among them, so
/// its merge stores whole blocks of the rectangle's rows (the module's **Stored
/// attachments**).
pub(super) tile_stores: bool,
}
/// The rectangle bounding `a` and `b`, each `[x0, y0, x1, y1)`; `None` (anywhere) where either is.
@@ -2582,12 +2656,34 @@ impl ShadowCarry {
/// for every texel.
pub(super) trait KeptArea {
fn kept_area(&self) -> Option<[u32; 4]>;
/// Whether the scratch was made for a command whose merge stores whole blocks where it can
/// ([`stores_blocks`], `shadow_merge.rs`): only such a command's keep takes it again.
fn in_blocks(&self) -> bool {
false
}
}
impl KeptArea for Arc<ShadowMerge> {
fn kept_area(&self) -> Option<[u32; 4]> {
self.area()
}
fn in_blocks(&self) -> bool {
ShadowMerge::in_blocks(self)
}
}
/// What a merge `ShadowSync::before` asks for is made for.
#[derive(Clone, Copy, Debug)]
pub(super) struct MergeFor {
/// A command that writes the bytes two ways ([`two_ways`]).
pub(super) two_ways: bool,
/// A command whose merge stores whole blocks where it is cut to the texels' rows
/// ([`stores_blocks`]): one that replaces every texel over logged pages
/// ([`overwrites_unkept`]), or a render pass that writes through the texture only by its
/// stores of the area's tiles ([`ShadowUse::tile_stores`]).
pub(super) blocks: bool,
}
impl<M: Clone + KeptArea> ShadowSync<M> {
@@ -2703,7 +2799,7 @@ impl<M: Clone + KeptArea> ShadowSync<M> {
&mut self,
shadows: &[ShadowUse],
uses: &[Use<ResourceKey>],
mut merge: impl FnMut(&ShadowCopies, bool, Option<[u32; 4]>) -> Result<M, Error>,
mut merge: impl FnMut(&ShadowCopies, MergeFor, Option<[u32; 4]>) -> Result<M, Error>,
) -> Result<Vec<ShadowCopy<M>>, Error> {
// A copy back of an image's shadow would replace the other alias's writes, and only a
// buffer's bytes laid out as the texture's are merged: such a command is refused before
@@ -2722,9 +2818,13 @@ impl<M: Clone + KeptArea> ShadowSync<M> {
let mut scratches = Vec::new();
for (i, shadow) in shadows.iter().enumerate() {
if two_ways(shadows, i, uses) {
let made_for = MergeFor {
two_ways: true,
blocks: false,
};
kept.push((
Arc::clone(&shadow.copies),
merge(&shadow.copies, true, None)?,
merge(&shadow.copies, made_for, None)?,
));
} else if merged_back(shadow) {
merged_kept.push(Arc::clone(&shadow.copies));
@@ -2735,14 +2835,24 @@ impl<M: Clone + KeptArea> ShadowSync<M> {
.iter()
.find(|e| e.copies.shadow_key == shadow.copies.shadow_key)
.and_then(|e| e.scratch.as_ref());
// A scratch made for a command of the other kind (one whose merge stores whole
// blocks, or one whose does not) is merged and kept again in a new one: only such
// a command's merge stores whole blocks (`shadow_merge.rs`).
let same = |scratch: &M| scratch.in_blocks() == stores_blocks(shadow, writes);
let area = match scratch {
Some(scratch) if holds(scratch.kept_area(), writes) => continue,
Some(scratch) if holds(scratch.kept_area(), writes) && same(scratch) => {
continue
}
Some(scratch) => bounding(scratch.kept_area(), writes),
None => writes,
};
let made_for = MergeFor {
two_ways: false,
blocks: stores_blocks(shadow, area),
};
scratches.push((
Arc::clone(&shadow.copies),
merge(&shadow.copies, false, area)?,
merge(&shadow.copies, made_for, area)?,
));
}
}
@@ -2789,7 +2899,7 @@ impl<M: Clone + KeptArea> ShadowSync<M> {
let two_ways = kept
.iter()
.any(|(copies, _)| copies.shadow_key == shadow.copies.shadow_key);
let overwrites = shadow.overwrites && !two_ways;
let overwrites = overwrites_unkept(shadow) && !two_ways;
// The texels the command needs as the buffer holds them: those it reads, and those
// it writes (which a copy back moves), where it bounds both and the copies are cut to
// a rectangle; every texel where it writes through a shadow whose copies back move
@@ -94,7 +94,18 @@
//! texel its kernel reads. Any other merge's scratch is new and all zero, so the bytes between
//! the texture's rows, which no copy of the shadow writes, are the same in the kept and changed
//! parts (`WorkCounts::shadow_merge_scratches_zeroed`).
//! - **The kernel** (`bind::shadow_merge_module`, one per device, `owned_kernel.rs`): four
//! - **Whole blocks** for a command that replaces every texel of a shadow over logged host pages
//! (`shadow.rs`, **Overwrites over logged pages**), and for a render pass that loads and stores
//! its color attachment inside its draws' scissors (`shadow.rs`, **Stored attachments**), cut to
//! the texels' rows: the kernel's `bind::ShadowMergeStores::Blocks` form stores each 256-byte
//! block of the rows that holds a changed word whole, without gaps, and no other block
//! (`bind::shadow_merge_module`'s module docs; a GPU storing into host memory over PCIe pays
//! hundreds of times for gaps between a subgroup's words). Every word of those rows is bytes the
//! command wrote, or bytes Metal's own store of the pass writes back, so a word it left is
//! stored with the value the merge reads, Metal's answer. Every other merge stores the changed
//! words alone (`ShadowMergeStores::Words`): its rows may hold bytes no command wrote, which
//! another writer may write meanwhile (`WorkCounts::shadow_merge_dispatches_in_blocks`).
//! - **The kernel** (`bind::shadow_merge_module`, one per device and form, `owned_kernel.rs`): four
//! 4-byte words an invocation, each a workgroup's invocations apart from the next, so one
//! store's words are consecutive across the invocations that run together (its module docs,
//! which name the device that charges hundreds of times for the gaps otherwise), the parts
@@ -135,7 +146,7 @@ use super::Device;
use crate::device::functions::Vk;
use ash::vk;
use metal2vulkan::bind::{
ShadowMergeImageModule, ShadowMergeModule, ShadowMergeRead, ShadowTexelView,
ShadowMergeImageModule, ShadowMergeModule, ShadowMergeRead, ShadowMergeStores, ShadowTexelView,
};
use metal2vulkan::vk::{Format, FormatFeatureFlags2, ImageUsageFlags};
use std::ops::Range;
@@ -278,6 +289,11 @@ pub(super) struct ShadowMerge {
/// The buffers the parts lie in, or the kept image, held until the command buffer completes.
held: Held,
kernel: OwnedKernel,
/// Whether it is made for a command whose merge stores whole blocks (`MergeFor::blocks`: one
/// that replaces every texel, or a render pass that stores the tiles of its area): its kernel
/// stores whole blocks where it is cut to the texels' rows (the module docs), so another
/// command's keep takes a merge of its own.
blocks: bool,
/// One set 0 per window, each binding the window of the parts (and the shadow's view, where
/// the merge fetches, and the kept image's, where it keeps in one) and of the current bytes:
/// pushed where the device pushes (`OwnedBinds`).
@@ -297,7 +313,7 @@ impl ShadowMerge {
pub(super) fn new(
device: &Device,
copies: &ShadowCopies,
(two_ways, area): (bool, Option<[u32; 4]>),
(two_ways, blocks, area): (bool, bool, Option<[u32; 4]>),
images: &KeptImages,
) -> Result<(ShadowMerge, Option<KeptLease>), Error> {
let (
@@ -619,15 +635,25 @@ impl ShadowMerge {
start += size;
}
}
// Whole blocks where every word the dispatches examine is bytes the command wrote or
// Metal's own store rewrites: a command's that replaces every texel, or a render pass's
// that stores the tiles of its area, cut to the texels' rows (the module docs).
let stores = match blocks && !two_ways && cut.is_some() {
true => ShadowMergeStores::Blocks,
false => ShadowMergeStores::Words,
};
counts.shadow_merge_planned(dispatches.len(), examined);
if stores == ShadowMergeStores::Blocks {
counts.shadow_merge_in_blocks(dispatches.len());
}
let kernel = match (fetched, kept_in) {
(Some(_), KeptIn::Image { texel, .. }) => {
device.owned_kernel(OwnedModule::ShadowMergeKeptImage(texel))?
device.owned_kernel(OwnedModule::ShadowMergeKeptImage(texel, stores))?
}
(Some((_, read)), KeptIn::Part(_)) => {
device.owned_kernel(OwnedModule::ShadowMergeImage(read))?
device.owned_kernel(OwnedModule::ShadowMergeImage(read, stores))?
}
(None, _) => device.owned_kernel(OwnedModule::ShadowMerge)?,
(None, _) => device.owned_kernel(OwnedModule::ShadowMerge(stores))?,
};
let binds = OwnedBinds::new(device, &kernel, &sets)?;
let cut = cut.map(|(cut, ..)| cut);
@@ -674,6 +700,7 @@ impl ShadowMerge {
keep_dispatch,
held,
kernel,
blocks,
binds,
dispatches,
};
@@ -777,6 +804,11 @@ impl ShadowMerge {
.map(|cut| cut.area)
}
/// Whether it was made for a command whose merge stores whole blocks (`MergeFor::blocks`).
pub(super) fn in_blocks(&self) -> bool {
self.blocks
}
/// Whether the keep, the changed copy and the merge are cut to a rectangle.
pub(super) fn cuts(&self) -> bool {
self.cut.is_some()
@@ -21,6 +21,28 @@
//! shadow's own write, `wrote_as`, at the commit and again at the completion); frame 6 then
//! copies nothing in for it (`changed_except` leaves the shadow's own write out).
//!
//! A pass that clears such a render target and draws inside rows 0 to 8 replaces every texel
//! (`ShadowUse::overwrites`): over logged pages it takes the merge, not a plain copy back
//! (`shadow.rs`, **Overwrites over logged pages**). A row the CPU wrote since and told the log,
//! which the pass clears to the value the image held before, ends with the pass's value (the
//! gated copy in took the CPU's bytes into the keep), and a row the CPU wrote but the log left
//! out, which the pass clears to the same value, keeps the CPU's bytes: the merge stores only
//! the words the pass changed against the keep. Over host pages with no log, the same pass's copy
//! back is a plain copy of every texel.
//!
//! Over a 1024x1024 such target whose CPU-written texels (told to the log) differ from black at
//! every other texel, a pass that clears it to black (with a draw in one pixel) changes every
//! other word: its merge stores whole 256-byte blocks
//! (`WorkCounts::shadow_merge_dispatches_in_blocks`) and the bytes are the pass's, the CPU's
//! texels it cleared black among them; a pass that loads it and draws black over every pixel
//! changes the same words, and its merge stores whole blocks too, as Metal's own store of such a
//! pass writes back every texel of each tile its draws reach (`shadow.rs`, **Stored
//! attachments**). Each prints the bytes its merge stores and its command buffers' median GPU
//! time (`DIRTY-OVERWRITE`). A pass that loads it and draws inside a 64x64 square, while a CPU
//! thread writes three texels beside the square over and over from before the commit to after
//! the completion, merges in whole blocks of the square's rows alone: each of those texels ends
//! holding the CPU's last write (`DIRTY-BESIDE`).
//!
//! One wait for a log's publication serves every gated copy in of a commit, two shadows over one
//! log among them, and a wait the log answers `false` is not made again for them
//! (`WorkCounts::dirty_waits`).
@@ -34,18 +56,19 @@
//! `m2v_cpu_icd`). The kernels are the owned fixture
//! `validation/fixtures/public/examples/runtime_examples.ll` (`llvm-as`).
use super::blit_holds::{device, Host, Scratch, BYTES, WAIT};
use super::blit_holds::{device, over_host, Host, Scratch, BYTES, WAIT};
use super::encoder_holds::{bytes_of, render_state};
use crate::{
Buffer, CommandBufferStatus, ComputePipelineState, Device, DirtyPages, DirtyStamp, Error,
EventRef, HostMemory, Library, LoadAction, PipelineOptions, Region, RenderPassDescriptor,
ResourceOptions, ScissorRect, Size, StoreAction, Texture, TextureDescriptor,
Buffer, ClearColor, CommandBufferStatus, ComputePipelineState, Device, DirtyPages, DirtyStamp,
Error, EventRef, HostMemory, Library, LoadAction, PipelineOptions, Region,
RenderPassDescriptor, ResourceOptions, ScissorRect, Size, StoreAction, Texture,
TextureDescriptor,
};
use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage};
use std::num::NonZeroU64;
use std::ops::Range;
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
const SIDE: u64 = 64;
@@ -428,6 +451,450 @@ fn a_logged_render_target_loaded_in_a_scissor_copies_only_the_changed_rows() {
drop(device);
}
/// One pass over `target` that clears it to opaque black and draws `color` over every pixel
/// inside rows 0 to 8 (the scissor), to completion: it replaces every texel.
fn clear_and_draw(device: &Device, target: &Texture, color: [f32; 4]) {
let state = render_state(device, "engine/tob_renders.ll", "tob_rect", "tob_solid");
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut pass = RenderPassDescriptor::new();
let attachment = &mut pass.color_attachments[0];
attachment.texture = Some(target.clone());
attachment.load_action = LoadAction::Clear;
attachment.clear_color = ClearColor::new(0.0, 0.0, 0.0, 1.0);
attachment.store_action = StoreAction::Store;
let mut encoder = command_buffer.render_command_encoder(&pass).unwrap();
encoder.set_render_pipeline_state(&state).unwrap();
let scissor = ScissorRect {
x: 0,
y: 0,
width: SIDE,
height: 8,
};
encoder.set_scissor_rect(scissor).unwrap();
let corners = bytes_of(&[-1.0f32, -1.0, 1.0, 1.0], f32::to_le_bytes);
encoder.set_vertex_bytes(&corners, 0).unwrap();
let color = bytes_of(&color, f32::to_le_bytes);
encoder.set_fragment_bytes(&color, 0).unwrap();
encoder
.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
assert!(command_buffer.wait_until_completed_for(WAIT).is_ok());
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
}
/// The texels copied back plainly and the merge dispatches planned so far.
fn backs(device: &Device) -> [u64; 2] {
let c = device.work_counts();
[
c.shadow_texels_copied_back,
c.shadow_merge_dispatches_planned,
]
}
/// A render target over `buffer`'s first bytes, or `None` where the device needs no shadow.
fn render_target(device: &Device, buffer: &Buffer) -> Option<Texture> {
let shadows = device.work_counts().shadowed_textures;
let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false);
descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
let target = buffer.new_texture(&descriptor, 0, ROW).unwrap();
let shadowed = device.work_counts().shadowed_textures - shadows;
eprintln!("DIRTY-PAGES: {shadowed} render shadow made");
(shadowed > 0).then_some(target)
}
const BLACK: [u8; 4] = [0, 0, 0, 255];
const RED: [u8; 4] = [255, 0, 0, 255];
#[test]
fn a_pass_replacing_a_logged_render_target_merges_back_the_words_it_changed() {
let scratch = Scratch::new("dirty-pages-overwrite");
let host = Host::new();
let device = device(&scratch.0);
eprintln!("DIRTY-PAGES: device {:?}", device.name());
let log = Arc::new(Log::default());
let Some(buffer) = over_logged(&device, &host, &log) else {
return;
};
host.fill(0x1010_1010);
let Some(target) = render_target(&device, &buffer) else {
return;
};
let bytes = buffer.contents().unwrap().as_ptr();
let texel_at = |row: u64| {
let mut texel = [0u8; 4];
// SAFETY: a texel inside the buffer's first rows, which no command uses now.
unsafe {
std::ptr::copy_nonoverlapping(bytes.add((row * ROW) as usize), texel.as_mut_ptr(), 4)
};
texel
};
// Frame 1: the pass clears every texel and draws rows 0 to 8, merged back, no plain copy.
let before = backs(&device);
clear_and_draw(&device, &target, [1.0, 0.0, 0.0, 1.0]);
let [copied, merges] = std::array::from_fn(|i| backs(&device)[i] - before[i]);
eprintln!("DIRTY-PAGES: overwrite frame 1: {copied} texels copied back, {merges} merges");
assert_eq!(copied, 0, "no texel copied back plainly");
assert!(merges > 0, "the pass's copy back is a merge");
assert_eq!(texel_at(0), RED, "the pass drew row 0");
assert_eq!(texel_at(20), BLACK, "and cleared row 20");
// Frame 2: the CPU writes row 40, told to the log, and row 50, left out of it; the pass
// clears both to the black the image held.
// SAFETY: rows inside the buffer's first bytes, which no command uses now.
unsafe {
std::ptr::write_bytes(bytes.add((40 * ROW) as usize), 0x40, ROW as usize);
std::ptr::write_bytes(bytes.add((50 * ROW) as usize), 0x50, ROW as usize);
}
log.told(40 * ROW..41 * ROW, 0);
let before = (backs(&device), counts(&device));
clear_and_draw(&device, &target, [1.0, 0.0, 0.0, 1.0]);
let [copied, merges] = std::array::from_fn(|i| backs(&device)[i] - before.0[i]);
let moved = delta(&device, before.1);
eprintln!(
"DIRTY-PAGES: overwrite frame 2: {copied} texels copied back, {merges} merges, copy in \
(gated, whole, skipped, bytes whole, copied) {moved:?}; row 40 {:?}, row 50 {:?}",
texel_at(40),
texel_at(50),
);
assert_eq!(copied, 0, "no texel copied back plainly");
assert!(merges > 0, "merged again");
assert_eq!(
moved[4],
SIDE * 4,
"the gated copy in took the told row alone"
);
assert_eq!(
texel_at(40),
BLACK,
"the pass's value over the told CPU write: Metal's"
);
assert_eq!(
texel_at(50),
[0x50; 4],
"a word the pass left as the keep held it is not stored"
);
assert_eq!(texel_at(0), RED);
drop(target);
drop(buffer);
drop(device);
}
#[test]
fn a_pass_replacing_an_unlogged_render_target_copies_it_back() {
let scratch = Scratch::new("dirty-pages-overwrite-unlogged");
let host = Host::new();
let device = device(&scratch.0);
let runs = Arc::new(AtomicUsize::new(0));
let Some(buffer) = over_host(&device, &host, &runs) else {
return;
};
host.fill(0x1010_1010);
let Some(target) = render_target(&device, &buffer) else {
return;
};
let bytes = buffer.contents().unwrap().as_ptr();
for frame in 1..=2 {
// SAFETY: a row inside the buffer's first bytes, which no command uses now.
unsafe { std::ptr::write_bytes(bytes.add((50 * ROW) as usize), 0x50, ROW as usize) };
let before = backs(&device);
clear_and_draw(&device, &target, [1.0, 0.0, 0.0, 1.0]);
let [copied, merges] = std::array::from_fn(|i| backs(&device)[i] - before[i]);
let mut texel = [0u8; 4];
// SAFETY: as above; the command buffer completed.
unsafe {
std::ptr::copy_nonoverlapping(bytes.add((50 * ROW) as usize), texel.as_mut_ptr(), 4)
};
eprintln!(
"DIRTY-PAGES: unlogged overwrite frame {frame}: {copied} texels copied back, {merges} \
merges; row 50 {texel:?}"
);
assert_eq!(copied, SIDE * SIDE, "every texel copied back plainly");
assert_eq!(merges, 0, "no merge");
assert_eq!(texel, BLACK, "the pass's value");
}
drop(target);
drop(buffer);
drop(device);
}
/// The large target's side and rows, the host pages' 4 MiB.
const LARGE: u64 = 1024;
const LARGE_ROW: u64 = 4 * LARGE;
/// One pass over `target` (`LARGE` square) that clears it to black (`load` `Clear`) or loads it,
/// and draws `color` over the pixels inside `scissor`, to completion: the command buffer's GPU
/// time in milliseconds, where the device gives it.
fn pass(
device: &Device,
target: &Texture,
load: LoadAction,
scissor: ScissorRect,
color: [f32; 4],
) -> Option<f64> {
let state = render_state(device, "engine/tob_renders.ll", "tob_rect", "tob_solid");
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut descriptor = RenderPassDescriptor::new();
let attachment = &mut descriptor.color_attachments[0];
attachment.texture = Some(target.clone());
attachment.load_action = load;
attachment.clear_color = ClearColor::new(0.0, 0.0, 0.0, 1.0);
attachment.store_action = StoreAction::Store;
let mut encoder = command_buffer.render_command_encoder(&descriptor).unwrap();
encoder.set_render_pipeline_state(&state).unwrap();
encoder.set_scissor_rect(scissor).unwrap();
let corners = bytes_of(&[-1.0f32, -1.0, 1.0, 1.0], f32::to_le_bytes);
encoder.set_vertex_bytes(&corners, 0).unwrap();
let color = bytes_of(&color, f32::to_le_bytes);
encoder.set_fragment_bytes(&color, 0).unwrap();
encoder
.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
assert!(command_buffer.wait_until_completed_for(WAIT).is_ok());
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
let (start, end) = (
command_buffer.gpu_start_time(),
command_buffer.gpu_end_time(),
);
Some((end.ok()? - start.ok()?) * 1e3)
}
/// The merge dispatches planned and those planned in whole blocks so far.
fn merges(device: &Device) -> [u64; 2] {
let c = device.work_counts();
[
c.shadow_merge_dispatches_planned,
c.shadow_merge_dispatches_in_blocks,
]
}
#[test]
fn a_scattered_overwrite_of_logged_pages_merges_back_in_whole_blocks() {
const ROUNDS: usize = 8;
let scratch = Scratch::new("dirty-pages-blocks");
let host = Host::new();
let device = device(&scratch.0);
eprintln!("DIRTY-PAGES: device {:?}", device.name());
let log = Arc::new(Log::default());
let Some(buffer) = over_logged(&device, &host, &log) else {
return;
};
assert!(LARGE_ROW * LARGE <= BYTES as u64);
let shadows = device.work_counts().shadowed_textures;
let mut descriptor =
TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, LARGE, LARGE, false);
descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
let target = buffer.new_texture(&descriptor, 0, LARGE_ROW).unwrap();
if device.work_counts().shadowed_textures == shadows {
eprintln!("DIRTY-PAGES: no render shadow made");
return;
}
let span = (LARGE_ROW * LARGE) as usize;
let bytes = buffer.contents().unwrap().as_ptr();
// The CPU's texels: every other one grey, the others black; told to the log.
let scatter = || {
let words: Vec<u32> = (0..LARGE * LARGE)
.map(|i| match i % 2 {
0 => 0x4040_4040,
_ => u32::from_le_bytes(BLACK),
})
.collect();
// SAFETY: the texture's bytes, which no command uses now.
unsafe { std::ptr::copy_nonoverlapping(words.as_ptr().cast::<u8>(), bytes, span) };
log.told(0..span as u64, 0);
};
let got = || {
// SAFETY: as above; every command buffer completed.
unsafe { std::slice::from_raw_parts(bytes, span) }.to_vec()
};
let every = ScissorRect {
x: 0,
y: 0,
width: LARGE,
height: LARGE,
};
let corner = ScissorRect {
x: 0,
y: 0,
width: 1,
height: 1,
};
let legs = [
(
"blocks (a pass clearing every texel)",
LoadAction::Clear,
corner,
RED,
),
(
"blocks (a pass loading and drawing every texel)",
LoadAction::Load,
every,
BLACK,
),
];
for (what, load, scissor, drawn) in legs {
let color = drawn.map(|c| f32::from(c) / 255.0);
let mut times = Vec::new();
let (mut planned, mut in_blocks) = (0, 0);
for _ in 0..ROUNDS {
scatter();
let before = merges(&device);
times.extend(pass(&device, &target, load, scissor, color));
let after = merges(&device);
planned += after[0] - before[0];
in_blocks += after[1] - before[1];
let now = got();
let wrong = (now.as_chunks::<4>().0.iter().enumerate())
.filter(|&(i, texel)| *texel != if i == 0 { drawn } else { BLACK })
.count();
assert_eq!(wrong, 0, "{what}: texels other than the pass's");
}
assert!(planned > 0, "{what}: merged");
// Both store whole blocks: one clears every texel, the other loads every texel and
// stores the tiles its draws reach (`ShadowUse::tile_stores`).
assert_eq!(in_blocks, planned, "{what}");
// By construction: every 256-byte block holds a changed word.
let stored = span;
times.sort_by(f64::total_cmp);
let median = times.get(times.len() / 2).copied().unwrap_or(f64::NAN);
eprintln!(
"DIRTY-OVERWRITE: {}: {what}: {in_blocks} of {planned} merge dispatches in whole \
blocks, {stored} bytes stored; GPU time median {median:.3} ms of {} command buffers \
[{:.3}..{:.3}]",
device.name(),
times.len(),
times.first().copied().unwrap_or(f64::NAN),
times.last().copied().unwrap_or(f64::NAN),
);
}
drop(target);
drop(buffer);
drop(device);
}
/// The texels beside the square a pass draws in that the CPU writes while it runs: right of it in
/// its rows (the next 256-byte block of a row), far right of it, and below it.
const BESIDE: [(u64, u64); 3] = [(64, 10), (900, 40), (10, 100)];
#[test]
fn a_pass_storing_its_loaded_area_keeps_a_cpu_write_beside_it() {
const ROUNDS: usize = 8;
let scratch = Scratch::new("dirty-pages-beside");
let host = Host::new();
let device = device(&scratch.0);
eprintln!("DIRTY-PAGES: device {:?}", device.name());
let log = Arc::new(Log::default());
let Some(buffer) = over_logged(&device, &host, &log) else {
return;
};
assert!(LARGE_ROW * LARGE <= BYTES as u64);
let shadows = device.work_counts().shadowed_textures;
let mut descriptor =
TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, LARGE, LARGE, false);
descriptor.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
let target = buffer.new_texture(&descriptor, 0, LARGE_ROW).unwrap();
if device.work_counts().shadowed_textures == shadows {
eprintln!("DIRTY-PAGES: no render shadow made");
return;
}
let span = (LARGE_ROW * LARGE) as usize;
let bytes = buffer.contents().unwrap().as_ptr();
let grey = 0x4040_4040u32;
let square = ScissorRect {
x: 0,
y: 0,
width: 64,
height: 64,
};
let inside = |x: u64, y: u64| x < 64 && y < 64;
let at = |(x, y): (u64, u64)| (y * LARGE_ROW + 4 * x) as usize;
let (mut planned, mut in_blocks, mut sweeps) = (0, 0, 0);
for _ in 0..ROUNDS {
// The CPU's texels: every other one grey, the others black; told to the log.
let words: Vec<u32> = (0..LARGE * LARGE)
.map(|i| match i % 2 {
0 => grey,
_ => u32::from_le_bytes(BLACK),
})
.collect();
// SAFETY: the texture's bytes, which no command uses now.
unsafe { std::ptr::copy_nonoverlapping(words.as_ptr().cast::<u8>(), bytes, span) };
log.told(0..span as u64, 0);
let before = merges(&device);
let stop = AtomicBool::new(false);
let started = AtomicBool::new(false);
let address = bytes as usize;
let last = std::thread::scope(|scope| {
let writer = scope.spawn(|| {
// SAFETY: whole texels of the buffer's bytes, 4-aligned; the pass writes none
// of them, and only this thread writes them while it runs.
let cells = BESIDE.map(|texel| unsafe {
std::sync::atomic::AtomicU32::from_ptr((address + at(texel)) as *mut u32)
});
let mut value = 0u32;
let mut swept = 0u64;
loop {
value = value.wrapping_add(1) | 0x8000_0000;
for cell in &cells {
cell.store(value, Ordering::SeqCst);
}
swept += 1;
started.store(true, Ordering::SeqCst);
if stop.load(Ordering::SeqCst) {
return (value, swept);
}
}
});
while !started.load(Ordering::SeqCst) {
std::hint::spin_loop();
}
pass(
&device,
&target,
LoadAction::Load,
square,
[0.0, 0.0, 0.0, 1.0],
);
stop.store(true, Ordering::SeqCst);
writer.join().unwrap()
});
sweeps += last.1;
let after = merges(&device);
planned += after[0] - before[0];
in_blocks += after[1] - before[1];
// SAFETY: the command buffer completed and the writer ended; nothing writes the bytes.
let now = unsafe { std::slice::from_raw_parts(bytes, span) };
for (texel, word) in now.as_chunks::<4>().0.iter().enumerate() {
let (x, y) = (texel as u64 % LARGE, texel as u64 / LARGE);
let want = match () {
_ if BESIDE.contains(&(x, y)) => last.0.to_le_bytes(),
_ if inside(x, y) => BLACK,
_ => words[texel].to_le_bytes(),
};
assert_eq!(*word, want, "texel ({x}, {y})");
}
}
eprintln!(
"DIRTY-BESIDE: {}: {in_blocks} of {planned} merge dispatches in whole blocks; the CPU \
wrote {} texels beside the square {sweeps} times over {ROUNDS} command buffers, each \
ending with its last write",
device.name(),
BESIDE.len(),
);
assert!(planned > 0, "merged");
assert_eq!(in_blocks, planned, "in whole blocks");
drop(target);
drop(buffer);
drop(device);
}
/// The stamps asked, the waits made and the waits answered `false` so far.
fn waits(device: &Device) -> [u64; 3] {
let c = device.work_counts();
@@ -10,6 +10,7 @@
use super::blit_holds::{device, Scratch};
use crate::owned_kernel::{OwnedBinds, OwnedModule, OwnedSet, OwnedSets};
use crate::ResourceOptions;
use metal2vulkan::bind::ShadowMergeStores;
#[test]
fn a_pushed_kernel_s_sets_are_pushed_and_never_allocated() {
@@ -18,7 +19,11 @@ fn a_pushed_kernel_s_sets_are_pushed_and_never_allocated() {
let pushes = device.shared().vk().push_descriptor().is_some();
let buffer = device.new_buffer(4096, ResourceOptions::private()).unwrap();
let (raw, at) = buffer.at(0);
for module in [OwnedModule::ShadowMerge, OwnedModule::RowsCopy] {
for module in [
OwnedModule::ShadowMerge(ShadowMergeStores::Words),
OwnedModule::ShadowMerge(ShadowMergeStores::Blocks),
OwnedModule::RowsCopy,
] {
let kernel = device.owned_kernel(module).unwrap();
assert_eq!(kernel.pushed, pushes, "{module:?}");
let set = || OwnedSet {
@@ -124,6 +124,7 @@ fn through(texture: &Arc<ShadowCopies>, writes: bool) -> (ShadowUse, Use<Resourc
kept: false,
area: None,
loads: None,
tile_stores: false,
},
used,
)
@@ -261,6 +262,7 @@ fn a_copy_back_covers_only_where_the_commands_wrote() {
kept: false,
area,
loads: None,
tile_stores: false,
};
let (_, written) = through(&t, true);
let run = |areas: &[Option<[u32; 4]>]| {
@@ -371,6 +373,7 @@ fn a_copy_in_covers_only_where_the_command_reads_and_writes() {
kept: false,
area: writes.then_some(area),
loads: Some(area),
tile_stores: false,
};
let a = [8, 4, 40, 20];
let mut sync = ShadowSync::<u32>::default();
@@ -771,6 +774,7 @@ fn a_read_inside_a_rectangle_leaves_the_other_changed_texels_to_the_next_read()
kept: false,
area: None,
loads: Some(area),
tile_stores: false,
};
within_command(sync, &[reader], &[], std::slice::from_ref(&read))
};
@@ -836,6 +840,7 @@ fn a_copy_back_of_a_part_leaves_a_twin_stale_there_alone() {
kept: false,
area: Some(area),
loads: Some([0, 0, 64, 32]),
tile_stores: false,
}];
let mut uses = vec![written.clone()];
for texture in also {
@@ -908,6 +913,7 @@ fn a_merge_of_a_part_leaves_a_twin_stale_there_alone() {
kept: false,
area: Some(area),
loads: Some([0, 0, 64, 32]),
tile_stores: false,
}];
let mut uses = vec![written.clone()];
for texture in also {
@@ -1051,6 +1057,7 @@ fn a_use_that_overwrites_every_texel_takes_no_copy_in() {
kept: false,
area: None,
loads: None,
tile_stores: false,
};
let (_, written) = through(&t, true);
for stores in [true, false] {
@@ -1601,6 +1608,7 @@ fn an_images_shadow_of_one_level_and_slice_is_cut_as_a_buffers_texture_is() {
let (_, read) = through(&s, false);
let reader = |area: [u32; 4]| ShadowUse {
loads: Some(area),
tile_stores: false,
..through(&s, false).0
};
let attachment = texels(image, 2..3, 0..1, true);
@@ -1661,6 +1669,7 @@ fn an_images_shadow_of_one_level_and_slice_is_cut_as_a_buffers_texture_is() {
writes: true,
area: Some(a),
loads: Some(a),
tile_stores: false,
..through(&s, true).0
};
let written = through(&s, true).1;
@@ -1742,6 +1751,7 @@ fn a_keep_holds_the_rectangle_its_commands_write_in() {
writes: true,
area,
loads: area,
tile_stores: false,
..through(&a, true).0
};
let copies = sync
@@ -1981,6 +1991,7 @@ impl Frame {
let shadows = [ShadowUse {
area: Some(area),
loads: Some(area),
tile_stores: false,
..through(texture, true).0
}];
let uses = [through(texture, true).1];
@@ -2263,3 +2274,59 @@ fn a_large_surfaces_first_copies_in_divide_into_carried_stood_earlier_and_unstoo
frame.sampling(&small, 1).sampling(&small, 1);
assert_eq!(frame.stood(), (64 * 32, 0, 0, 0), "a small mapped buffer's");
}
/// The scratch kinds a command's merges are made for (`MergeFor::blocks`) and the rectangles they
/// keep, in a fresh encoder, for a command that uses the shadowed textures `shadows` and has
/// `uses`.
fn made_for(shadows: &[ShadowUse], uses: &[Use<ResourceKey>]) -> Vec<(bool, Option<[u32; 4]>)> {
let mut sync = ShadowSync::<u32>::default();
let mut made = Vec::new();
sync.before(shadows, uses, |_, merge_for, area| {
made.push((merge_for.blocks, area));
Ok(0)
})
.unwrap();
made
}
/// A render pass's color it loads and stores inside its draws' scissors
/// (`ShadowUse::tile_stores`) is kept for a merge that stores whole blocks of that rectangle's
/// rows, as Metal's own store writes back every texel of each tile its draws reach; a pass whose
/// writes no rectangle bounds, and one whose texture a draw also writes through, keep one that
/// stores the changed words alone.
#[test]
fn a_pass_storing_its_loaded_area_merges_in_whole_blocks() {
let buffer = ResourceKey::new();
let t = cut_shadow(buffer, 256..256 + 320 * 32);
assert!(t.merges_back() && t.cuts());
let area = [8, 4, 40, 20];
let pass = |area: Option<[u32; 4]>, tile_stores: bool| ShadowUse {
area,
loads: area,
tile_stores,
..through(&t, true).0
};
let used = [through(&t, true).1];
assert_eq!(
made_for(&[pass(Some(area), true)], &used),
[(true, Some(area))]
);
// Not by tile stores alone, or bounded by no rectangle: the changed words alone.
assert_eq!(
made_for(&[pass(Some(area), false)], &used),
[(false, Some(area))]
);
assert_eq!(made_for(&[pass(None, true)], &used), [(false, None)]);
// A draw's write through the texture joins the pass's use: the changed words alone.
let mut joined = Vec::new();
shadow::join(&mut joined, &pass(Some(area), true));
shadow::join(&mut joined, &through(&t, true).0);
assert!(!joined[0].tile_stores && joined[0].area.is_none());
assert_eq!(made_for(&joined, &used), [(false, None)]);
// A draw's read of it leaves the pass's tile stores.
let mut joined = Vec::new();
shadow::join(&mut joined, &pass(Some(area), true));
shadow::join(&mut joined, &through(&t, false).0);
assert!(joined[0].tile_stores);
assert_eq!(made_for(&joined, &used), [(true, Some(area))]);
}
@@ -363,6 +363,7 @@ pub(crate) struct Counters {
shadow_merge_copies_dispatched: AtomicU64,
shadow_merge_dispatches_planned: AtomicU64,
shadow_merge_words_examined: AtomicU64,
shadow_merge_dispatches_in_blocks: AtomicU64,
shadow_merge_scratches_reused: AtomicU64,
shadow_merge_scratches_zeroed: AtomicU64,
row_copies: AtomicU64,
@@ -2326,6 +2327,13 @@ impl Counters {
.fetch_add(words, Ordering::Relaxed);
}
/// `dispatches` of a merge planned in whole blocks (`shadow_merge.rs`: a command's that replaces
/// every texel, or a render pass's that stores the tiles of its area).
pub(crate) fn shadow_merge_in_blocks(&self, dispatches: usize) {
self.shadow_merge_dispatches_in_blocks
.fetch_add(dispatches as u64, Ordering::Relaxed);
}
/// A merge of a shadowed texture took its scratch from its shadow's spares (`shadow_merge.rs`,
/// `ScratchSpares`).
pub(crate) fn shadow_merge_scratch_reused(&self) {
@@ -4622,6 +4630,14 @@ pub struct WorkCounts {
/// after them and stores into the buffer's bytes only where they differ, so the words stored
/// are at most these and are not counted (only the GPU knows them).
pub shadow_merge_words_examined: u64,
/// Those dispatches that store whole 256-byte blocks (`bind::ShadowMergeStores::Blocks`): a
/// merge of a command that replaced every texel of a shadow over logged host pages, cut to its
/// texels' rows, every byte of which the command wrote (`shadow.rs`, **Overwrites over logged
/// pages**), or of a render pass that loaded and stored its color attachment inside its draws'
/// scissors, cut to that rectangle's rows, whose tiles Metal's own store writes back
/// (**Stored attachments**). Of the blocks they examine, each holding a changed word is stored
/// whole and each other is neither read nor written; which ones changed only the GPU knows.
pub shadow_merge_dispatches_in_blocks: u64,
/// The merges of shadowed textures whose scratch was a buffer their shadow kept from an
/// earlier merge whose command buffers completed (`shadow_merge.rs`): no buffer made.
pub shadow_merge_scratches_reused: u64,
@@ -5559,6 +5575,9 @@ impl Device {
shadow_merge_words_examined: counters
.shadow_merge_words_examined
.load(Ordering::Relaxed),
shadow_merge_dispatches_in_blocks: counters
.shadow_merge_dispatches_in_blocks
.load(Ordering::Relaxed),
shadow_merge_scratches_reused: counters
.shadow_merge_scratches_reused
.load(Ordering::Relaxed),
@@ -1 +1 @@
994c21cf2d9e02b567ab545e9773ea6043f95d68731d354fe3d0bc2695424419
58fdd6a92ba611d4f24c6fd335171b10897cca8b7fe704a6eeb1b3927133fe15
+1 -1
View File
@@ -305,7 +305,7 @@ pub use sample_planes::{
};
pub use shadow_copy_back::{shadow_copy_back_module, ShadowCopyBackModule, ShadowTexelView};
pub use shadow_copy_in::{shadow_copy_in_module, ShadowCopyInModule};
pub use shadow_merge::{shadow_merge_module, ShadowMergeModule};
pub use shadow_merge::{shadow_merge_module, ShadowMergeModule, ShadowMergeStores};
pub use shadow_merge_image::{
shadow_merge_image_module, shadow_merge_kept_image_module, ShadowMergeImageModule,
ShadowMergeRead,
+262 -33
View File
@@ -62,6 +62,23 @@
//! loads of every shape at 0.32 ms. On an RX 7900 XTX (RADV) and a Radeon 780M the two shapes are
//! within measurement of each other.
//!
//! **Whole blocks** ([`ShadowMergeStores::Blocks`], the consumer's choice by the merge's
//! structure). The `LOCAL_SIZE` words a workgroup takes in one step, `4Ng + Nk` to
//! `4Ng + Nk + N - 1`, are one block of [`ShadowMergeModule::BLOCK_BYTES`]: each invocation first
//! compares its words of the kept and changed buffers and marks the step's block in the
//! workgroup's memory where its word differs (an atomic or, after the flags are cleared and a
//! barrier); after a second barrier, every word below `count` of a marked block is merged as
//! above, a word with no changed byte stored as the current buffer held it when read, and no word
//! of an unmarked block is read or written. So every block holding a change is stored whole, its
//! words consecutive across the invocations (a run per row it crosses), and the stores leave no
//! gaps inside it: on an RTX 5080 Laptop GPU, stores into imported host memory that leave words
//! between a warp's lanes take hundreds of times the time of the same bytes stored without gaps
//! (above). The bytes are the same as word by word where no other writer writes the current
//! buffer during the dispatch; one that writes a byte of a marked block outside its changed bytes
//! between the read and the store is undone. A consumer takes this form only where every word of
//! the region is bytes its commands wrote, or bytes Metal's own store of them writes back (a
//! render pass's tiles), so that such a write is a race with them (`ShadowMergeStores::Blocks`).
//!
//! **Synchronization** (consumer): the copies' `TRANSFER_WRITE` → `SHADER_STORAGE_READ` and
//! `SHADER_STORAGE_WRITE` in `COMPUTE_SHADER` before the dispatch; its writes →
//! `TRANSFER_READ` before the current buffer is copied back, or the bytes' next use.
@@ -78,8 +95,8 @@ use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::BResult;
use crate::spirv::ids::{GlobalId, TypeId, Value};
use crate::spirv::ir::{
natural_layout, BinOp, ExecMode, ExecModel, IoDir, LayoutRule, MemAccess, StorageClass, Type,
TypedModule,
natural_layout, AtomicOp, BinOp, ConstBits, Constant, ExecMode, ExecModel, IoDir, LayoutRule,
MemAccess, MemoryOrder, Scope, Semantics, StorageClass, Type, TypedModule,
};
/// The crate-owned shadow merge module of one device, validated like any output.
@@ -107,6 +124,9 @@ impl ShadowMergeModule {
pub const WORDS: u32 = 4;
/// Bytes of the `COMPUTE` push-constant range at offset 0: the region's shape.
pub const PUSH_BYTES: u32 = 16;
/// Bytes of one block under whole-block stores ([`ShadowMergeStores::Blocks`]): the
/// `LOCAL_SIZE` consecutive words a workgroup takes in one step (the module docs).
pub const BLOCK_BYTES: u32 = 4 * Self::LOCAL_SIZE;
/// The workgroups of a dispatch over `count` words.
pub fn groups(count: u32) -> u32 {
@@ -175,7 +195,7 @@ const SHAPE: PushField = PushField::DispatchRegion;
/// [`shadow_merge_module`] serializes, which the CPU interpreter runs. Its bindings are the
/// symbols `KEPT`, `CHANGED` and `CURRENT`, and its push field the shape, a `uvec4` (the module
/// docs).
fn typed_module() -> BResult<TypedModule> {
fn typed_module(blocks: bool) -> BResult<TypedModule> {
let mut b = ModuleBuilder::new();
let u32_ = b.ty(Type::Int {
width: 32,
@@ -188,6 +208,10 @@ fn typed_module() -> BResult<TypedModule> {
let kept = words_buffer(&mut b, KEPT, u32_)?;
let changed = words_buffer(&mut b, CHANGED, u32_)?;
let current = words_buffer(&mut b, CURRENT, u32_)?;
let block_flags = match blocks {
true => Some(block_flags(&mut b, u32_, ShadowMergeModule::WORDS)?),
false => None,
};
let group = b.builtin(crate::spv::BuiltIn::WorkgroupId, IoDir::Input, uvec3)?;
let local = b.builtin(crate::spv::BuiltIn::LocalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
@@ -219,24 +243,34 @@ fn typed_module() -> BResult<TypedModule> {
)?;
let base = f.binary(BinOp::IMul, g, span)?;
let base = f.binary(BinOp::IAdd, base, l)?;
// The invocation's words, one after the other, each as one invocation took it alone.
for k in 0..ShadowMergeModule::WORDS {
let i = match k {
0 => base,
k => {
let step = u32_value(&mut f, k * ShadowMergeModule::LOCAL_SIZE)?;
f.binary(BinOp::IAdd, base, step)?
}
};
let inside = f.binary(BinOp::ULessThan, i, count)?;
let merge: ArmFn<'_, ()> = Box::new(move |f, _| {
let p = f.access_chain(kept, &[zero, i])?;
if let Some(block_flags) = block_flags {
// Whole blocks: each step's words, the workgroup's `LOCAL_SIZE` consecutive words, are
// one block, stored whole where any of them changed (the module docs).
let flags = Blocks::new(&mut f, block_flags, l)?;
let mut words = Vec::new();
for k in 0..ShadowMergeModule::WORDS {
let i = match k {
0 => base,
k => {
let step = u32_value(&mut f, k * ShadowMergeModule::LOCAL_SIZE)?;
f.binary(BinOp::IAdd, base, step)?
}
};
let inside = f.binary(BinOp::ULessThan, i, count)?;
// A word past the region reads the region's first, and counts as unchanged.
let read = f.select(inside, i, zero)?;
let p = f.access_chain(kept, &[zero, read])?;
let before = f.load(p, MemAccess::default())?;
let p = f.access_chain(changed, &[zero, i])?;
let p = f.access_chain(changed, &[zero, read])?;
let after = f.load(p, MemAccess::default())?;
let differ = f.binary(BinOp::BitwiseXor, before, after)?;
let moved = f.binary(BinOp::INotEqual, differ, zero)?;
// A word the command left as it was is neither read nor written.
let differ = f.select(inside, differ, zero)?;
flags.mark(&mut f, k, differ)?;
words.push((i, inside, after, differ));
}
barrier(&mut f)?;
for (k, (i, inside, after, differ)) in (0..).zip(words) {
let store = flags.stores(&mut f, k, inside)?;
let write: ArmFn<'_, ()> = Box::new(move |f, _| {
let y = f.binary(BinOp::UDiv, i, width)?;
let x = f.binary(BinOp::UMod, i, width)?;
@@ -247,10 +281,42 @@ fn typed_module() -> BResult<TypedModule> {
merge_word(f, at, after, differ)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), moved, write, None)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), inside, merge, None)?;
f.if_(&mut (), store, write, None)?;
}
} else {
// The invocation's words, one after the other, each as one invocation took it alone.
for k in 0..ShadowMergeModule::WORDS {
let i = match k {
0 => base,
k => {
let step = u32_value(&mut f, k * ShadowMergeModule::LOCAL_SIZE)?;
f.binary(BinOp::IAdd, base, step)?
}
};
let inside = f.binary(BinOp::ULessThan, i, count)?;
let merge: ArmFn<'_, ()> = Box::new(move |f, _| {
let p = f.access_chain(kept, &[zero, i])?;
let before = f.load(p, MemAccess::default())?;
let p = f.access_chain(changed, &[zero, i])?;
let after = f.load(p, MemAccess::default())?;
let differ = f.binary(BinOp::BitwiseXor, before, after)?;
let moved = f.binary(BinOp::INotEqual, differ, zero)?;
// A word the command left as it was is neither read nor written.
let write: ArmFn<'_, ()> = Box::new(move |f, _| {
let y = f.binary(BinOp::UDiv, i, width)?;
let x = f.binary(BinOp::UMod, i, width)?;
let row = f.binary(BinOp::IMul, y, row_words)?;
let word = f.binary(BinOp::IAdd, first_word, row)?;
let word = f.binary(BinOp::IAdd, word, x)?;
let at = f.access_chain(current, &[zero, word])?;
merge_word(f, at, after, differ)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), moved, write, None)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), inside, merge, None)?;
}
}
f.ret(None)?;
let id = f.finish()?;
@@ -266,9 +332,92 @@ fn typed_module() -> BResult<TypedModule> {
b.finalize()
}
/// The workgroup's flags of its blocks under whole-block stores: one word per block, `steps` of
/// them (the module docs).
pub(super) fn block_flags(b: &mut ModuleBuilder, u32_: TypeId, steps: u32) -> BResult<GlobalId> {
let len = b.constant(Constant::Scalar {
ty: u32_,
bits: ConstBits(u64::from(steps)),
})?;
let flags = b.ty(Type::Array {
elem: u32_,
len,
stride: None,
})?;
b.plain_global(StorageClass::Workgroup, flags, None)
}
/// The workgroup barrier between the blocks' marks and their stores.
pub(super) fn barrier(f: &mut FunctionBuilder<'_>) -> BResult<()> {
let sem = Semantics {
order: MemoryOrder::AcquireRelease,
workgroup_memory: true,
..Semantics::RELAXED
};
f.control_barrier(Scope::Workgroup, Scope::Workgroup, sem)
}
/// The flags of a workgroup's blocks under whole-block stores, each zero until a word of its
/// block changed (the module docs).
pub(super) struct Blocks {
flags: Value,
zero: Value,
}
impl Blocks {
/// The flags `flags` (a [`block_flags`] global) cleared, invocation `l` clearing flag `l`
/// where it has one, then a barrier, so each mark lands after every clear.
pub(super) fn new(f: &mut FunctionBuilder<'_>, flags: GlobalId, l: Value) -> BResult<Blocks> {
let zero = u32_value(f, 0)?;
let flags = f.module().global_value(flags)?;
let steps = u32_value(f, ShadowMergeModule::WORDS)?;
let own = f.binary(BinOp::ULessThan, l, steps)?;
let clear: ArmFn<'_, ()> = Box::new(move |f, _| {
let at = f.access_chain(flags, &[l])?;
f.store(at, zero, MemAccess::default())?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), own, clear, None)?;
barrier(f)?;
Ok(Blocks { flags, zero })
}
/// Mark block `k` changed where `differ` (a word's xor of its kept and changed words) is not
/// zero.
pub(super) fn mark(&self, f: &mut FunctionBuilder<'_>, k: u32, differ: Value) -> BResult<()> {
let (flags, zero) = (self.flags, self.zero);
let moved = f.binary(BinOp::INotEqual, differ, zero)?;
let at = u32_value(f, k)?;
let mark: ArmFn<'_, ()> = Box::new(move |f, _| {
let at = f.access_chain(flags, &[at])?;
let one = u32_value(f, 1)?;
f.atomic(AtomicOp::Or, at, Scope::Workgroup, Semantics::RELAXED, one)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), moved, mark, None)?;
Ok(())
}
/// Whether a word of block `k`, `inside` the region, is stored: its block changed. Read after
/// the barrier that follows every mark.
pub(super) fn stores(
&self,
f: &mut FunctionBuilder<'_>,
k: u32,
inside: Value,
) -> BResult<Value> {
let at = u32_value(f, k)?;
let at = f.access_chain(self.flags, &[at])?;
let flag = f.load(at, MemAccess::default())?;
let changed = f.binary(BinOp::INotEqual, flag, self.zero)?;
f.binary(BinOp::LogicalAnd, inside, changed)
}
}
/// Merge into the current word at `at` the changed word `after`, `differ` its xor with the kept
/// word (not zero): each byte where they differ becomes `after`'s, and the others keep the
/// current word's (the module docs).
/// word: each byte where they differ becomes `after`'s, and the others keep the current word's
/// (the module docs); where `differ` is zero (a word of a changed block under whole-block
/// stores), the current word is stored as read.
pub(super) fn merge_word(
f: &mut FunctionBuilder<'_>,
at: Value,
@@ -295,6 +444,27 @@ pub(super) fn merge_word(
Ok(())
}
/// How a merge module stores the region's changed bytes into the current buffer (the module
/// docs).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ShadowMergeStores {
/// The changed words alone: a word with no changed byte is neither read nor written, so
/// another writer's bytes there are never rewritten.
Words,
/// Whole blocks of [`ShadowMergeModule::BLOCK_BYTES`]: a block holding a changed word is
/// stored whole, its words the commands left as read, and no other block is read or
/// written. For a region every byte of which the consumer's commands wrote (a command that
/// replaced every texel of a texture, in a region of its texels' rows): another writer's
/// write to a byte of it is a race with those commands, which Metal leaves unordered.
Blocks,
}
impl ShadowMergeStores {
fn blocks(self) -> bool {
self == ShadowMergeStores::Blocks
}
}
/// The fixed binding numbers of the module's symbols.
fn binding_of(sym: &Symbol) -> Option<u32> {
match sym {
@@ -306,12 +476,15 @@ fn binding_of(sym: &Symbol) -> Option<u32> {
}
}
/// The shadow merge module of `device`: built with the typed builder, checked by the owned
/// The shadow merge module of `device`, storing as `stores` says: built with the typed builder, checked by the owned
/// verifier against the device's profile (requirements included), serialized, and numbered with
/// the fixed bindings of [`ShadowMergeModule`].
pub fn shadow_merge_module(device: &Device) -> Result<ShadowMergeModule, Error> {
pub fn shadow_merge_module(
device: &Device,
stores: ShadowMergeStores,
) -> Result<ShadowMergeModule, Error> {
let profile = device.profile();
let m = typed_module()?;
let m = typed_module(stores.blocks())?;
let mut meter = Meter::new(&Budget::default());
crate::spirv::verify::verify(&m, profile, &mut meter)?;
let r = crate::spirv::serialize::serialize(m)?;
@@ -331,13 +504,16 @@ pub fn shadow_merge_module(device: &Device) -> Result<ShadowMergeModule, Error>
#[cfg(test)]
mod tests {
use super::{typed_module, ShadowMergeModule, CHANGED, CURRENT, KEPT};
use crate::spirv::interp::Outcome;
use crate::spirv::interp::{run, Buffer, Config, Order, Resources};
use crate::spirv::testing::{assert_valid, committed_profiles};
#[test]
fn the_merge_kernel_is_valid_on_every_committed_profile() {
for (_, p) in committed_profiles().expect("profiles") {
assert_valid(typed_module().expect("module"), &p);
for blocks in [false, true] {
assert_valid(typed_module(blocks).expect("module"), &p);
}
}
}
@@ -350,8 +526,9 @@ mod tests {
}
/// Run the kernel over `kept`, `changed` and `current` with the push bytes `shape`, in
/// `groups` workgroups, both invocation orders: the current buffer after it, the others
/// unchanged.
/// `groups` workgroups, both invocation orders and both forms of its stores (whole blocks and
/// changed words, which give the same bytes where no other writer runs beside the kernel):
/// the current buffer after it, the others unchanged.
fn merged_in(
kept: &[u8],
changed: &[u8],
@@ -359,8 +536,31 @@ mod tests {
shape: &[u8; 16],
groups: u32,
) -> Vec<u8> {
let m = typed_module().expect("module");
let mut out = Vec::new();
for blocks in [false, true] {
let (bytes, outcome) = merged_form(kept, changed, current, shape, groups, blocks);
// Whole blocks take two workgroup barriers (the clear, the marks); words none.
let barriers = if blocks { 2 } else { 0 };
assert!(outcome.iter().all(|i| i.barriers == barriers), "{blocks}");
out.push(bytes);
}
assert_eq!(out[0], out[1], "whole blocks store the bytes words do");
out.swap_remove(0)
}
/// [`merged_in`] in one form of the stores, whole `blocks` or words: the current buffer
/// after it, and the invocations' stats.
fn merged_form(
kept: &[u8],
changed: &[u8],
current: &[u8],
shape: &[u8; 16],
groups: u32,
blocks: bool,
) -> (Vec<u8>, Vec<crate::spirv::interp::InvocationStats>) {
let m = typed_module(blocks).expect("module");
let mut out = Vec::new();
let mut stats = Vec::new();
for order in [Order::Forward, Order::Reverse] {
let part = |slot, bytes: &[u8]| Buffer {
slot: Some(slot),
@@ -381,13 +581,18 @@ mod tests {
workgroups: [groups, 1, 1],
..Config::default()
};
let buffers = run(&m, &cfg, res).expect("run").buffers;
let Outcome {
buffers,
invocations,
..
} = run(&m, &cfg, res).expect("run");
assert_eq!(buffers[0], kept, "the kept buffer is only read");
assert_eq!(buffers[1], changed, "the changed buffer is only read");
out.push(buffers[2].clone());
stats = invocations;
}
assert_eq!(out[0], out[1], "order independent");
out.swap_remove(0)
(out.swap_remove(0), stats)
}
/// Each byte the texture changed is the changed buffer's; every other byte keeps the current
@@ -495,6 +700,30 @@ mod tests {
assert_eq!(merged_in(&kept, &changed, &current, &shape, groups), want);
}
/// Whole blocks: a block with no changed word reads and writes no word of the current
/// buffer, and a word of a changed block the command left keeps the current buffer's bytes.
/// The current buffer holds the first block's words alone, so an access to any other block's
/// traps (out of bounds) and fails the run; the words form touches the changed word alone.
#[test]
fn whole_blocks_touch_no_word_of_an_unchanged_block() {
let block = ShadowMergeModule::BLOCK_BYTES as usize;
// Two workgroups' words: eight blocks.
let words = 2 * (ShadowMergeModule::WORDS * ShadowMergeModule::LOCAL_SIZE) as usize;
let kept = vec![0u8; 4 * words];
let mut changed = kept.clone();
// One byte of word 3, in the first block.
changed[13] = 0x5a;
let current: Vec<u8> = (0..block).map(|i| (i % 251) as u8 ^ 0xc3).collect();
let mut want = current.clone();
want[13] = 0x5a;
let count = words as u32;
let shape = ShadowMergeModule::shape(count, count, 0, 0);
for blocks in [true, false] {
let (bytes, _) = merged_form(&kept, &changed, &current, &shape, 2, blocks);
assert_eq!(bytes, want, "{blocks}");
}
}
/// Invocations past the words write nothing, and every word of several workgroups merges.
#[test]
fn every_word_merges_across_workgroups_and_none_past_them() {
@@ -74,11 +74,18 @@
//! `COMPUTE_SHADER`, the kept buffer's copy → `SHADER_STORAGE_READ` (the kept image's copy →
//! `SHADER_SAMPLED_READ`), and the bytes' earlier accesses → `SHADER_STORAGE_READ` and
//! `SHADER_STORAGE_WRITE` there, before the dispatch; its writes → the bytes' next use.
//!
//! **Whole blocks** (`ShadowMergeStores::Blocks`): as `bind::shadow_merge`'s module docs say,
//! the `LOCAL_SIZE` words of a row a workgroup takes in one step are one block, marked in
//! workgroup memory where a word of it changed, and every word of a marked block is stored, none
//! of an unmarked one. A word past the row reads the row's first texel, and counts as unchanged.
use std::sync::Arc;
use super::shadow_copy_back::{fetched_words, ShadowTexelView};
use super::shadow_merge::{merge_word, u32_value, words_buffer};
use super::shadow_merge::{
barrier, block_flags, merge_word, u32_value, words_buffer, Blocks, ShadowMergeStores,
};
use crate::budget::{Budget, Meter};
use crate::device::requirements::Requirements;
use crate::device::Device;
@@ -280,7 +287,7 @@ impl Rebuild {
/// [`shadow_merge_kept_image_module`]) serializes, which the CPU interpreter runs. Its bindings
/// are the symbols `IMAGE`, `KEPT` (or `KEPT_IMAGE`) and `CURRENT`, and its push field the shape,
/// a `uvec4` (the module docs).
fn typed_module(read: ShadowMergeRead, kept: Kept) -> BResult<TypedModule> {
fn typed_module(read: ShadowMergeRead, kept: Kept, blocks: bool) -> BResult<TypedModule> {
let words = read.words();
let mut b = ModuleBuilder::new();
let u32_ = b.ty(Type::Int {
@@ -320,6 +327,10 @@ fn typed_module(read: ShadowMergeRead, kept: Kept) -> BResult<TypedModule> {
}
};
let current = words_buffer(&mut b, CURRENT, u32_)?;
let block_flags = match blocks {
true => Some(block_flags(&mut b, u32_, ShadowMergeImageModule::WORDS)?),
false => None,
};
let group = b.builtin(crate::spv::BuiltIn::WorkgroupId, IoDir::Input, uvec3)?;
let local = b.builtin(crate::spv::BuiltIn::LocalInvocationId, IoDir::Input, uvec3)?;
let void = b.ty(Type::Void)?;
@@ -406,65 +417,131 @@ fn typed_module(read: ShadowMergeRead, kept: Kept) -> BResult<TypedModule> {
let span = u32_value(&mut f, span)?;
let base = f.binary(BinOp::IMul, g, span)?;
let base = f.binary(BinOp::IAdd, base, l)?;
// The invocation's words, one after the other, each as one invocation took it alone.
for k in 0..ShadowMergeImageModule::WORDS {
let w = match k {
0 => base,
k => {
let step = u32_value(&mut f, k * ShadowMergeImageModule::LOCAL_SIZE)?;
f.binary(BinOp::IAdd, base, step)?
}
};
let inside = f.binary(BinOp::ULessThan, w, row_count)?;
let lanes = lanes.clone();
let merge: ArmFn<'_, ()> = Box::new(move |f, _| {
if let Some(block_flags) = block_flags {
// Whole blocks: each step's words, the workgroup's `LOCAL_SIZE` consecutive words of the
// row, are one block, stored whole where any of them changed (`bind::shadow_merge`'s
// module docs).
let flags = Blocks::new(&mut f, block_flags, l)?;
let mut taken = Vec::new();
for k in 0..ShadowMergeImageModule::WORDS {
let w = match k {
0 => base,
k => {
let step = u32_value(&mut f, k * ShadowMergeImageModule::LOCAL_SIZE)?;
f.binary(BinOp::IAdd, base, step)?
}
};
let inside = f.binary(BinOp::ULessThan, w, row_count)?;
// A word past the row reads the row's first, and counts as unchanged.
let read = f.select(inside, w, zero)?;
let (x, lane) = match split {
None => (w, None),
None => (read, None),
Some((shift, mask)) => (
f.binary(BinOp::ShiftRightLogical, w, shift)?,
Some(f.binary(BinOp::BitwiseAnd, w, mask)?),
f.binary(BinOp::ShiftRightLogical, read, shift)?,
Some(f.binary(BinOp::BitwiseAnd, read, mask)?),
),
};
let tx = f.binary(BinOp::IAdd, x0, x)?;
let coord = f.composite_construct(uvec2, &[tx, ty])?;
let image = f.load(image, MemAccess::default())?;
let loaded = f.load(image, MemAccess::default())?;
let ops = ImageOperands {
lod: Some(zero),
..ImageOperands::default()
};
let texel = f.fetch(image, coord, &ops)?;
let texel = rebuild.words(f, texel)?;
let after = one_word(f, &texel, lane, &lanes)?;
// The word before the command: in the kept image, the texel's at its own
// coordinates; in the kept buffer, the row's word, row after row.
let texel = f.fetch(loaded, coord, &ops)?;
let texel = rebuild.words(&mut f, texel)?;
let after = one_word(&mut f, &texel, lane, &lanes)?;
let before = match kept {
KeptAt::Image(kept, view) => {
let kept = f.load(kept, MemAccess::default())?;
let texel = f.fetch(kept, coord, &ops)?;
let words = fetched_words(f, texel, view)?;
one_word(f, &words, lane, &lanes)?
let words = fetched_words(&mut f, texel, view)?;
one_word(&mut f, &words, lane, &lanes)?
}
KeptAt::Buffer(kept) => {
let kept_row = f.binary(BinOp::IMul, y, row_count)?;
let place = f.binary(BinOp::IAdd, kept_row, w)?;
let place = f.binary(BinOp::IAdd, kept_row, read)?;
let p = f.access_chain(kept, &[zero, place])?;
f.load(p, MemAccess::default())?
}
};
let differ = f.binary(BinOp::BitwiseXor, before, after)?;
let moved = f.binary(BinOp::INotEqual, differ, zero)?;
// A word the command left as it was is neither read nor written.
let differ = f.select(inside, differ, zero)?;
flags.mark(&mut f, k, differ)?;
taken.push((w, inside, after, differ));
}
barrier(&mut f)?;
for (k, (w, inside, after, differ)) in (0..).zip(taken) {
let store = flags.stores(&mut f, k, inside)?;
let write: ArmFn<'_, ()> = Box::new(move |f, _| {
// The word at its row's place in the current buffer.
let place = f.binary(BinOp::IAdd, row, w)?;
let to = f.access_chain(current, &[zero, place])?;
merge_word(f, to, after, differ)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), moved, write, None)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), inside, merge, None)?;
f.if_(&mut (), store, write, None)?;
}
} else {
// The invocation's words, one after the other, each as one invocation took it alone.
for k in 0..ShadowMergeImageModule::WORDS {
let w = match k {
0 => base,
k => {
let step = u32_value(&mut f, k * ShadowMergeImageModule::LOCAL_SIZE)?;
f.binary(BinOp::IAdd, base, step)?
}
};
let inside = f.binary(BinOp::ULessThan, w, row_count)?;
let lanes = lanes.clone();
let merge: ArmFn<'_, ()> = Box::new(move |f, _| {
let (x, lane) = match split {
None => (w, None),
Some((shift, mask)) => (
f.binary(BinOp::ShiftRightLogical, w, shift)?,
Some(f.binary(BinOp::BitwiseAnd, w, mask)?),
),
};
let tx = f.binary(BinOp::IAdd, x0, x)?;
let coord = f.composite_construct(uvec2, &[tx, ty])?;
let image = f.load(image, MemAccess::default())?;
let ops = ImageOperands {
lod: Some(zero),
..ImageOperands::default()
};
let texel = f.fetch(image, coord, &ops)?;
let texel = rebuild.words(f, texel)?;
let after = one_word(f, &texel, lane, &lanes)?;
// The word before the command: in the kept image, the texel's at its own
// coordinates; in the kept buffer, the row's word, row after row.
let before = match kept {
KeptAt::Image(kept, view) => {
let kept = f.load(kept, MemAccess::default())?;
let texel = f.fetch(kept, coord, &ops)?;
let words = fetched_words(f, texel, view)?;
one_word(f, &words, lane, &lanes)?
}
KeptAt::Buffer(kept) => {
let kept_row = f.binary(BinOp::IMul, y, row_count)?;
let place = f.binary(BinOp::IAdd, kept_row, w)?;
let p = f.access_chain(kept, &[zero, place])?;
f.load(p, MemAccess::default())?
}
};
let differ = f.binary(BinOp::BitwiseXor, before, after)?;
let moved = f.binary(BinOp::INotEqual, differ, zero)?;
// A word the command left as it was is neither read nor written.
let write: ArmFn<'_, ()> = Box::new(move |f, _| {
// The word at its row's place in the current buffer.
let place = f.binary(BinOp::IAdd, row, w)?;
let to = f.access_chain(current, &[zero, place])?;
merge_word(f, to, after, differ)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), moved, write, None)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
f.if_(&mut (), inside, merge, None)?;
}
}
f.ret(None)?;
let id = f.finish()?;
@@ -521,15 +598,17 @@ fn binding_of(sym: &Symbol) -> Option<u32> {
}
}
/// The image-reading merge module of `device` reading the shadow's texels as `read` does:
/// The image-reading merge module of `device` reading the shadow's texels as `read` does and
/// storing as `stores` says:
/// built with the typed builder, checked by the owned verifier against the device's profile
/// (requirements included), serialized, and numbered with the fixed bindings of
/// [`ShadowMergeImageModule`].
pub fn shadow_merge_image_module(
device: &Device,
read: ShadowMergeRead,
stores: ShadowMergeStores,
) -> Result<ShadowMergeImageModule, Error> {
module_of(device, read, Kept::Buffer)
module_of(device, read, Kept::Buffer, stores)
}
/// The image-reading merge module of `device` reading texels through the unsigned-integer
@@ -539,8 +618,14 @@ pub fn shadow_merge_image_module(
pub fn shadow_merge_kept_image_module(
device: &Device,
view: ShadowTexelView,
stores: ShadowMergeStores,
) -> Result<ShadowMergeImageModule, Error> {
module_of(device, ShadowMergeRead::Words(view), Kept::Image(view))
module_of(
device,
ShadowMergeRead::Words(view),
Kept::Image(view),
stores,
)
}
/// [`shadow_merge_image_module`] or [`shadow_merge_kept_image_module`], by `kept`.
@@ -548,9 +633,10 @@ fn module_of(
device: &Device,
read: ShadowMergeRead,
kept: Kept,
stores: ShadowMergeStores,
) -> Result<ShadowMergeImageModule, Error> {
let profile = device.profile();
let m = typed_module(read, kept)?;
let m = typed_module(read, kept, stores == ShadowMergeStores::Blocks)?;
let mut meter = Meter::new(&Budget::default());
crate::spirv::verify::verify(&m, profile, &mut meter)?;
let r = crate::spirv::serialize::serialize(m)?;
@@ -592,7 +678,9 @@ mod tests {
fn the_image_merge_kernels_are_valid_on_every_committed_profile() {
for (_, p) in committed_profiles().expect("profiles") {
for (read, kept) in forms() {
assert_valid(typed_module(read, kept).expect("module"), &p);
for blocks in [false, true] {
assert_valid(typed_module(read, kept, blocks).expect("module"), &p);
}
}
}
}
@@ -671,7 +759,8 @@ mod tests {
/// The current buffer's words after one dispatch over `region` (`[x0, y0, width, height]`) of
/// `shadow` read through `read`, `kept` its region's words before (in a buffer, row after row,
/// or, by `form`, in an image at their own coordinates), rows `row_words` apart in `current`
/// from `first_word`, in both invocation orders.
/// from `first_word`, in both invocation orders and both forms of the stores (whole blocks and
/// changed words, which give the same bytes where no other writer runs beside the kernel).
fn merged(
shadow: &Image,
(read, form): (ShadowMergeRead, Kept),
@@ -680,7 +769,6 @@ mod tests {
(row_words, first_word): (u32, u32),
current: &[u32],
) -> Vec<u32> {
let m = typed_module(read, form).expect("module");
let [x0, y0, width, height] = region;
let extent = [shadow.extent[0], shadow.extent[1]];
let shape = ShadowMergeImageModule::shape([x0, y0], width, row_words, first_word);
@@ -698,7 +786,11 @@ mod tests {
})
};
let mut out = Vec::new();
for order in [Order::Forward, Order::Reverse] {
for (blocks, order) in [false, true]
.into_iter()
.flat_map(|blocks| [Order::Forward, Order::Reverse].map(|order| (blocks, order)))
{
let m = typed_module(read, form, blocks).expect("module");
let buffer = |slot, words: &[u32]| Buffer {
slot: Some(slot),
address: None,
@@ -722,6 +814,9 @@ mod tests {
..Config::default()
};
let (outcome, images) = run_with_images(&m, &cfg, res, images).expect("run");
// Whole blocks take two workgroup barriers (the clear, the marks); words none.
let barriers = if blocks { 2 } else { 0 };
assert!(outcome.invocations.iter().all(|i| i.barriers == barriers));
assert_eq!(&images[0], shadow, "the view is only read");
match form {
Kept::Buffer => {
@@ -731,9 +826,48 @@ mod tests {
}
out.push(words_of(outcome.buffers.last().expect("current")));
}
assert_eq!(out[0], out[1], "order independent");
assert!(
out.iter().all(|o| *o == out[0]),
"order and form independent"
);
out.swap_remove(0)
}
/// Whole blocks: a block of a row with no changed word reads and writes no word of the
/// current buffer, and a word of a changed block the command left keeps the current
/// buffer's. The current buffer holds the row's first block alone (`LOCAL_SIZE` words), so an
/// access to any other block of the row traps (out of bounds) and fails the run, through
/// every read, the kept words in a buffer or in an image.
#[test]
fn whole_blocks_touch_no_word_of_an_unchanged_block_of_a_row() {
for (read, form) in forms() {
let words = read.words();
let region = [10, 2, 270, 1];
let [x0, y0, width, _] = region;
// Kept: the fetched words but texel 3's word 0, whose low byte alone differs.
let mut kept = Vec::new();
for x in 0..width {
for i in 0..words {
let word = texel_word(x0 + x, y0, i);
kept.push(if x == 3 && i == 0 { word ^ 0xff } else { word });
}
}
let current: Vec<u32> = (0..ShadowMergeImageModule::LOCAL_SIZE)
.map(|i| 0xa5a5_0000 | i)
.collect();
let got = merged(
&image([300, 7], read),
(read, form),
region,
&kept,
(width * words, 0),
&current,
);
let mut want = current.clone();
let at = (3 * words) as usize;
want[at] = (current[at] & !0xff) | (texel_word(x0 + 3, y0, 0) & 0xff);
assert_eq!(got, want, "{read:?} {form:?}");
}
}
/// Each byte the texture changed since the keep lands at its row's place; a word whose kept
/// and fetched words are equal keeps the current buffer's (another writer's write there
+1 -1
View File
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 478;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 1693;
pub const RUNTIME_VERSION: u32 = 1696;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
@@ -45,6 +45,12 @@ const EXTENDED: [ExtendedRange; 13] = [
ExtendedRange::Rgba16Bfloat,
];
/// Both forms of a shadow merge's stores.
const STORES: [bind::ShadowMergeStores; 2] = [
bind::ShadowMergeStores::Words,
bind::ShadowMergeStores::Blocks,
];
fn modules() -> Vec<Build> {
let mut out: Vec<Build> = Vec::new();
macro_rules! plain {
@@ -66,7 +72,6 @@ fn modules() -> Vec<Build> {
replay_preprocess_module,
rotate_texels_module,
rows_copy_module,
shadow_merge_module,
tiled_texels_module,
two_plane_texels_module,
visibility_combine_module,
@@ -78,6 +83,12 @@ fn modules() -> Vec<Build> {
|name: String, build: Box<dyn Fn(&Device) -> Result<Arc<[u32]>, Error> + Sync>| {
out.push((name, build));
};
for stores in STORES {
push(
format!("shadow_merge_module({stores:?})"),
Box::new(move |d| Ok(bind::shadow_merge_module(d, stores)?.spirv)),
);
}
for form in EXTENDED {
push(
format!("extended_shadow_module({form:?})"),
@@ -101,16 +112,20 @@ fn modules() -> Vec<Build> {
format!("shadow_copy_in_module({view:?})"),
Box::new(move |d| Ok(bind::shadow_copy_in_module(d, view)?.spirv)),
);
push(
format!("shadow_merge_kept_image_module({view:?})"),
Box::new(move |d| Ok(bind::shadow_merge_kept_image_module(d, view)?.spirv)),
);
for stores in STORES {
push(
format!("shadow_merge_kept_image_module({view:?}, {stores:?})"),
Box::new(move |d| Ok(bind::shadow_merge_kept_image_module(d, view, stores)?.spirv)),
);
}
}
for read in bind::ShadowMergeRead::ALL {
push(
format!("shadow_merge_image_module({read:?})"),
Box::new(move |d| Ok(bind::shadow_merge_image_module(d, read)?.spirv)),
);
for stores in STORES {
push(
format!("shadow_merge_image_module({read:?}, {stores:?})"),
Box::new(move |d| Ok(bind::shadow_merge_image_module(d, read, stores)?.spirv)),
);
}
}
for conversion in crate::bind::ycbcr_convert::conversions() {
push(
+9 -3
View File
@@ -308,6 +308,7 @@ assoc-const metal2vulkan::bind::ShadowMergeImageModule::LOCAL_SIZE pub const LOC
assoc-const metal2vulkan::bind::ShadowMergeImageModule::PUSH_BYTES pub const PUSH_BYTES: u32
assoc-const metal2vulkan::bind::ShadowMergeImageModule::SET pub const SET: u32
assoc-const metal2vulkan::bind::ShadowMergeImageModule::WORDS pub const WORDS: u32
assoc-const metal2vulkan::bind::ShadowMergeModule::BLOCK_BYTES pub const BLOCK_BYTES: u32
assoc-const metal2vulkan::bind::ShadowMergeModule::CHANGED_BINDING pub const CHANGED_BINDING: u32
assoc-const metal2vulkan::bind::ShadowMergeModule::CURRENT_BINDING pub const CURRENT_BINDING: u32
assoc-const metal2vulkan::bind::ShadowMergeModule::KEPT_BINDING pub const KEPT_BINDING: u32
@@ -773,6 +774,7 @@ assoc-const-value metal2vulkan::bind::ShadowMergeImageModule::LOCAL_SIZE 64
assoc-const-value metal2vulkan::bind::ShadowMergeImageModule::PUSH_BYTES 16
assoc-const-value metal2vulkan::bind::ShadowMergeImageModule::SET 0
assoc-const-value metal2vulkan::bind::ShadowMergeImageModule::WORDS 4
assoc-const-value metal2vulkan::bind::ShadowMergeModule::BLOCK_BYTES 4 * Self::LOCAL_SIZE
assoc-const-value metal2vulkan::bind::ShadowMergeModule::CHANGED_BINDING 1
assoc-const-value metal2vulkan::bind::ShadowMergeModule::CURRENT_BINDING 2
assoc-const-value metal2vulkan::bind::ShadowMergeModule::KEPT_BINDING 0
@@ -1343,6 +1345,7 @@ enum metal2vulkan::bind::RewriteProgram #[cfg_attr(feature = "serde", derive(ser
enum metal2vulkan::bind::RewriteSource #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum RewriteSource
enum metal2vulkan::bind::SamplerSource #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum SamplerSource
enum metal2vulkan::bind::ShadowMergeRead #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum ShadowMergeRead
enum metal2vulkan::bind::ShadowMergeStores #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum ShadowMergeStores
enum metal2vulkan::bind::ShadowTexelView #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum ShadowTexelView
enum metal2vulkan::bind::StatusWord #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum StatusWord
enum metal2vulkan::bind::TessellationRecords #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum TessellationRecords
@@ -2781,6 +2784,7 @@ field metal2vulkan-runtime::WorkCounts.shadow_copies_in_dispatched pub shadow_co
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
field metal2vulkan-runtime::WorkCounts.shadow_merge_dispatches_in_blocks pub shadow_merge_dispatches_in_blocks: u64
field metal2vulkan-runtime::WorkCounts.shadow_merge_dispatches_planned pub shadow_merge_dispatches_planned: u64
field metal2vulkan-runtime::WorkCounts.shadow_merge_kept_images_followed pub shadow_merge_kept_images_followed: u64
field metal2vulkan-runtime::WorkCounts.shadow_merge_kept_images_live pub shadow_merge_kept_images_live: u64
@@ -4550,9 +4554,9 @@ fn metal2vulkan::bind::rows_copy_module pub fn rows_copy_module(device: &Device)
fn metal2vulkan::bind::sampler_desc pub fn sampler_desc(device: &crate::device::Device, desc: &crate::bind::state::SamplerDescriptor, use_: SamplerUse, opaque_black: OpaqueBlackBorder, image_format: Option<vk::Format>) -> Result<vk::SamplerDesc, BindError>
fn metal2vulkan::bind::shadow_copy_back_module pub fn shadow_copy_back_module(device: &Device, view: ShadowTexelView) -> Result<ShadowCopyBackModule, Error>
fn metal2vulkan::bind::shadow_copy_in_module pub fn shadow_copy_in_module(device: &Device, view: ShadowTexelView) -> Result<ShadowCopyInModule, Error>
fn metal2vulkan::bind::shadow_merge_image_module pub fn shadow_merge_image_module(device: &Device, read: ShadowMergeRead) -> Result<ShadowMergeImageModule, Error>
fn metal2vulkan::bind::shadow_merge_kept_image_module pub fn shadow_merge_kept_image_module(device: &Device, view: ShadowTexelView) -> Result<ShadowMergeImageModule, Error>
fn metal2vulkan::bind::shadow_merge_module pub fn shadow_merge_module(device: &Device) -> Result<ShadowMergeModule, Error>
fn metal2vulkan::bind::shadow_merge_image_module pub fn shadow_merge_image_module(device: &Device, read: ShadowMergeRead, stores: ShadowMergeStores) -> Result<ShadowMergeImageModule, Error>
fn metal2vulkan::bind::shadow_merge_kept_image_module pub fn shadow_merge_kept_image_module(device: &Device, view: ShadowTexelView, stores: ShadowMergeStores) -> Result<ShadowMergeImageModule, Error>
fn metal2vulkan::bind::shadow_merge_module pub fn shadow_merge_module(device: &Device, stores: ShadowMergeStores) -> Result<ShadowMergeModule, Error>
fn metal2vulkan::bind::stencil_split_module pub fn stencil_split_module(device: &Device, feature: Feature) -> Result<StencilSplitModule, Error>
fn metal2vulkan::bind::tessellation_scan_module pub fn tessellation_scan_module(device: &Device, kernel: &TessellationScanKernel) -> Result<TessellationScanModule, Error>
fn metal2vulkan::bind::tiled_texels_module pub fn tiled_texels_module(device: &Device) -> Result<TiledTexelsModule, Error>
@@ -12129,6 +12133,8 @@ variant metal2vulkan::bind::SamplerSource::Slot Slot { slot: SlotRef, compare: b
variant metal2vulkan::bind::ShadowMergeRead::B8G8R8A8Unorm B8G8R8A8Unorm
variant metal2vulkan::bind::ShadowMergeRead::R8G8B8A8Unorm R8G8B8A8Unorm
variant metal2vulkan::bind::ShadowMergeRead::Words Words(ShadowTexelView)
variant metal2vulkan::bind::ShadowMergeStores::Blocks Blocks
variant metal2vulkan::bind::ShadowMergeStores::Words Words
variant metal2vulkan::bind::ShadowTexelView::R32G32B32A32Uint R32G32B32A32Uint
variant metal2vulkan::bind::ShadowTexelView::R32G32Uint R32G32Uint
variant metal2vulkan::bind::ShadowTexelView::R32Uint R32Uint
Can't render this file because it is too large.
+1
View File
@@ -646,6 +646,7 @@ surface! {
fn shadow_merge_kept_image_module;
struct ShadowMergeImageModule N;
enum ShadowMergeRead E;
enum ShadowMergeStores E;
fn extended_shadow_module;
struct ExtendedShadowModule N;
struct BlockDecodeModule N;
+6 -1
View File
@@ -1315,7 +1315,12 @@ bound.
is a dispatch that merges only the words the commands
changed, so that writer's writes to the texels they left stay, as on Metal: the CPU's, over a
`Shared` or `Managed` buffer's bytes, host pages or the caller's `VkBuffer`, and another queue's
commands', over an untracked buffer's. A tracked `Private` buffer's bytes have no such writer (the
commands', over an untracked buffer's. After a render pass that loads and stores it as a color
attachment inside its draws' scissors, or a command that replaces every texel over host pages
that log their writes, the dispatch stores each 256-byte block of the rows it merges that holds
a changed word whole (`WorkCounts::shadow_merge_dispatches_in_blocks`): Metal's own store of
such a pass writes back every texel of each tile its draws reach, so a write to a texel the
pass left inside its render area while it runs is not kept on Metal either. A tracked `Private` buffer's bytes have no such writer (the
runtime orders another queue's commands that touch them before or after the command buffer, as
Metal does), and are copied back (`shadow_texels_copied_back`), as a command that replaces every
texel is. The scratch keeps the rectangle the commands write in, where they bound it and the
+12 -6
View File
@@ -909,9 +909,15 @@ else.
snaps each decoded tap to Metal's twelve-bit step (`lower/sampler/bicubic.rs`); and `half`
`fmod` gives a zero result Metal's sign on its exact remainder routine, where no note records the
device's yet. Each is open work toward the device's answer; none is announced.
- **A shadow's merge back to host pages stores each changed word alone**, so over PCIe, where the
changed words alternate, the stores leave gaps the bus takes one at a time: on an RTX 5080 a
merge over 4 MiB of host pages with every other word changed took 150 ms of GPU time, against
0.40 ms with a 64x64 square changed and 0.86 ms with every word changed. Storing whole blocks
takes under 1 ms in each of those shapes, but would rewrite unchanged bytes a CPU may be writing
meanwhile, a write Metal keeps, so the merge does not. Not announced.
- **A shadow's merge back to host pages stores each changed word alone after a command that
leaves texels it does not write** (a kernel's or a blit's partial writes among them; a render
pass that loads and stores its attachment inside its scissors, and a command that replaces
every texel over logged pages, store whole 256-byte blocks). Over PCIe each separate run of
changed words past the first in a 64-byte host line costs about 180 ns, serialized: on an RTX
5080, 4 MiB with every other word changed took 88 to 102 ms (11 ms with each line's runs stored
in separate passes), against 0.4 ms in whole blocks. Blocks stay out there: they rewrite
unchanged bytes a CPU may be writing meanwhile, and Metal keeps such a write beside a kernel's
(on an M3 Max, a kernel writing one texel lost none of a CPU thread's writes to the texels
around it in about 1.1e9 checks), while a loading and storing pass rewrites the whole 32x32
tile it draws in (`shadow.rs`, **Stored attachments**). A blit's partial writes keep the
kernel's rule. Not announced.