Read a self-read through a snapshot of a color's own image where its image lacks STORAGE, pinning the instances through it

On the Iris Xe (m3-max-5702, the self_reads lane) a surface in place over host pages split every
reading draw: 30 splits a frame, 224M texels copied in, 19.5 to 26 ms of GPU a frame, where its
shadow took the snapshot (4.2 to 4.8 ms). Its image lacks STORAGE (the device's check failed
storage writes over its pages), so snapshot_wanted fell back: a later framebuffer fetch of the
color would render it through a stand-in for the whole pass, copied in before the pass, which a
snapshot draw reading the texture's own image would not see.

A draw now reads such a color through a snapshot of its own image all the same, pinning it
(RenderLowering::pins_own_attachment), where nothing the pass's end decides from the whole pass
changes what the instances through the draw render: the pass's first instance recorded inline,
no stand-in, memoryless color or depth/stencil attachment in the pass, every color stored Store,
no tile dispatch, execution, color groups or extended-range shadows, a draw that fetches nothing
and needs no hidden depth. A stand-in arriving after a pin freezes the pins (no later draw pins),
and the pass's end then renders the instances through the last pinned one with the colors' own
images, takes each stand-in's copy of its attachment after the last of them (and a merged
color's keep after that copy), keeps the reloads after them alone and joins no run of passes:
as after an instance recorded inline (render/inline_first.rs).

Counted: WorkCounts::reading_draws_pinned, WorkCounts::stand_ins_after_pins.

Tests: tests::self_read_storage: a private target without STORAGE pins its first pass's reader
and then takes its storage form; a pass whose pinned reader is followed by a fetch of the target
keeps the reader's pixels and halves the fetched ones (a stand-in for the whole pass would leave
the reader the red before the pass).

The self-read cost lane (runtime_lane::attachment_read_costs::self_reads) prints the readers
pinned per frame.

Verified:
- Iris Xe (ANV, Mesa 26.2.6), m3-max-6011: tests::self_read_storage passed both. A private
  BGRA8Unorm target without STORAGE gave (splits, snapshotted, pinned, stand-ins after pins,
  storage forms) = [0, 1, 1, 0, 1] in its first pass and [0, 1, 0, 0, 0] in later passes. A
  fetch after a pinned reader gave [0, 1, 1, 1, 1] in pass 0, with the reader's pixels the pass's
  red and the fetched ones halved.
- lavapipe takes no snapshot path. There, both tests check the split branch ([1, 0, 0, 0, 0]);
  193 filtered lavapipe tests passed in m3-max-5964.
- Clippy plain, --cfg m2v_cpu_icd and --cfg m2v_gpu, and rustdoc -D warnings, for runtime and
  validation: clean (m3-max-5964).
- The Iris lane frame: the device's render-target check now fails over host pages (the next
  commits), so the surface is a shadow and its readers take the snapshot unpinned: 3.94-3.97
  ms/frame on development and on this commit alike (m3-max-6068, three rounds each, each process
  checking on a fresh cache). Pins apply there to a private target without STORAGE and to a
  render target over pages whose check passed.

(cherry picked from commit e0799938e01c14d6b087ce7442bf9acfe3171b1c)
This commit is contained in:
Anees Iqbal committed 2026-11-07 19:55:49 -08:00
1 parent d1c4221cb6
commit e5c37ecc62
12 files changed
+485 -105

No files matched your search

@@ -2053,6 +2053,8 @@ impl Gpu for Runtime {
("attachment_read_clears", c.attachment_read_clears),
("reading_draws_snapshotted", c.reading_draws_snapshotted),
("snapshot_inline_splits", c.snapshot_inline_splits),
("reading_draws_pinned", c.reading_draws_pinned),
("stand_ins_after_pins", c.stand_ins_after_pins),
("feedback_loop_alias_images", c.feedback_loop_alias_images),
("feedback_loop_shadow_images", c.feedback_loop_shadow_images),
("depth_attachments_moved", c.depth_attachments_moved),
@@ -10,7 +10,10 @@
//! ([`pooled_backing`]).
//! - **A fetched texture's scratch.** One rule for both forms of framebuffer fetch: a color
//! texture whose image lacks the usage its fetch form needs renders, in a pass that fetches
//! it, into a scratch image that has it, as its attachment in every instance too. In the
//! it, into a scratch image that has it, as its attachment in every instance too, but those
//! that render the texture itself before it arrives (recorded inline, or pinned by a draw that
//! reads it through a snapshot: `render/inline_first.rs`, `render/snapshot.rs`), after which it
//! is copied in. In the
//! pixel interlock that usage is `STORAGE`, which a texture the runtime makes holds only where
//! it costs the image nothing (`framebuffer_fetch::Answers`); through input attachments it is
//! input attachment usage, which every color render target the runtime makes holds and a
@@ -461,6 +461,34 @@ impl LinearMerge {
}
}
/// Record into `command_buffer`, between two render pass instances of the pass, the keep
/// that follows its stand-in's copy in there, where the instances before rendered the
/// attachment itself (`render/snapshot.rs`'s pins), as [`record_keep`](Self::record_keep)
/// records it before the pass: first, where it has one, the scratch's fill with zero; each
/// between barriers. The pass's uses hold the keep's ([`keep_uses`](Self::keep_uses)).
///
/// # Safety
///
/// As for [`LinearMerge::reload_in`].
pub(super) unsafe fn keep_in_pass(&self, device: &Vk, command_buffer: vk::CommandBuffer) {
// SAFETY: the caller's contract; the scratch is the merge's, a transfer destination, and
// the filled range is its two parts, whole words.
unsafe {
Barrier::everything().record(device, command_buffer);
if let Some((offset, size)) = self.padding {
device.cmd_fill_buffer(command_buffer, self.scratch, offset, size, 0);
Barrier::everything().record(device, command_buffer);
}
self.keep_in(device, command_buffer);
Barrier::everything().record(device, command_buffer);
}
}
/// The keep's uses: the kept image's read.
pub(super) fn keep_uses(&self) -> &[Use<ResourceKey>] {
&self.keep_uses
}
/// The keep's copy.
///
/// # Safety
+92 -16
View File
@@ -107,7 +107,9 @@
//! leaves out, bound as storage views of their level and layer, whose fragment shader reads
//! and writes join the draw's uses. Either way a fetched attachment whose image lacks the
//! usage its form needs (input attachment usage, or `STORAGE`) renders, from the draw on and
//! for the whole pass, into a stand-in that has it (`attachment_stand_in.rs`). In a
//! for the whole pass, into a stand-in that has it (`attachment_stand_in.rs`): but for the
//! instances recorded inline and those a draw pinned to the attachments' own images
//! (`render/inline_first.rs`, `render/snapshot.rs`), after which it takes their texels. In a
//! multisampled pass the interlock form reads and writes the attachment's sample planes on a
//! device without multisampled storage images (`sample_planes.rs`): made at the first draw that
//! fetches the attachment, bound to every such draw as a storage view of every layer, and moved
@@ -383,7 +385,7 @@ use metal2vulkan::pipeline::{
StorageAttachmentUse, StorageAttachmentView,
};
use pass_start_reads::{PassStartReads, PassStartTables};
use pass_steps::{InstanceSteps, PassSteps, StagedDispatch, StagedRows};
use pass_steps::{AfterPins, InstanceSteps, PassSteps, StagedDispatch, StagedRows};
use pending::{OwnedRecording, PendingDraw};
use provoking::ProvokingForms;
use shadows::InstanceShadows;
@@ -1693,6 +1695,14 @@ pub(crate) struct RenderLowering {
/// The pass's color group, where the device draws its colors in groups: the encoder draws
/// that group's (`render/color_groups.rs`).
grouped: Option<Box<color_groups::Grouped>>,
/// The count of the pass's instances through the last that a draw pinned to its colors' own
/// images, reading one through a snapshot of it that a later fetch would otherwise render
/// through a stand-in (`render/snapshot.rs`): a stand-in arriving after them takes its
/// attachment's texels after the last of them. 0 where no draw pinned one.
pinned_through: usize,
/// A stand-in or the hidden depth and stencil arrived after a pin: no later draw pins
/// (`render/snapshot.rs`).
pins_frozen: bool,
}
/// What a render encoder's draws retained of their own (their pipeline states, their variants'
@@ -2246,6 +2256,8 @@ impl RenderLowering {
held_bound: Bound::default(),
again: draw_again::DrawAgain::default(),
grouped,
pinned_through: 0,
pins_frozen: false,
},
)
}
@@ -4239,7 +4251,7 @@ impl RenderLowering {
inputs_read,
residency,
extended,
reload_at,
mut reload_at,
log,
depth_writes,
drew_depth_writes,
@@ -4248,6 +4260,7 @@ impl RenderLowering {
live,
bind_memo,
pass_start,
pinned_through,
..
} = *self;
// The views and sampler descriptions its binds made or found, which the device's next
@@ -4827,10 +4840,24 @@ impl RenderLowering {
// again.
let mut runs: Vec<RunColor> = Vec::new();
let mut shadow_runs: Vec<ShadowRunColor> = Vec::new();
let run_point = match core.encodes_again() || crate::replay::is_replaying() {
true => None,
false => Some(core.command_buffer().state().run_point()),
};
// Where a draw pinned the pass's colors to their own images and stand-ins arrived after
// it (`render/snapshot.rs`): the count of the instances through the last pinned one, which
// render the attachments themselves. Every stand-in arrived after them, as the pass held
// none at a pin: each takes its attachment's texels after the last of them, as after the
// instances recorded inline (`render/inline_first.rs`), and is merged back, reloaded or
// copied back after them alone; and no run of passes takes the pass (`pass_runs.rs`).
let pinned = (inline && pinned_through > inlined)
.then_some(pinned_through)
.filter(|_| layout.colors.iter().flatten().any(|c| c.stand_in.is_some()));
if let Some(through) = pinned {
reload_at.retain(|&at| at >= through);
core.device().shared().counts.stand_ins_after_pin();
}
let run_point =
match core.encodes_again() || crate::replay::is_replaying() || pinned.is_some() {
true => None,
false => Some(core.command_buffer().state().run_point()),
};
if let Some(now) = run_point {
// A quiet pass touches nothing but what its commands name and its attachments: no
// command reaches memory it does not name, nor a heap; no draw or tile dispatch
@@ -5133,11 +5160,14 @@ impl RenderLowering {
};
copied_in.extend(depth_stencil_copies(false));
let stand_ins_in = StandInCopies::plan_aspects(&copied_in, true)?;
let (stand_ins_in, stand_ins_after_first) = match inline {
true => (None, stand_ins_in),
false => (stand_ins_in, None),
// Where a draw pinned the colors, after the last pinned instance (`pinned`), the merged
// colors' keeps after their copies.
let (stand_ins_in, stand_ins_after_first, stand_ins_after_pins) = match (inline, pinned) {
(true, Some(_)) => (None, None, stand_ins_in),
(true, None) => (None, stand_ins_in, None),
(false, _) => (stand_ins_in, None, None),
};
if let Some(copies) = &stand_ins_after_first {
for copies in stand_ins_after_first.iter().chain(&stand_ins_after_pins) {
uses.extend(copies.uses().iter().cloned());
}
// A memoryless color's backing, arriving later, where the first instance recorded inline
@@ -5258,6 +5288,21 @@ impl RenderLowering {
depth_stencil: None,
..layout.clone()
});
// The instances through the last pinned one render each color's own image, and no hidden
// depth or stencil, which arrived after them where it did (`pinned`).
let fixed = pinned.map(|_| {
let mut fixed = PassLayout {
depth_stencil: None,
..layout.clone()
};
for color in fixed.colors.iter_mut().flatten() {
if let Some(own) = color.stand_in.as_ref().map(|s| s.own.clone()) {
color.target = own;
color.stand_in = None;
}
}
fixed
});
// The layout of the instances that resolve: the scratch image as the depth/stencil
// attachment where its copy stands for it.
let resolving_layout = resolve_source
@@ -5555,10 +5600,17 @@ impl RenderLowering {
copies.record(&mut core);
}
// What the merged colors hold once copied in, before any step writes them: kept by a
// run's first pass alone.
// run's first pass alone; where a draw pinned the colors, after their copies in after the
// last pinned instance.
let mut kept_after_pins = Vec::new();
for (index, merge) in &merged {
if !goes_on(*index) {
merge.record_keep(&mut core);
match (goes_on(*index), pinned) {
(true, _) => {}
(false, Some(_)) => {
uses.extend(merge.keep_uses().iter().cloned());
kept_after_pins.push(Arc::clone(merge));
}
(false, None) => merge.record_keep(&mut core),
}
}
if let Some(clears) = reach_clears {
@@ -5639,7 +5691,11 @@ impl RenderLowering {
first: index == 0,
last: index + 1 == count && !resolve_after,
};
let own = instance_layout(&layout, bare.as_ref(), &instance.shape);
// An instance through the last pinned one renders the attachments themselves.
let own = match (&fixed, pinned) {
(Some(fixed), Some(through)) if index < through => fixed,
_ => instance_layout(&layout, bare.as_ref(), &instance.shape),
};
let feedback = instance.feedback;
// Its framebuffer holds the views its draws render colors through.
let viewed = reformatted(own, &instance.reformats);
@@ -5778,6 +5834,11 @@ impl RenderLowering {
device: device.clone(),
sets: Default::default(),
},
after_pins: pinned.map(|through| AfterPins {
at: through - 1,
copies: stand_ins_after_pins,
keeps: kept_after_pins,
}),
};
// An inline first instance's steps before it go before the pass, into the command buffer
// before the pass's, as the end records them before the pass's first instance; the
@@ -6482,7 +6543,7 @@ impl RenderLowering {
/// not fetch input attachments renders it in place where its texture is not memoryless and its
/// image has `STORAGE` and takes the storage view, and through a stand-in for the whole pass
/// otherwise (`next_instance`), which a draw read through a snapshot of the texture would not
/// see (`render/snapshot.rs`).
/// see but where it pins the color (`render/snapshot.rs`).
fn keeps_own_attachment(&self, index: usize) -> bool {
let Some(color) = self.layout.colors.get(index).and_then(Option::as_ref) else {
return false;
@@ -6941,6 +7002,9 @@ impl RenderLowering {
cause: Split,
) {
if let Some(layout) = stood {
// What a stand-in brings after a pin, a later draw cannot pin past
// (`render/snapshot.rs`).
self.pins_frozen |= self.pinned_through > 0;
*self.layout = *layout;
self.kept_attachments = None;
}
@@ -10075,7 +10139,19 @@ impl RenderLowering {
} else {
Split::Shape
};
// A draw that pins its colors to their own images brings nothing to the pass's layout
// (`snapshot_wanted`): its instance and those before it render them.
let pins = snapshot.as_ref().is_some_and(|wanted| wanted.pins != 0);
if pins && stood.is_some() {
return Err(internal(
"a stand-in arriving with a draw that pins its colors",
));
}
self.install(next, stood, continuation, cause);
if pins {
self.pinned_through = self.earlier.len() + 1;
device.shared().counts.reading_draw_pinned();
}
self.current.feedback.0 |= feedback.0;
self.current.storage_colors |= storage_colors;
if let Some(begin) = inline {
@@ -2573,6 +2573,10 @@ impl RenderExecution {
// No pass of several color groups executes render commands
// (`render/color_groups.rs`).
grouped: None,
// The commands' draws pin no color: no instance of theirs records inline
// (`render/snapshot.rs`).
pinned_through: 0,
pins_frozen: false,
}
}
@@ -109,7 +109,8 @@
//! - **A stand-in that arrives later** (a fetched attachment whose image lacks the usage the
//! fetch needs) stands in from the next instance on: the end copies each attachment into its
//! stand-in right after the inline instance, which rendered the attachment itself, not before
//! the pass, and back after the last as before.
//! the pass, and back after the last as before; after the last instance a draw pinned to the
//! attachments' own images, where one did (`render/snapshot.rs`).
//! - **Counted**: `WorkCounts::inline_passes` (passes whose first instance recorded inline) and
//! `WorkCounts::inline_passes_split` (those of more than one instance), and
//! `WorkCounts::inline_split_instances` (`render/inline_splits.rs`); the passes whose first
@@ -39,6 +39,7 @@ use crate::attachment_stand_in::StandInCopies;
use crate::depth_stand_in::StandInCopies as DepthStandInCopies;
use crate::device::functions::Vk;
use crate::device::lock;
use crate::linear_merge::LinearMerge;
use crate::owned_kernel::OwnedSets;
use crate::pipeline::RawPipeline;
use crate::render_target::{self, ClearValues, FramebufferObject, MovedImage, RenderPassObject};
@@ -133,6 +134,19 @@ pub(super) struct PassSteps {
pub(super) clear_values: ClearValues,
pub(super) render_area: vk::Rect2D,
pub(super) staged_rows: StagedRows,
/// Where a draw pinned the pass's colors to their own images and stand-ins arrived after
/// it (`render/snapshot.rs`): what goes after the last pinned instance.
pub(super) after_pins: Option<AfterPins>,
}
/// The steps after a pass's last pinned instance (`render/snapshot.rs`): the stand-ins' copies
/// of their attachments' texels, which the pinned instances rendered, and then the keeps of those
/// merged back into a buffer's bytes (`linear_merge.rs`).
pub(super) struct AfterPins {
/// The last pinned instance.
pub(super) at: usize,
pub(super) copies: Option<StandInCopies>,
pub(super) keeps: Vec<Arc<LinearMerge>>,
}
impl PassSteps {
@@ -295,6 +309,14 @@ impl PassSteps {
if let Some(copies) = self.stand_in_copies.as_ref().filter(|_| tests) {
copies.record_out(raw, command_buffer);
}
if let Some(pins) = self.after_pins.as_ref().filter(|pins| pins.at == index) {
if let Some(copies) = &pins.copies {
copies.record_in(raw, command_buffer);
}
for merge in &pins.keeps {
merge.keep_in_pass(raw, command_buffer);
}
}
}
}
@@ -79,8 +79,8 @@
//! through a view of another format, and which no later fetch can render through a stand-in
//! (`RenderCommandEncoder::keeps_own_attachment`: its image has `STORAGE`, which a texture of
//! the runtime's own without it, its device laying it out otherwise with it, takes at a later
//! commit where it may, noted at its reader's split, `texture/storage_form.rs`, so its later
//! passes' readers take the snapshot), no two of the colors of one image (whose
//! commit where it may, noted at its reader's draw, `texture/storage_form.rs`) or which the draw
//! pins (below), no two of the colors of one image (whose
//! snapshot is one); the draw costs no more so than the split would
//! (`RenderCommandEncoder::snapshot_cheaper`: at any area where every such color is a texture
//! whose image lies over its buffer's bytes, `RenderCommandEncoder::over_bytes`; else its
@@ -98,19 +98,40 @@
//! (`WorkCounts::snapshot_inline_splits` counts the first cause). After it, an execution of
//! render commands, and a draw that binds such a color's image as a storage image, record into
//! another instance: the feedback loop layout serves neither.
//! - **Pins.** A fetch of a color in the pixel interlock reads and writes its image as a storage
//! image, so a later fetch of a color whose image lacks `STORAGE` renders it through a stand-in
//! (`attachment_stand_in.rs`), which the pass's end puts in place for the whole pass, copied in
//! before it: a snapshot draw before the fetch would have read the texture's own image, which
//! the pass no longer rendered. A draw reads such a color through a snapshot all the same where
//! it can pin it (`RenderCommandEncoder::pins_own_attachment`): where nothing the pass's end
//! decides from the whole pass changes what its instances so far render, and nothing arrives
//! with the draw (the pass's first instance recorded inline, which ran its load actions itself,
//! `render/inline_first.rs`; no stand-in, memoryless color or depth/stencil attachment, every
//! color stored `Store`, no tile dispatch, execution, color groups or extended-range shadow; a
//! draw that fetches nothing and needs no hidden depth or stencil). Its instance and those
//! before it render each color's own image (`RenderLowering::pinned_through`), and a stand-in
//! arriving after them takes its attachment's texels after the last of them, as after an
//! instance recorded inline: the pass's end renders those instances through the colors' own
//! images, records each stand-in's copy in after them, the keep of one merged back into a
//! buffer's bytes after that (`linear_merge.rs`), and the reloads after a barrier after them
//! alone, and no run of passes takes the pass (`pass_runs.rs`). Once a stand-in or the hidden
//! depth and stencil arrived after a pin, no later draw pins (`RenderLowering::pins_frozen`):
//! its reader splits.
//! - **Counted**: `WorkCounts::reading_draws_snapshotted`, and of them
//! `WorkCounts::snapshot_inline_splits`. With `METAL2VULKAN_LOG_PIPELINES` set,
//! `WorkCounts::snapshot_inline_splits` and `WorkCounts::reading_draws_pinned`; the passes whose
//! stand-ins arrived after a pin, `WorkCounts::stand_ins_after_pins`. With `METAL2VULKAN_LOG_PIPELINES` set,
//! the first draw of each reason a draw took the split says so, once per device
//! (`metal2vulkan-snapshot-fallback`), and the draws the area rule weighed are counted by their
//! share of their colors' pixels and texel bytes, a line at 64 of them, each power of two
//! after, and as the device ends (`metal2vulkan-snapshot-readers`, `reader_sizes.rs`).
use super::{PlanFacts, Reformat, RenderLowering};
use super::{inline_first, PlanFacts, Reformat, RenderLowering};
use crate::copy_plan::block_bytes;
use crate::dynamic_state::ColorWriteMasks;
use crate::pipeline::{GraphicsState as DrawingState, Settled};
use crate::render_state::MAX_VIEWPORTS;
use crate::render_target::{self, Feedback};
use crate::render_values::StoreAction;
use crate::texture::Texture;
use ash::vk;
use metal2vulkan::bind::{BindingPlan, ImageSource, PushHole, WriteSource};
@@ -123,6 +144,9 @@ use std::collections::BTreeSet;
pub(super) struct Wanted {
pub(super) slots: BTreeSet<u32>,
pub(super) feedback: Feedback,
/// The colors among them that no later fetch would keep in their own images, which the
/// draw pins to them ([`RenderLowering::pins_own_attachment`]).
pub(super) pins: u32,
}
/// The form `plan` keeps fragment texture slot `slot`'s snapshot in
@@ -316,17 +340,21 @@ impl RenderLowering {
.filter(|&i| wanted.feedback.has(i))
.collect();
for &index in &colors {
if !self.keeps_own_attachment(index) {
// A texture of the runtime's own whose image lacks `STORAGE` (the device lays it
// out otherwise with it) takes its storage form at a later commit, where it may
// (`texture/storage_form.rs`): its later passes' readers take the snapshot.
if let Some(color) = self.layout.colors.get(index).and_then(Option::as_ref) {
color.target.texture.want_storage_form();
}
if self.keeps_own_attachment(index) {
continue;
}
// A texture of the runtime's own whose image lacks `STORAGE` (the device lays it
// out otherwise with it) takes its storage form at a later commit, where it may
// (`texture/storage_form.rs`): its later passes' readers need no pin.
if let Some(color) = self.layout.colors.get(index).and_then(Option::as_ref) {
color.target.texture.want_storage_form();
}
if !self.pins_own_attachment(pipeline, index) {
return self.snapshot_fallback(
"a framebuffer fetch of the attachment would render it through a stand-in",
);
}
wanted.pins |= 1 << index;
}
// A texture's snapshot is its image's (`Texture::snapshot_texels`): two colors of one
// image would copy their texels into one snapshot.
@@ -350,6 +378,44 @@ impl RenderLowering {
Some(wanted)
}
/// Whether the draw of `pipeline` reads the pass's color `index`, whose own image a later
/// fetch would not keep (`keeps_own_attachment`), through a snapshot of that image all the
/// same, pinning it (the module docs): where nothing the pass's end decides from the whole
/// pass changes what its instances through the draw's render, and nothing arrives with the
/// draw. So: the pass's first instance recorded inline, which ran the pass's load actions
/// itself (`render/inline_first.rs`); nothing arrived since an earlier pin
/// (`pins_frozen`); no stand-in, memoryless color or depth/stencil attachment in the pass,
/// hidden or not, every color stored `Store` (which no later call changes: so no texture over
/// a buffer renders through an image it keeps, `kept_bytes.rs`), and no tile dispatch,
/// execution of render commands, color groups or extended-range shadow that records an
/// instance's draws again; a draw that fetches no color and whose state needs no hidden
/// depth or stencil; and the color a 2D one.
pub(super) fn pins_own_attachment(&self, pipeline: &DrawingState, index: usize) -> bool {
let Some(color) = self.layout.colors.get(index).and_then(Option::as_ref) else {
return false;
};
let graphics = &pipeline.base().graphics;
let (depth, stencil) = self.layout.aspects();
let plain = |c: &crate::render_pass::ColorTarget| {
c.stand_in.is_none()
&& !c.memoryless
&& !super::memoryless(&c.target)
&& c.store == StoreAction::Store
};
matches!(self.inline, inline_first::Inline::Begun(_))
&& !self.pins_frozen
&& self.grouped.is_none()
&& self.dispatches.is_empty()
&& self.executions.is_empty()
&& !self.extended.keeps_draws()
&& self.layout.depth_stencil.is_none()
&& self.layout.colors.iter().flatten().all(plain)
&& graphics.storage_attachments.is_empty()
&& graphics.input_attachments.is_empty()
&& !self.state.needs_hidden(depth, stencil)
&& !crate::render_pass::not_2d(&color.target)
}
/// Whether a draw of `pipeline` that reads the pass's `colors` through snapshots costs no
/// more than the split would: at any area over a buffer's bytes
/// ([`over_bytes`](Self::over_bytes)), else by [`snapshot_weights`](Self::snapshot_weights);
@@ -1,23 +1,32 @@
//! A private render target read at its own pixels after a memory barrier, whose image lacks
//! `STORAGE` (`DeviceShared::storage_costs_forced`: the device lays it out otherwise with it, as
//! ANV lays out an optimal `BGRA8Unorm` image), takes its storage form at the commit of its first
//! such pass (`render/snapshot.rs`, `texture/storage_form.rs`): that pass's reader splits it, as a
//! later fetch would render it through a stand-in its snapshot does not see, and every later
//! pass's reader takes the snapshot, on a device that takes the path. Elsewhere every reader
//! splits and nothing swaps. Each pass, a command buffer of its own over the `BGRA8Unorm` target,
//! fills the block [`BLOCK`] with a red of its own, then after a barrier draws the block through
//! its scissor with `tob_read`, each fragment writing the texel it read: the pass's own red at
//! every pixel of the block, as Metal orders the barrier, where a read of the copy from before
//! the pass would write the red before it.
//! ANV lays out an optimal `BGRA8Unorm` image), on a device that takes the snapshot path
//! (`render/snapshot.rs`): its first such pass's reader takes the snapshot pinned to the target's
//! own image, which a later fetch would otherwise render through a stand-in the snapshot does not
//! see, and the target takes its storage form at that pass's commit where the device makes one
//! (`texture/storage_form.rs`), so every later pass's reader takes the snapshot unpinned. Elsewhere
//! every reader splits and nothing swaps. Each pass, a command buffer of its own over the
//! `BGRA8Unorm` target, fills the block [`BLOCK`] with a red of its own, then after a barrier draws
//! the block through its scissor with `tob_read`, each fragment writing the texel it read: the
//! pass's own red at every pixel of the block, as Metal orders the barrier, where a read of the
//! copy from before the pass would write the red before it.
//!
//! The fill's and the reader's pipelines are made first, by the same pass over an untracked
//! target (which never takes its storage form): a draw whose `VkPipeline` the device's pool is
//! still making is recorded by a host step, and its command buffer takes no switch.
//! A pass whose reader pinned the target and that then fetches the target (`fetch_ordered` over
//! [`FETCHED`], halving its red) renders it through a stand-in from the fetch on: the stand-in
//! takes the target's texels after the reader's instance (`WorkCounts::stand_ins_after_pins`),
//! so the reader's pixels outside the fetch keep the pass's red, and those inside it hold half of
//! it, where a stand-in for the whole pass would leave the reader's snapshot the red before the
//! pass.
//!
//! The pipelines are made first, by the same passes over an untracked target (which never takes
//! its storage form): a draw whose `VkPipeline` the device's pool is still making is recorded by
//! a host step, and its command buffer takes no switch.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are `tob_rect`,
//! `tob_solid` and `tob_read` of the owned fixture
//! `validation/fixtures/public/engine/tob_renders.ll` (`llvm-as`).
//! `validation/fixtures/public/engine/tob_renders.ll`, and `fetch_ordered` of
//! `validation/fixtures/public/engine/fragment_fetch.ll` (`llvm-as`).
use super::blit_holds::{device, Scratch, WAIT};
use super::encoder_holds::{bytes_of, library};
@@ -44,6 +53,10 @@ const FORMAT: PixelFormat = PixelFormat::BGRA8Unorm;
/// (`RenderCommandEncoder::snapshot_cheaper`).
const BLOCK: [u64; 4] = [8, 8, 16, 16];
/// The block a fetching draw halves the red of, `[x0, y0, x1, y1]`: over a quarter of
/// [`BLOCK`] and past it.
const FETCHED: [u64; 4] = [12, 4, 24, 12];
/// The red the first pass clears the target to.
const CLEARED: u8 = 20;
@@ -55,19 +68,27 @@ fn red_of(pass: u8) -> u8 {
60 + 50 * pass
}
/// The fixture's state of `tob_rect` and `fragment`, into a color of [`FORMAT`].
fn state(device: &Device, fragment: &str) -> RenderPipelineState {
let library = library(device, "engine/tob_renders.ll");
let function = |name: &str| {
let function = library.new_function_with_name(name).unwrap();
/// The state of `tob_rect` and the fixture `fixture`'s `fragment`, into a color of [`FORMAT`],
/// where the device makes it.
fn state_of(
device: &Device,
fixture: &str,
fragment: &str,
) -> Result<RenderPipelineState, crate::Error> {
let function = |path: &str, name: &str| {
let function = library(device, path).new_function_with_name(name).unwrap();
StageSource::Function(function.function_descriptor())
};
let mut descriptor = RenderPipelineDescriptor::new(function("tob_rect"));
descriptor.fragment = Some(function(fragment));
let vertex = function("engine/tob_renders.ll", "tob_rect");
let mut descriptor = RenderPipelineDescriptor::new(vertex);
descriptor.fragment = Some(function(fixture, fragment));
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(FORMAT));
device
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap()
device.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
}
/// The state of `tob_rect` and `tob_renders.ll`'s `fragment`, into a color of [`FORMAT`].
fn state(device: &Device, fragment: &str) -> RenderPipelineState {
state_of(device, "engine/tob_renders.ll", fragment).unwrap()
}
/// A private [`FORMAT`] render target that shaders read, its hazards tracked where `tracked`.
@@ -92,12 +113,27 @@ fn corners([x0, y0, x1, y1]: [u64; 4]) -> Vec<u8> {
bytes_of(&[x(x0), y(y1), x(x1), y(y0)], f32::to_le_bytes)
}
/// Pass `pass` over `target` in a command buffer of its own, committed and completed: the
/// target's red at each pixel after it, and the device's work counts as it completed.
/// The scissor rectangle of the target's pixels `[x0, x1) x [y0, y1)`.
fn scissor([x0, y0, x1, y1]: [u64; 4]) -> ScissorRect {
ScissorRect {
x: x0,
y: y0,
width: x1 - x0,
height: y1 - y0,
}
}
/// Pass `pass` over `target` in a command buffer of its own, committed and completed, a draw of
/// `fetch` over [`FETCHED`] after the reader where it is given: the target's red at each pixel
/// after it, and the device's work counts as it completed.
fn pass_over(
queue: &CommandQueue,
target: &Texture,
(fill, read): (&RenderPipelineState, &RenderPipelineState),
(fill, read, fetch): (
&RenderPipelineState,
&RenderPipelineState,
Option<&RenderPipelineState>,
),
pass: u8,
) -> (Vec<u8>, WorkCounts) {
let device = queue.device();
@@ -124,17 +160,16 @@ fn pass_over(
(encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap();
let fragment = RenderStages::FRAGMENT;
encoder.memory_barrier_with_scope(BarrierScope::RENDER_TARGETS, fragment, fragment);
let [x0, y0, x1, y1] = BLOCK;
let scissor = ScissorRect {
x: x0,
y: y0,
width: x1 - x0,
height: y1 - y0,
};
encoder.set_scissor_rect(scissor).unwrap();
encoder.set_scissor_rect(scissor(BLOCK)).unwrap();
encoder.set_render_pipeline_state(read).unwrap();
encoder.set_fragment_texture(Some(target), 0).unwrap();
(encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap();
if let Some(fetch) = fetch {
encoder.set_scissor_rect(scissor(FETCHED)).unwrap();
encoder.set_render_pipeline_state(fetch).unwrap();
encoder.set_vertex_bytes(&corners(FETCHED), 0).unwrap();
(encoder.draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0)).unwrap();
}
encoder.end_encoding().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
(blit.copy_from_texture_to_buffer(
@@ -169,8 +204,59 @@ fn settled(device: &Device) {
}
}
/// The device's answers for a target of [`target`]'s whose image lacks `STORAGE`: whether it
/// takes the snapshot path (`render/snapshot.rs`: the snapshot draws' features, and a fetch in the
/// pixel interlock, as a pass that fetches through input attachments takes no snapshot), and
/// whether the target then takes its storage form (`texture/storage_form.rs`).
fn snapshots(device: &Device, target: &Texture) -> (bool, bool) {
let profile = device.compile_device().profile();
let plan = target.image_plan().unwrap().clone();
assert!(
!plan.usage.contains(ImageUsageFlags::STORAGE),
"the target's image lacks STORAGE"
);
let snapshots = device.shared().color_write_masks.is_some() && through_storage(profile);
let forms = snapshots && storage_candidate(&plan, profile).is_some();
let feedback = plan
.usage
.contains(ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT);
eprintln!(
"SELF-READ-STORAGE {}: snapshots {snapshots}, storage forms {forms}, feedback {feedback}",
device.name()
);
(snapshots, forms)
}
/// What pass `pass` moved of the counts between `before` and `after`: its splits, readers through
/// snapshots, those pinned, passes whose stand-ins arrived after a pin, and storage forms taken.
fn counts_moved(before: &WorkCounts, after: &WorkCounts) -> [u64; 5] {
[
after.attachment_read_splits - before.attachment_read_splits,
after.reading_draws_snapshotted - before.reading_draws_snapshotted,
after.reading_draws_pinned - before.reading_draws_pinned,
after.stand_ins_after_pins - before.stand_ins_after_pins,
after.storage_forms_taken - before.storage_forms_taken,
]
}
/// The red `fetched` passes leave at `(x, y)` of a target cleared to [`CLEARED`]: the last pass's
/// red inside [`BLOCK`], halved inside [`FETCHED`] by each pass that fetched.
fn red_after(pass: u8, fetched: bool, x: u64, y: u64) -> u8 {
let within = |[x0, y0, x1, y1]: [u64; 4]| (x0..x1).contains(&x) && (y0..y1).contains(&y);
let mut red = CLEARED;
for at in 0..=pass {
if within(BLOCK) {
red = red_of(at);
}
if fetched && within(FETCHED) {
red /= 2;
}
}
red
}
#[test]
fn a_private_targets_readers_take_the_snapshot_once_it_took_its_storage_form() {
fn a_private_targets_readers_take_the_snapshot_pinned_until_it_takes_its_storage_form() {
let cache = Scratch::new("self-read-storage");
let device = device(&cache.0);
device
@@ -178,61 +264,49 @@ fn a_private_targets_readers_take_the_snapshot_once_it_took_its_storage_form() {
.storage_costs_forced
.store(true, Ordering::Relaxed);
let queue = device.new_command_queue().unwrap();
let states = (&state(&device, "tob_solid"), &state(&device, "tob_read"));
let states = (
&state(&device, "tob_solid"),
&state(&device, "tob_read"),
None,
);
let warm = target(&device, false);
for pass in 0..2 {
pass_over(&queue, &warm, states, pass);
}
settled(&device);
let target = target(&device, true);
let profile = device.compile_device().profile();
let plan = target.image_plan().unwrap().clone();
assert!(
!plan.usage.contains(ImageUsageFlags::STORAGE),
"the target's image lacks STORAGE"
);
// A device that takes the snapshot path (`render/snapshot.rs`) for an image of the target's
// that has `STORAGE`, as the storage form gives it where the device makes one.
let takes = device.shared().color_write_masks.is_some()
&& through_storage(profile)
&& storage_candidate(&plan, profile).is_some();
let feedback = plan
.usage
.contains(ImageUsageFlags::ATTACHMENT_FEEDBACK_LOOP_EXT);
eprintln!(
"SELF-READ-STORAGE {}: takes {takes}, feedback {feedback}",
device.name()
);
let (snapshots, forms) = snapshots(&device, &target);
let mut before = device.work_counts();
for pass in 0..PASSES {
let pooled = before.pipelines_pooled;
let (reds, after) = pass_over(&queue, &target, states, pass);
let moved = (
after.attachment_read_splits - before.attachment_read_splits,
after.reading_draws_snapshotted - before.reading_draws_snapshotted,
after.storage_forms_taken - before.storage_forms_taken,
);
let moved = counts_moved(&before, &after);
eprintln!(
"SELF-READ-STORAGE pass {pass}: (splits, snapshotted, storage forms) {moved:?}, \
pipelines pooled {}",
after.pipelines_pooled - pooled
"SELF-READ-STORAGE pass {pass}: (splits, snapshotted, pinned, stand-ins after pins, \
storage forms) {moved:?}, pipelines pooled {}, inline passes {}",
after.pipelines_pooled - pooled,
after.inline_passes - before.inline_passes
);
let [x0, y0, x1, y1] = BLOCK;
for (i, &red) in reds.iter().enumerate() {
let (x, y) = (i as u64 % SIDE, i as u64 / SIDE);
let inside = (x0..x1).contains(&x) && (y0..y1).contains(&y);
let want = if inside { red_of(pass) } else { CLEARED };
assert_eq!(red, want, "pass {pass}: pixel ({x}, {y})");
assert_eq!(
red,
red_after(pass, false, x, y),
"pass {pass}: pixel ({x}, {y})"
);
}
let want = match (takes, pass) {
(true, 0) => (1, 0, 1),
(true, _) => (0, 1, 0),
(false, _) => (1, 0, 0),
// The first pass's reader pins the target, which takes its storage form at its commit
// where the device makes one; a later pass's reader pins it where it took none.
let want = match (snapshots, pass) {
(true, 0) => [0, 1, 1, 0, u64::from(forms)],
(true, _) => [0, 1, u64::from(!forms), 0, 0],
(false, _) => [1, 0, 0, 0, 0],
};
assert_eq!(
moved,
want,
"pass {pass} on {}: splits, readers through snapshots, storage forms taken",
"pass {pass} on {}: splits, readers through snapshots, pinned, stand-ins after \
pins, storage forms taken",
device.name()
);
before = after;
@@ -240,7 +314,80 @@ fn a_private_targets_readers_take_the_snapshot_once_it_took_its_storage_form() {
let image = target.image_plan().unwrap();
assert_eq!(
image.usage.contains(ImageUsageFlags::STORAGE),
takes,
forms,
"the target's image has STORAGE after its passes"
);
}
#[test]
fn a_fetch_after_a_pinned_reader_renders_through_a_stand_in_from_the_fetch_on() {
let cache = Scratch::new("self-read-pinned-fetch");
let device = device(&cache.0);
device
.shared()
.storage_costs_forced
.store(true, Ordering::Relaxed);
let queue = device.new_command_queue().unwrap();
let fetch = match state_of(&device, "engine/fragment_fetch.ll", "fetch_ordered") {
Ok(fetch) => fetch,
Err(error) => {
eprintln!(
"SELF-READ-PINNED-FETCH {}: no framebuffer fetch on this device: {error}",
device.name()
);
return;
}
};
let states = (
&state(&device, "tob_solid"),
&state(&device, "tob_read"),
Some(&fetch),
);
let warm = target(&device, false);
for pass in 0..2 {
pass_over(&queue, &warm, states, pass);
}
settled(&device);
let target = target(&device, true);
let (snapshots, forms) = snapshots(&device, &target);
let mut before = device.work_counts();
for pass in 0..2 {
let (reds, after) = pass_over(&queue, &target, states, pass);
let moved = counts_moved(&before, &after);
eprintln!(
"SELF-READ-PINNED-FETCH pass {pass}: (splits, snapshotted, pinned, stand-ins after \
pins, storage forms) {moved:?}, inline passes {}",
after.inline_passes - before.inline_passes
);
for (i, &red) in reds.iter().enumerate() {
let (x, y) = (i as u64 % SIDE, i as u64 / SIDE);
assert_eq!(
red,
red_after(pass, true, x, y),
"pass {pass}: pixel ({x}, {y})"
);
}
// The first pass's reader pins the target and its fetch takes the stand-in after the
// reader's instance; a later pass's fetch renders the target in place where it took its
// storage form.
let pinned = pass == 0 || !forms;
let want = match snapshots {
true => [
0,
1,
u64::from(pinned),
u64::from(pinned),
u64::from(pass == 0 && forms),
],
false => [1, 0, 0, 0, 0],
};
assert_eq!(
moved,
want,
"pass {pass} on {}: splits, readers through snapshots, pinned, stand-ins after \
pins, storage forms taken",
device.name()
);
before = after;
}
}
@@ -470,6 +470,8 @@ pub(crate) struct Counters {
attachment_read_clears: AtomicU64,
reading_draws_snapshotted: AtomicU64,
snapshot_inline_splits: AtomicU64,
reading_draws_pinned: AtomicU64,
stand_ins_after_pins: AtomicU64,
feedback_loop_alias_images: AtomicU64,
feedback_loop_shadow_images: AtomicU64,
depth_attachments_moved: AtomicU64,
@@ -3432,6 +3434,18 @@ impl Counters {
self.snapshot_inline_splits.fetch_add(1, Ordering::Relaxed);
}
/// A draw read through a snapshot a color whose image a later fetch would render through a
/// stand-in, its instance pinned to the color's own image (`render/snapshot.rs`).
pub(crate) fn reading_draw_pinned(&self) {
self.reading_draws_pinned.fetch_add(1, Ordering::Relaxed);
}
/// A pass's stand-ins arrived after its pinned instances, and took the attachments' texels
/// after the last of them (`render/snapshot.rs`).
pub(crate) fn stand_ins_after_pin(&self) {
self.stand_ins_after_pins.fetch_add(1, Ordering::Relaxed);
}
/// The device made a linear image aliasing a buffer's bytes with feedback loop usage
/// (`Device::storage_over_buffer`, `texture::feedback_candidate`).
pub(crate) fn feedback_loop_alias_image(&self) {
@@ -6515,6 +6529,16 @@ pub struct WorkCounts {
/// was recorded inline, its render pass instance begun without the feedback loop layout the
/// snapshot needs (`render/snapshot.rs`, `render/inline_first.rs`).
pub snapshot_inline_splits: u64,
/// Of `reading_draws_snapshotted`, the draws that read a color whose image lacks the
/// `STORAGE` a later framebuffer fetch of it in the interlock would need, so that a fetch would
/// render it through a stand-in for the whole pass: each pins its instance, and those before
/// it, to the color's own image (`render/snapshot.rs`).
pub reading_draws_pinned: u64,
/// Passes whose stand-ins arrived after a pinned instance (`reading_draws_pinned`): the
/// instances through the last pinned one rendered the attachments themselves, and each
/// stand-in took its attachment's texels after them, not before the pass
/// (`render/snapshot.rs`).
pub stand_ins_after_pins: u64,
/// Linear images aliasing a buffer's bytes (a texture over a buffer, a no-copy buffer or an
/// IOSurface plane) that the device made with feedback loop usage
/// (`texture::feedback_candidate`), so a draw may read the texture through a snapshot while
@@ -7410,6 +7434,8 @@ impl Device {
attachment_read_clears: counters.attachment_read_clears.load(Ordering::Relaxed),
reading_draws_snapshotted: counters.reading_draws_snapshotted.load(Ordering::Relaxed),
snapshot_inline_splits: counters.snapshot_inline_splits.load(Ordering::Relaxed),
reading_draws_pinned: counters.reading_draws_pinned.load(Ordering::Relaxed),
stand_ins_after_pins: counters.stand_ins_after_pins.load(Ordering::Relaxed),
feedback_loop_alias_images: counters.feedback_loop_alias_images.load(Ordering::Relaxed),
feedback_loop_shadow_images: counters
.feedback_loop_shadow_images
@@ -51,8 +51,9 @@
//! memory barrier over the render targets and a draw over the same rectangle that reads the target
//! at its own pixels (`tob_read`), through no scissor; each target also without the barriers and
//! readers, the baseline. Printed per case (`SELF-READ-COST`): the GPU time per frame, and per
//! frame the splits, snapshots, render pass instances begun, shadow copies, texels copied in
//! (and of them those of a surface's shadow copied in again), keeps and their texels, merges, the
//! frame the splits, snapshots (and of them those pinned to the target's own image,
//! `WorkCounts::reading_draws_pinned`), render pass instances begun, shadow copies, texels copied
//! in (and of them those of a surface's shadow copied in again), keeps and their texels, merges, the
//! shadows made of render targets over host pages and the textures in place over them (once the
//! device's in-place check answered, each line and its time printed, `SELF-READ-CHECK`), and the
//! images made with feedback loop usage.
@@ -994,8 +995,9 @@ fn self_reads_on(device: &Device, policy: HostPageTexturePolicy) {
println!(
"SELF-READ-COST {name} {kind} {width}x{height} rows of {row} bytes {} pairs {} \
{}x{}: GPU {:.3} ms/frame (median); per frame: splits {:.2}, snapshotted \
{:.2}, instances {:.2}, shadow copies {:.2}, bounded {:.2}, texels copied in \
{:.0}, of a surface again {:.0}, keeps {:.2}, texels kept {:.0}, merges {:.2}; \
{:.2}, pinned {:.2}, instances {:.2}, shadow copies {:.2}, bounded {:.2}, texels \
copied in {:.0}, of a surface again {:.0}, keeps {:.2}, texels kept {:.0}, \
merges {:.2}; \
render-target shadows over host pages {}, textures in place over host pages \
{}, images made with feedback loop usage: shadows {}, aliases {}",
SELF_PAIRS,
@@ -1008,6 +1010,7 @@ fn self_reads_on(device: &Device, policy: HostPageTexturePolicy) {
before.reading_draws_snapshotted,
after.reading_draws_snapshotted
),
per(before.reading_draws_pinned, after.reading_draws_pinned),
per(
before.render_passes_begun_instances,
after.render_passes_begun_instances
@@ -2926,6 +2926,7 @@ field metal2vulkan-runtime::WorkCounts.queue_switch_checks_recalled pub queue_sw
field metal2vulkan-runtime::WorkCounts.queue_switch_checks_run pub queue_switch_checks_run: u64
field metal2vulkan-runtime::WorkCounts.queues_gone_long pub queues_gone_long: u64
field metal2vulkan-runtime::WorkCounts.queues_sharing_a_vk_queue pub queues_sharing_a_vk_queue: u64
field metal2vulkan-runtime::WorkCounts.reading_draws_pinned pub reading_draws_pinned: u64
field metal2vulkan-runtime::WorkCounts.reading_draws_snapshotted pub reading_draws_snapshotted: u64
field metal2vulkan-runtime::WorkCounts.reencodes_refused pub reencodes_refused: u64
field metal2vulkan-runtime::WorkCounts.registrations_waited pub registrations_waited: u64
@@ -3093,6 +3094,7 @@ field metal2vulkan-runtime::WorkCounts.stamped_buffers_reused pub stamped_buffer
field metal2vulkan-runtime::WorkCounts.stand_in_bytes pub stand_in_bytes: u64
field metal2vulkan-runtime::WorkCounts.stand_in_copies_made pub stand_in_copies_made: u64
field metal2vulkan-runtime::WorkCounts.stand_in_copies_made_at_draws pub stand_in_copies_made_at_draws: u64
field metal2vulkan-runtime::WorkCounts.stand_ins_after_pins pub stand_ins_after_pins: u64
field metal2vulkan-runtime::WorkCounts.stand_ins_made pub stand_ins_made: u64
field metal2vulkan-runtime::WorkCounts.storage_forms_taken pub storage_forms_taken: u64
field metal2vulkan-runtime::WorkCounts.storage_placeholder_attachments pub storage_placeholder_attachments: u64
Can't render this file because it is too large.