Take the storage form for a private target whose self-read splits for want of STORAGE

A draw that reads its pass's color attachment at its own pixels after a render-target barrier
takes the snapshot only where no later fetch could render the attachment through a stand-in
(`keeps_own_attachment`: the image has STORAGE). A private texture whose device lays an image
out otherwise with STORAGE (with_free_usage leaves it off: the Iris Xe's optimal BGRA8Unorm,
as the orchestrator relayed from the 4845 A/B, 12-15 ms a frame of 30 splits for the private
selfread target) split at every such read, every frame, for good.

The fallback now notes the texture for its storage form (texture/storage_form.rs), the switch a
fetching pass's scratch already takes: at a later commit its image is made again with STORAGE
and its texels copied in once, announced as fetched-target-storage, and its later passes'
readers take the snapshot. A texture noted already returns before its plan is asked again, as
a reader that splits notes it at each such draw.

Test: tests/self_read_storage.rs (device test), with a test-only switch that makes STORAGE
cost every image (DeviceShared::storage_costs_forced, read in Device::if_free): a private
BGRA8Unorm target's first pass splits and takes the form at its commit, its later passes'
readers take the snapshot, each pass's texels Metal's; where the device does not take the path,
every reader splits and nothing swaps. Docs: the fetched-target-storage declaration and its
API.md entry, the FAST-PATHS attachment-read row.

(cherry picked from commit e0444b4029c9372197faf8c5bab3d967cb9bb543)
This commit is contained in:
Anees Iqbal committed 2026-11-07 15:14:06 -08:00
1 parent 87617be3cd
commit be1f1c141b
9 files changed
+293 -7

No files matched your search

@@ -590,7 +590,9 @@ degradations! {
"a scratch image per pass, the texture copied into it before the pass on a `Load` \
and back after it on a `Store`";
/// A runtime texture that a pass rendered into a scratch image for want of `STORAGE`
/// (`fetch-through-scratch` through the pixel interlock) took its storage form: its image
/// (`fetch-through-scratch` through the pixel interlock), or whose draw that read it at
/// its own pixels after a barrier split its pass for want of it (`render/snapshot.rs`),
/// took its storage form: its image
/// made again with `STORAGE` and its texels copied in once, at the commit of the device's
/// only uncommitted command buffer (`texture/storage_form.rs`); with a submission check,
/// once that command buffer's checks ran at its submission and every encoder of it ran.
@@ -485,6 +485,11 @@ pub(super) struct DeviceShared {
/// (`linear_attachment::bound`).
#[cfg(test)]
pub(crate) linear_rule_forced: AtomicBool,
/// `STORAGE` costs every image whose plan lacks it something (`Device::if_free`), whatever
/// the device lays out: for the tests of `tests/self_read_storage.rs` on a device that gives a
/// render target `STORAGE` for nothing.
#[cfg(test)]
pub(crate) storage_costs_forced: AtomicBool,
/// The logs of its shadows over host pages a consumer logs the writes to
/// (`dirty_pages.rs`).
pub(super) dirty: super::dirty_pages::DirtyShadows,
@@ -2061,6 +2066,8 @@ impl Device {
failing_host_imports: Default::default(),
#[cfg(test)]
linear_rule_forced: Default::default(),
#[cfg(test)]
storage_costs_forced: Default::default(),
dirty: Default::default(),
standings: Default::default(),
fresh: Default::default(),
@@ -514,6 +514,13 @@ impl Device {
candidate: ImagePlan,
texture_type: TextureType,
) -> Result<ImagePlan, Error> {
#[cfg(test)]
if (self.shared().storage_costs_forced).load(std::sync::atomic::Ordering::Relaxed)
&& candidate.usage.contains(ImageUsageFlags::STORAGE)
&& !plan.usage.contains(ImageUsageFlags::STORAGE)
{
return Ok(plan);
}
let answers = &self.shared().textures.usage_answers;
let known = lock(answers).answer(&plan, &candidate);
let free = match known {
@@ -77,7 +77,10 @@
//! of a texture the attachment renders in place, at the binding's own first level and slice,
//! with feedback loop usage (`Texture::snapshot_color`, `texture::feedback_candidate`), not
//! through a view of another format, and which no later fetch can render through a stand-in
//! (`RenderCommandEncoder::keeps_own_attachment`), no two of the colors of one image (whose
//! (`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
//! 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
@@ -314,6 +317,12 @@ impl RenderLowering {
.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();
}
return self.snapshot_fallback(
"a framebuffer fetch of the attachment would render it through a stand-in",
);
@@ -362,6 +362,8 @@ mod scheduler;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod scheduler_wakes;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod self_read_storage;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod set_zero_at_offsets;
mod shader_cache;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
@@ -0,0 +1,246 @@
//! 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.
//!
//! 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 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`).
use super::blit_holds::{device, Scratch, WAIT};
use super::encoder_holds::{bytes_of, library};
use crate::framebuffer_fetch::{storage_candidate, through_storage};
use crate::{
BlitOption, CommandQueue, CpuCacheMode, Device, HazardTrackingMode, LoadAction, Origin,
PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, ScissorRect, Size,
StorageMode, StoreAction, Texture, TextureDescriptor, WorkCounts,
};
use metal2vulkan::metal::{BarrierScope, PixelFormat, PrimitiveType, RenderStages, TextureUsage};
use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource};
use metal2vulkan::vk::ImageUsageFlags;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
/// The target's side, in pixels.
const SIDE: u64 = 32;
/// The target's format, a guest framebuffer's.
const FORMAT: PixelFormat = PixelFormat::BGRA8Unorm;
/// The block each pass fills and reads, `[x0, y0, x1, y1]`: its 64 pixels of the snapshot draw's
/// 20 bytes cost less than the split's copy of the target's 1024 texels of 4 bytes
/// (`RenderCommandEncoder::snapshot_cheaper`).
const BLOCK: [u64; 4] = [8, 8, 16, 16];
/// The red the first pass clears the target to.
const CLEARED: u8 = 20;
/// The passes over the target.
const PASSES: u8 = 3;
/// The red pass `pass` fills the block with.
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();
StageSource::Function(function.function_descriptor())
};
let mut descriptor = RenderPipelineDescriptor::new(function("tob_rect"));
descriptor.fragment = Some(function(fragment));
descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(FORMAT));
device
.new_render_pipeline_state(&descriptor, &PipelineOptions::default())
.unwrap()
}
/// A private [`FORMAT`] render target that shaders read, its hazards tracked where `tracked`.
fn target(device: &Device, tracked: bool) -> Texture {
let mut d = TextureDescriptor::texture_2d(FORMAT, SIDE, SIDE, false);
d.usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
d.resource_options = match tracked {
true => ResourceOptions::private(),
false => ResourceOptions::new(
StorageMode::Private,
CpuCacheMode::DefaultCache,
HazardTrackingMode::Untracked,
),
};
device.new_texture(&d).unwrap()
}
/// The corners, in normalized device coordinates, of the target's pixels `[x0, x1) x [y0, y1)`.
fn corners([x0, y0, x1, y1]: [u64; 4]) -> Vec<u8> {
let x = |p: u64| p as f32 / SIDE as f32 * 2.0 - 1.0;
let y = |p: u64| 1.0 - p as f32 / SIDE as f32 * 2.0;
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.
fn pass_over(
queue: &CommandQueue,
target: &Texture,
(fill, read): (&RenderPipelineState, &RenderPipelineState),
pass: u8,
) -> (Vec<u8>, WorkCounts) {
let device = queue.device();
let row = SIDE * 4;
let back = device
.new_buffer(SIDE * row, ResourceOptions::shared())
.unwrap();
let mut descriptor = RenderPassDescriptor::new();
let color = &mut descriptor.color_attachments[0];
color.texture = Some(target.clone());
color.load_action = match pass {
0 => LoadAction::Clear,
_ => LoadAction::Load,
};
color.clear_color = crate::ClearColor::new(f64::from(CLEARED) / 255.0, 0.0, 0.0, 1.0);
color.store_action = StoreAction::Store;
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.render_command_encoder(&descriptor).unwrap();
encoder.set_render_pipeline_state(fill).unwrap();
encoder.set_vertex_bytes(&corners(BLOCK), 0).unwrap();
let red = f32::from(red_of(pass)) / 255.0;
let rgba = bytes_of(&[red, 0.0, 0.0, 1.0], f32::to_le_bytes);
encoder.set_fragment_bytes(&rgba, 0).unwrap();
(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_render_pipeline_state(read).unwrap();
encoder.set_fragment_texture(Some(target), 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(
target,
0,
0,
Origin::new(0, 0, 0),
Size::new(SIDE, SIDE, 1),
&back,
0,
row,
SIDE * row,
BlitOption::None,
))
.unwrap();
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.error(), None);
let counts = device.work_counts();
let texels = super::merge_scratch::read(&back, SIDE * row);
// `BGRA8Unorm`'s red is its third byte.
(texels.chunks(4).map(|texel| texel[2]).collect(), counts)
}
/// Wait until the device's pipeline pool makes nothing.
fn settled(device: &Device) {
let until = Instant::now() + WAIT;
while device.work_counts().pipeline_pool_busy != 0 {
assert!(Instant::now() < until, "the pipeline pool still busy");
std::thread::sleep(Duration::from_millis(1));
}
}
#[test]
fn a_private_targets_readers_take_the_snapshot_once_it_took_its_storage_form() {
let cache = Scratch::new("self-read-storage");
let device = device(&cache.0);
device
.shared()
.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 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 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,
);
eprintln!(
"SELF-READ-STORAGE pass {pass}: (splits, snapshotted, storage forms) {moved:?}, \
pipelines pooled {}",
after.pipelines_pooled - pooled
);
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})");
}
let want = match (takes, pass) {
(true, 0) => (1, 0, 1),
(true, _) => (0, 1, 0),
(false, _) => (1, 0, 0),
};
assert_eq!(
moved,
want,
"pass {pass} on {}: splits, readers through snapshots, storage forms taken",
device.name()
);
before = after;
}
let image = target.image_plan().unwrap();
assert_eq!(
image.usage.contains(ImageUsageFlags::STORAGE),
takes,
"the target's image has STORAGE after its passes"
);
}
@@ -10,7 +10,10 @@
//! whose plan [`storage_candidate`] gives `STORAGE`, and whose `VkImage`
//! was never handed out ([`Texture::vk_image`](crate::Texture::vk_image) keeps it for good).
//! Noted once, at the first fetching pass that renders it into a scratch image for want of
//! `STORAGE`. An untracked texture keeps its scratch: the program orders its uses on other
//! `STORAGE`, or at the first draw that reads it after a barrier in a pass that renders it and
//! splits the pass for want of `STORAGE` (`render/snapshot.rs`: a later fetch would render it
//! through a stand-in its snapshot does not see), whose later passes' readers then take the
//! snapshot. An untracked texture keeps its scratch: the program orders its uses on other
//! queues with its own fences and events, which the copy below could not follow.
//! - **When: the commit of the only uncommitted command buffer.** A command buffer that commits
//! while it is the device's only one not committed (`queue.rs`'s
@@ -272,7 +275,8 @@ impl Image {
impl Texture {
/// Note the texture, a color render target that a pass fetches through the pixel interlock
/// and renders into a scratch image for want of `STORAGE`, to take its storage form where it
/// and renders into a scratch image for want of `STORAGE`, or whose reader after a barrier
/// splits its pass for want of it (`render/snapshot.rs`), to take its storage form where it
/// may (the module docs); once.
pub(crate) fn want_storage_form(&self) {
if self.0.parent.is_some() {
@@ -289,7 +293,10 @@ impl Texture {
..
}
);
if !own
// Noted already: a reader that splits its pass notes it at each such draw
// (`render/snapshot.rs`), so the plan is asked no more.
if form.noted.load(Ordering::Relaxed)
|| !own
|| !image.identity.tracked
|| self.storage_mode() != StorageMode::Private
|| form.taken.get().is_some()
+2 -1
View File
@@ -1838,7 +1838,8 @@ bound.
copied into it before the pass on a `Load` and back after it on a `Store`.
- `metal2vulkan-degrade-fetched-target-storage` (performance). `FetchedTargetStorage`: A runtime
texture that a pass rendered into a scratch image for want of `STORAGE` (`fetch-through-scratch`
through the pixel interlock) took its storage form: its image made again with `STORAGE` and its
through the pixel interlock), or whose draw that read it at its own pixels after a memory barrier
split its pass for want of it, took its storage form: its image made again with `STORAGE` and its
texels copied in once, at the commit of the device's only uncommitted command buffer; with a
submission check, once that command buffer's checks ran at its submission and every encoder of it
ran. Announced once per device, whatever `DeviceOptions::announce_each` says, before that command
+6 -1
View File
@@ -220,7 +220,12 @@ recorded here.
instance (`texture/attached_reads.rs`): the texels around the draw's scissors where it reads at
its own pixels alone, else every texel or what the instances since drew. After a barrier inside
the instance, an own-pixel read takes a snapshot drawn in its subpass (`render/snapshot.rs`,
docs/API.md "Snapshot reads") or splits the instance; both are exact. Over a texture over its
docs/API.md "Snapshot reads") or splits the instance; both are exact. A private texture of the
runtime's own whose image lacks `STORAGE` (the device lays it out otherwise with it) splits at
its first such read, as a later fetch would render it through a stand-in its snapshot does not
see, and takes its storage form at a later commit (`texture/storage_form.rs`,
`WorkCounts::storage_forms_taken`, `fetched-target-storage`): its later passes' readers take the
snapshot. Over a texture over its
buffer's bytes (a linear image over an ordinary buffer's packed rows or over host pages, or the
shadow a texture over host pages that renders is where it is one) it takes the snapshot at any
area, where the device makes that image with feedback loop usage