Runtime: a texture's attachment views bounded, the least recently used idle one evicted

A texture kept an image view for each level, first layer and layer count a pass rendered into,
for its whole life and with no bound (the field's doc said levels times slices, but the key
holds the layer count, so an N-slice array could keep N(N+1)/2 a level). Now a texture keeps at
most one view for each level and slice (each depth plane of a 3D texture's levels) and one more
a level (texture.rs attachment_bound): a cube's six faces one by one and its six layered fit.
A view made past the bound first evicts the least recently taken views that no command buffer
holds, to the reaper, until the bound has room (texture.rs evict_idle); where command buffers in
flight hold every one it evicts none, so the list holds the bound and what work not yet retired
holds past it.

How a view a command buffer in flight uses is known never to be evicted:
- Each view is an Arc (texture.rs AttachmentView). The texture's list holds one count; a take
  (texture.rs attachment_view) clones another only under the list's lock, into the pass's
  Attachment::held (texture.rs:406).
- The pass's begin keeps that Arc in its command buffer's kept list before the pass records
  (render_encoder.rs:935 for each target, :940 for each resolve; command.rs:1701
  hold_attachment_view into kept.rs:256 ByKind::attachment_views, via Kept::hold, kept.rs:191).
  A stencil target that targets() skips shares the depth target's view, which the pass checks
  (pass.rs DepthStencilViews).
- That list is cleared only at the command buffer's retirement (command.rs:2124, in retire) or
  at the drop of one never committed (command.rs:2201), before the texture list
  (kept.rs:264).
- Eviction takes only a view whose strong count is 1, the list's own (texture.rs:386), counted
  under the same lock, so no other hold can appear while it decides.
Between the take and the keep, the pass's own Attachment holds a count, so a view is never seen
idle in that window.

Docs: the field's, the attachment call's, Gauges::attachment_views' and the runtime README's
pass section now state the key and the bound. The kept-list size note counts eight lists.

Verification is in the jobs named where this lands; the device tests of the previous commit
are red without this change.
This commit is contained in:
Anees Iqbal committed 2026-12-02 08:36:02 -08:00
1 parent 15d5e6f0f2
commit 80ef3ea24e
6 files changed
+135 -36

No files matched your search

+4 -1
View File
@@ -4583,7 +4583,10 @@ cache is answered compile-required on both.
a shader reads them through `texture2d_ms` or `depth2d_ms`. The texture keeps an
image view of that level and those layers with the identity swizzle (a 2D view of one layer, a
2D array view of more), made at the first pass that renders into it and freed with the texture
(`Gauges::attachment_views`).
(`Gauges::attachment_views`). It keeps at most one view for each level and slice (each depth
plane of a 3D texture's levels) and one more a level, so a cube's faces one by one and its six
layered fit; past that, a new view first frees the least recently used one that no command
buffer in flight holds, and where they all are held it frees none until they retire.
- A pass with no attachment is `renderTargetWidth` by `renderTargetHeight` pixels at
`defaultRasterSampleCount` samples: one dynamic rendering of no attachment, whose draws'
pipeline states have that `rasterSampleCount` and no attachment format, and write their answers
+10 -1
View File
@@ -22,7 +22,7 @@ use crate::record::{self, Reach, Recorder};
use crate::render::RenderPipelineState;
use crate::ring::{Placed, Writes};
use crate::sampler::SamplerState;
use crate::texture::{Image, OverCopy, Texture, TextureInner, TextureObject};
use crate::texture::{Attachment, Image, OverCopy, Texture, TextureInner, TextureObject};
use crate::times::{self, Pair, Times};
use crate::visibility::{Queries, Query};
use ash::vk;
@@ -1695,6 +1695,15 @@ impl Building {
self.gpu.kept.variants.hold(variant);
}
/// Keeps the texture's view of `attachment`, which a pass renders through, until the command
/// buffer retires: one count at the recording's first pass through it, none at a later one.
/// A texture evicts only a view no command buffer keeps (`crate::texture::AttachmentView`).
pub(crate) fn hold_attachment_view(&mut self, attachment: &Attachment) {
if let Some(view) = &attachment.held {
self.gpu.kept.attachment_views.hold(view);
}
}
/// Keeps `content`, a kernel's variant that a dispatch runs, until the command buffer
/// retires: no state holds it (`PipelineInner::variant`).
pub(crate) fn hold_content(&mut self, content: &Arc<Compiled>) {
+4 -2
View File
@@ -3694,8 +3694,10 @@ pub struct Gauges {
/// with its shader modules and their `VkPipeline`s, shared by every state of that content.
/// One lives while a state or the device's map of contents holds it.
pub render_contents: u64,
/// The image views textures keep for render passes: one for each level and slice a pass
/// rendered into, freed with the texture.
/// The image views textures keep for render passes: one for each level, first slice and
/// layer count a pass rendered into, freed with the texture. A texture keeps at most one for
/// each level and slice (each depth plane of a 3D texture's levels) and one more a level; past
/// that, a new one first frees the least recently used one no command buffer in flight holds.
pub attachment_views: u64,
/// Command buffers not yet retired.
pub command_buffers: u64,
+13 -7
View File
@@ -1,7 +1,8 @@
//! What a command buffer keeps of the objects its encoders use: each buffer, texture, sampler
//! state and pipeline state once, as Metal's command buffer retains each object once, and each
//! kernel variant past its kernel's cells that it dispatches (`crate::pipeline::Listed`), until
//! the command buffer retires. The first use of an object in a recording takes its one
//! state and pipeline state once, as Metal's command buffer retains each object once, each
//! kernel variant past its kernel's cells that it dispatches (`crate::pipeline::Listed`), and each
//! attachment view its passes render through (`crate::texture::AttachmentView`), until the
//! command buffer retires. The first use of an object in a recording takes its one
//! reference, of the object alone ([`Handle::Kept`]): nothing a command buffer keeps counts as a
//! handle of the device, so the consumer's last handle is the device's last whatever work is in
//! flight.
@@ -16,7 +17,7 @@ use crate::buffer::Buffer;
use crate::pipeline::{Compiled, ComputePipelineState, Listed};
use crate::render::RenderPipelineState;
use crate::sampler::SamplerState;
use crate::texture::Texture;
use crate::texture::{AttachmentView, Texture};
use std::collections::HashSet;
use std::hash::{BuildHasherDefault, Hasher};
use std::mem::ManuallyDrop;
@@ -139,9 +140,9 @@ impl<T> Deref for Uncounted<T> {
/// game streams (at most 128, of textures), and a cap on memory, not a fit to them: a smaller
/// bound for one kind would make every recording that used one more object of it allocate again.
///
/// At most, then, a queue keeps for each command buffer it holds at once ([`Objects`]) six lists
/// at the bound, each 128 handles (1 KiB) and an address set of 256 buckets (2.3 KiB): 19.6 KiB,
/// so 1.2 MiB for a queue of 64 command buffers.
/// At most, then, a queue keeps for each command buffer it holds at once ([`Objects`]) eight lists
/// at the bound, each 128 handles (1 KiB) and an address set of 256 buckets (2.3 KiB): 26.1 KiB,
/// so 1.6 MiB for a queue of 64 command buffers.
pub(crate) const KEPT_BOUND: usize = 128;
/// The objects of one kind a recording keeps, each once, in the order first used.
@@ -250,12 +251,17 @@ pub(crate) struct ByKind {
pub(crate) variants: Kept<Arc<Listed>>,
/// The sRGB variants of kernels the recording dispatched, which no state holds.
pub(crate) contents: Kept<Arc<Compiled>>,
/// The attachment views the recording's passes rendered through: a texture evicts only a
/// view no list holds.
pub(crate) attachment_views: Kept<Arc<AttachmentView>>,
}
impl ByKind {
/// Releases every object, keeping each list's capacity, within [`KEPT_BOUND`], for the next
/// recording.
pub(crate) fn clear(&mut self) {
// Before the textures: a texture whose last hold is that list's frees its views as it drops.
self.attachment_views.clear();
self.buffers.clear();
self.textures.clear();
self.samplers.clear();
@@ -928,12 +928,16 @@ fn begin(
)
})
};
// Each attachment's texture, and its view, which the texture evicts only once no command
// buffer keeps it. A stencil target that `targets` skips shares the depth target's view.
for t in pass.targets() {
building.keep_texture(&t.texture);
building.hold_attachment_view(&t.attachment);
}
if pass.resolving {
for r in pass.resolves() {
building.keep_texture(&r.texture);
building.hold_attachment_view(&r.attachment);
}
}
// Kept as Metal's pass holds it; its writes are the encoder's, at its first mode and its end.
+100 -25
View File
@@ -251,10 +251,10 @@ pub(crate) struct TextureInner {
view: Option<View>,
/// How the image holds the pixel format, which a pass's clear value follows.
emulation: FormatEmulation,
/// The image views render passes rendered into, one for each level and layer of the image
/// (`Texture::attachment`), kept until the texture is gone: at most its levels times its
/// slices.
attachments: Mutex<Vec<AttachmentView>>,
/// The image views render passes rendered into, one for each level, first layer and layer
/// count of the image a pass rendered into (`Texture::attachment`), kept until the texture is
/// gone or, past [`attachment_bound`], evicted while idle ([`AttachmentViews`]).
attachments: Mutex<AttachmentViews>,
/// Its view of its image's shadow, where a draw may read an attachment through it on a device
/// without the attachment feedback loop (`crate::shadow`): the sampled view's own type,
/// mapping and range, and the view once a draw read through it, which its second element
@@ -325,8 +325,12 @@ impl ShadowView {
}
}
/// An image view of one level and layer of a texture's image, for render passes.
struct AttachmentView {
/// An image view of one level and layers of a texture's image, for render passes: its texture's
/// list holds it ([`AttachmentViews`]), and so does each command buffer not yet retired whose pass
/// rendered into it, from that pass's begin (`crate::kept::ByKind::attachment_views`). A hold is
/// taken only under the list's lock, so a view the lock finds with the list's count alone is idle,
/// and stays idle while the lock is held.
pub(crate) struct AttachmentView {
level: u32,
/// Its first layer: a slice, or a 3D image's depth plane.
layer: u32,
@@ -334,10 +338,72 @@ struct AttachmentView {
view: vk::ImageView,
}
impl crate::kept::Handle for Arc<AttachmentView> {
/// The view itself.
type Kept = Arc<AttachmentView>;
fn object(&self) -> &Arc<AttachmentView> {
self
}
fn address_of(object: &Arc<AttachmentView>) -> usize {
Arc::as_ptr(object) as usize
}
}
/// A texture's attachment views, each with the number of the last take that found or made it,
/// and the number of the next take. At most [`attachment_bound`] of them: a view made past it
/// first evicts the least recently taken views no command buffer holds, to the reaper, until the
/// bound has room for it; where command buffers in flight hold every one, it evicts none, so the
/// list holds the bound and what work not yet retired holds past it.
#[derive(Default)]
struct AttachmentViews {
views: Vec<(Arc<AttachmentView>, u64)>,
takes: u64,
}
/// The most attachment views `d`'s texture keeps: one for each level and slice a pass renders one
/// layer of (each depth plane of a 3D texture's levels), and one more a level, a layered pass's
/// view of its slices. So a cube's faces one by one and its six layered fit, and the views of
/// other first slices and layer counts take the place of the least recently used.
fn attachment_bound(d: &TextureDescriptor) -> usize {
let levels = d.mipmap_level_count as usize;
match d.texture_type {
TextureType::Type3D => (0..d.mipmap_level_count)
.map(|level| (d.depth >> level).max(1) as usize)
.sum(),
_ => levels * (slices(d) as usize + 1),
}
}
/// Evicts the least recently taken views of `views` that no command buffer holds, to the reaper,
/// until `room` or fewer remain or none is idle. Called under the list's lock, so a view it finds
/// idle stays so ([`AttachmentView`]).
fn evict_idle(core: &Core, views: &mut Vec<(Arc<AttachmentView>, u64)>, room: usize) {
let mut evicted = Vec::new();
while views.len() > room {
let idle = (views.iter().enumerate())
.filter(|(_, (view, _))| Arc::strong_count(view) == 1)
.min_by_key(|(_, (_, taken))| *taken)
.map(|(at, _)| at);
let Some(at) = idle else {
break;
};
evicted.push(views.swap_remove(at).0.view);
}
if !evicted.is_empty() {
core.reaper.give(Job::Free(Free::AttachmentViews(evicted)));
}
}
/// A level and slices of a texture as a render pass attachment ([`Texture::attachment`]).
pub(crate) struct Attachment {
/// The image view of the level and layers, every aspect, with the identity swizzle.
pub(crate) view: vk::ImageView,
/// The texture's view, `view`, as its list keeps it: a hold taken under the list's lock,
/// which the pass's command buffer keeps until it retires ([`AttachmentView`]). `None` for a
/// resolve image's view, which its texture keeps for its life.
pub(crate) held: Option<Arc<AttachmentView>>,
pub(crate) image: vk::Image,
/// The level and first layer in the image.
pub(crate) level: u32,
@@ -1165,8 +1231,8 @@ impl Drop for TextureInner {
let core = &self.core;
let attachments =
(self.attachments.get_mut()).unwrap_or_else(std::sync::PoisonError::into_inner);
if !attachments.is_empty() {
let views = attachments.drain(..).map(|a| a.view).collect();
if !attachments.views.is_empty() {
let views = attachments.views.drain(..).map(|(a, _)| a.view).collect();
core.reaper.give(Job::Free(Free::AttachmentViews(views)));
}
// A view's id and image are its parent's, which it keeps.
@@ -1679,7 +1745,7 @@ impl Device {
named: None,
view: None,
emulation: plan.emulation,
attachments: Mutex::new(Vec::new()),
attachments: Mutex::default(),
shadow: None,
levels: Mutex::new(None),
};
@@ -1973,7 +2039,7 @@ impl Device {
named,
view: None,
emulation: plan.emulation,
attachments: Mutex::new(Vec::new()),
attachments: Mutex::default(),
shadow,
levels: Mutex::new(None),
};
@@ -4804,7 +4870,7 @@ impl Texture {
extended,
}),
emulation: plan.emulation,
attachments: Mutex::new(Vec::new()),
attachments: Mutex::default(),
shadow,
levels: Mutex::new(None),
};
@@ -5421,7 +5487,7 @@ pub(crate) trait TextureObject {
/// `level` and the `layers` slices from `slice` of the texture as a render pass attachment:
/// the image view of that one level and those layers of its image (a 2D view of one layer, a
/// 2D array view of more), every aspect, with the identity swizzle, made at the first pass
/// that renders into it and kept with the texture. A 3D texture's attachment, where the
/// that renders into it and kept with the texture, within its bound ([`AttachmentViews`]). A 3D texture's attachment, where the
/// attachment takes a depth plane (`plane`, a color attachment's `depthPlane`) and the pass
/// renders one layer, is that plane of the level: a 2D view of the plane, which its image's
/// 2D-array compatibility gives (`Plan::flags`); `plane` is read of no other type, as Metal
@@ -5550,6 +5616,7 @@ pub(crate) trait TextureObject {
};
let attachment = Attachment {
view,
held: None,
image,
level: 0,
layer: 0,
@@ -5711,14 +5778,19 @@ pub(crate) trait TextureObject {
}))
}
};
let mut views = lock(&self.object().attachments);
let kept = (views.iter())
.find(|a| a.level == level_in_image && a.layer == first && a.layers == layers)
.map(|a| a.view);
let view = match kept {
Some(view) => view,
let mut kept = lock(&self.object().attachments);
let take = kept.takes;
kept.takes += 1;
let found = (kept.views.iter_mut())
.find(|(a, _)| a.level == level_in_image && a.layer == first && a.layers == layers);
let held = match found {
Some((held, taken)) => {
*taken = take;
Arc::clone(held)
}
None => {
let core = &self.object().core;
evict_idle(core, &mut kept.views, attachment_bound(d).saturating_sub(1));
let range = vk::ImageSubresourceRange {
aspect_mask: image.aspects,
base_mip_level: level_in_image,
@@ -5747,17 +5819,20 @@ pub(crate) trait TextureObject {
)
}?;
core.counters.rise(Gauge::AttachmentViews);
views.push(AttachmentView {
let held = Arc::new(AttachmentView {
level: level_in_image,
layer: first,
layers,
view,
});
view
kept.views.push((Arc::clone(&held), take));
held
}
};
drop(kept);
Ok(Attachment {
view,
view: held.view,
held: Some(held),
image: image.image,
level: level_in_image,
layer,
@@ -6198,8 +6273,8 @@ pub(crate) trait TextureObject {
/// image and its layer count, in no order.
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
fn attachment_views(&self) -> Vec<(u32, u32, u32)> {
(lock(&self.object().attachments).iter())
.map(|a| (a.level, a.layer, a.layers))
(lock(&self.object().attachments).views.iter())
.map(|(a, _)| (a.level, a.layer, a.layers))
.collect()
}
@@ -6646,7 +6721,7 @@ impl Device {
named: Some(named),
view: None,
emulation: FormatEmulation::Direct,
attachments: Mutex::new(Vec::new()),
attachments: Mutex::default(),
shadow: None,
levels: Mutex::new(None),
};
@@ -6925,7 +7000,7 @@ impl Device {
named: None,
view: None,
emulation: plan.emulation,
attachments: Mutex::new(Vec::new()),
attachments: Mutex::default(),
shadow,
levels: Mutex::new(None),
};