diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 0a7d6d23b..22a4e8ad3 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -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 diff --git a/crates/metal2vulkan-runtime/src/command.rs b/crates/metal2vulkan-runtime/src/command.rs index 60a1d2035..f0c34dcb5 100644 --- a/crates/metal2vulkan-runtime/src/command.rs +++ b/crates/metal2vulkan-runtime/src/command.rs @@ -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) { diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index 3bf58b1cd..d8a151d59 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -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, diff --git a/crates/metal2vulkan-runtime/src/kept.rs b/crates/metal2vulkan-runtime/src/kept.rs index 4f9317149..543daaea1 100644 --- a/crates/metal2vulkan-runtime/src/kept.rs +++ b/crates/metal2vulkan-runtime/src/kept.rs @@ -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 Deref for Uncounted { /// 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>, /// The sRGB variants of kernels the recording dispatched, which no state holds. pub(crate) contents: Kept>, + /// The attachment views the recording's passes rendered through: a texture evicts only a + /// view no list holds. + pub(crate) attachment_views: Kept>, } 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(); diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index 7f9f19aed..94ee6b15f 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -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. diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 2a69d0ecf..0c0ae0de1 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -251,10 +251,10 @@ pub(crate) struct TextureInner { view: Option, /// 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>, + /// 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, /// 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 { + /// The view itself. + type Kept = Arc; + + fn object(&self) -> &Arc { + self + } + + fn address_of(object: &Arc) -> 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, 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, 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>, 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), };