diff --git a/crates/metal2vulkan-runtime/src/indirect_execute/kept.rs b/crates/metal2vulkan-runtime/src/indirect_execute/kept.rs index d6b807f4b..81ab43e24 100644 --- a/crates/metal2vulkan-runtime/src/indirect_execute/kept.rs +++ b/crates/metal2vulkan-runtime/src/indirect_execute/kept.rs @@ -87,7 +87,7 @@ impl Execute { let key = ComputeKey { pipeline: self.pipeline.clone(), ordered: self.ordered, - resident: ResidentKey::new(residency.kept_key()), + resident: ResidentKey::new(residency.kept_key(command_buffer.device())), }; Some(Keeping { key, kept, read_at }) } diff --git a/crates/metal2vulkan-runtime/src/kept_commands.rs b/crates/metal2vulkan-runtime/src/kept_commands.rs index aa320e170..757f09f22 100644 --- a/crates/metal2vulkan-runtime/src/kept_commands.rs +++ b/crates/metal2vulkan-runtime/src/kept_commands.rs @@ -47,14 +47,14 @@ use crate::encoder::ResidentPart; use crate::error::Error; use crate::execution::Execution; use crate::heap_sets::{self, SetVersion}; -use crate::residency::Residency; +use crate::residency::{KeptListing, Residency}; use crate::resource::ResourceKey; use crate::spares::CommandPool; use crate::tracker::Summary; use crate::upload::Uploads; use crate::work_counts::Counters; use ash::vk; -use metal2vulkan::bind::{ReplayFaults, UsedResource}; +use metal2vulkan::bind::ReplayFaults; use std::any::Any; use std::collections::{BTreeMap, BTreeSet}; use std::ops::Range; @@ -259,21 +259,21 @@ pub(super) fn resolutions( } /// The resources an execution's encoders made resident, as the key of a chunk it records holds -/// them (`Residency::kept_key`): one list an execution, which the chunks it records share, so a -/// later execution compares its own with a kept chunk's whole once a list ([`ResidentMet`]) and -/// by pointer after. +/// them (`Residency::kept_key`): one list a residency's content, which the executions that take +/// it and the chunks they record share, so a later execution compares its own with a kept +/// chunk's whole once a list ([`ResidentMet`]) and by pointer after. #[derive(Clone)] -pub(super) struct ResidentKey(Arc<(Vec, Vec)>); +pub(super) struct ResidentKey(Arc); impl ResidentKey { /// The key of `resident`, an execution's (`Residency::kept_key`). - pub(super) fn new(resident: (Vec, Vec)) -> ResidentKey { - ResidentKey(Arc::new(resident)) + pub(super) fn new(resident: Arc) -> ResidentKey { + ResidentKey(resident) } - /// The resources' keys, in token order. - pub(super) fn keys(&self) -> &[ResourceKey] { - &self.0 .1 + /// Whether `key` is one of the resources' keys. + pub(super) fn holds_key(&self, key: &ResourceKey) -> bool { + self.0.holds_key(key) } } diff --git a/crates/metal2vulkan-runtime/src/render/executions/kept.rs b/crates/metal2vulkan-runtime/src/render/executions/kept.rs index 635aef36b..cd59d16b3 100644 --- a/crates/metal2vulkan-runtime/src/render/executions/kept.rs +++ b/crates/metal2vulkan-runtime/src/render/executions/kept.rs @@ -132,7 +132,6 @@ use crate::sample_positions::Sixteenths; use metal2vulkan::bind::indirect_commands::{BufferStage, CommandRecord}; use metal2vulkan::bind::ReplayFaults; use metal2vulkan::metal::IndirectCommandType; -use std::collections::BTreeSet; use std::ops::Range; use std::sync::atomic::Ordering; use std::sync::Arc; @@ -492,16 +491,17 @@ impl RenderExecution { // Read before the chunks are recorded: a sampler state made meanwhile leaves a key no later // execution's equals. let samplers = command_buffer.generation().sampler_slots_changed(); - let resident = ResidentKey::new(residency.kept_key()); + let resident = ResidentKey::new(residency.kept_key(command_buffer.device())); // An attachment is among them as a texture made resident, or in a heap or over a buffer // made resident. - let keys: BTreeSet = resident.keys().iter().copied().collect(); let attached = colors .map(|color| &color.target.texture) .chain(layout.depth_stencil.as_ref().map(|ds| &ds.target.texture)) .filter(|texture| { - keys.contains(&texture.use_key()) - || texture.bytes_key().is_some_and(|key| keys.contains(&key)) + resident.holds_key(&texture.use_key()) + || texture + .bytes_key() + .is_some_and(|key| resident.holds_key(&key)) }) .map(|texture| texture.use_key()) .collect(); diff --git a/crates/metal2vulkan-runtime/src/residency.rs b/crates/metal2vulkan-runtime/src/residency.rs index c20c81465..387fa6b52 100644 --- a/crates/metal2vulkan-runtime/src/residency.rs +++ b/crates/metal2vulkan-runtime/src/residency.rs @@ -77,13 +77,20 @@ //! `compute/live.rs`): so that share is listed once per change, whatever else a command //! changes. A compute dispatch that finds the generation, and every other input, its last //! dispatch settled with takes what that one settled (`compute.rs`, `DispatchMemo`). +//! - **Copies.** A residency's copies share what it made resident until one of them changes it, +//! which then takes a copy of its own: so each execution of an indirect command buffer, its +//! settle at the commit and its host step, which each take the command buffer's residency +//! (`CommandBuffer::residency`), costs a count, not the resources it holds. So does the kept +//! key of their recordings ([`kept_key`](Residency::kept_key)), listed once for what a +//! residency holds while no used resource's statement changes (the **Generations** rule). //! - **Stages.** A render encoder makes a resource resident for the render stages it names //! (`useResource:usage:stages:`, `useHeap:stages:`), joined as the usages are: a draw's //! functions reach it in those of their stages alone (the binder's `UsedResource::stages`), and //! a tile dispatch only where they hold the tile stage. A compute encoder names none, and its //! dispatches reach every resource it made resident. -use super::buffer::{Buffer, ReadApart}; +use super::buffer::{host_cells_moved, Buffer, ReadApart}; +use super::device::{lock, Device}; use super::heap::Heap; use super::indirect_command_buffer::IndirectCommandBuffer; use super::key_hash::KeyMap; @@ -96,7 +103,7 @@ use metal2vulkan::bind::{ResidentRange, ResourceClass, UsedResource}; use metal2vulkan::metal::{RenderStages, ResourceUsage}; use metal2vulkan::pipeline::{BindingSource, PipelineLayout, Stage, SyntheticBinding}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; /// The generation last given to a residency of the process ([`Residency::generation`]). static GENERATIONS: AtomicU64 = AtomicU64::new(0); @@ -124,14 +131,9 @@ pub(super) enum Used { /// The resources an encoder made resident, by token, each with its usage and render stages. #[derive(Clone, Default)] pub(super) struct Residency { - used: Vec<(Used, ResourceUsage, RenderStages)>, - /// Each resource of `used` by its identity, with its token. - tokens: KeyMap, - /// The tokens of the indirect command buffers among `used`. - indirect: Vec, - /// The tokens of the textures among `used`: a command's look at the textures made resident - /// costs their count, not every resource's. - textures: Vec, + /// The resources (the module docs' **Copies**): shared by its copies until one of them + /// changes them. + held: Arc, /// Whether one of `textures` is sampled through an address-mode map other than the identity /// (`Texture::address_mode_map`, fixed as the texture is made; a view's is its texture's): /// set as such a texture is made resident, which none is ever made no longer, so a command's @@ -164,6 +166,68 @@ pub(super) struct Residency { heaps_found: Option)>>, } +/// What a [`Residency`] made resident, which its copies share. +#[derive(Default)] +struct Held { + used: Vec<(Used, ResourceUsage, RenderStages)>, + /// Each resource of `used` by its identity, with its token. + tokens: KeyMap, + /// The tokens of the indirect command buffers among `used`. + indirect: Vec, + /// The tokens of the textures among `used`: a command's look at the textures made resident + /// costs their count, not every resource's. + textures: Vec, + /// Its kept key ([`Residency::kept_key`]) as last listed, with the moves of no-copy buffers + /// and the device's views epoch it was listed at: the listing while both hold. + kept: Mutex)>>, +} + +/// A copy, to be changed: its kept key is listed again. +impl Clone for Held { + fn clone(&self) -> Held { + Held { + used: self.used.clone(), + tokens: self.tokens.clone(), + indirect: self.indirect.clone(), + textures: self.textures.clone(), + kept: Mutex::new(None), + } + } +} + +impl Held { + /// `held`, to change: its own (a copy where copies share it), its kept key to be listed + /// again. + fn changed(held: &mut Arc) -> &mut Held { + let held = Arc::make_mut(held); + *held.kept.get_mut().unwrap_or_else(PoisonError::into_inner) = None; + held + } +} + +/// What a kept recording of commands that resolved and bound against a residency was recorded +/// from (`kept_commands.rs`, [`Residency::kept_key`]): its resources as the bind state states +/// them and each one's key, in token order, and the keys sorted, for a look. +pub(super) struct KeptListing { + used: Vec, + keys: Vec, + sorted: Vec, +} + +impl KeptListing { + /// Whether `key` is one of the resources' keys: a look in the sorted keys. + pub(super) fn holds_key(&self, key: &ResourceKey) -> bool { + self.sorted.binary_search(key).is_ok() + } +} + +/// Equal where both list the same resources, stated alike, with the same keys. +impl PartialEq for KeptListing { + fn eq(&self, other: &KeptListing) -> bool { + self.used == other.used && self.keys == other.keys + } +} + /// Where each buffer and heap's own buffer a residency made resident lies in Metal's address /// space: the pieces of the space between their starts and ends in order, each with the first /// made resident of those that hold it, and the ends, each with the first made resident of @@ -284,7 +348,7 @@ impl Used { impl Residency { /// Whether it holds nothing: no resource, heap or live table. pub(super) fn is_empty(&self) -> bool { - self.used.is_empty() && self.heaps.is_empty() && self.live.is_none() + self.held.used.is_empty() && self.heaps.is_empty() && self.live.is_none() } /// Its generation (the module docs): equal to another residency's only where neither changed @@ -297,11 +361,11 @@ impl Residency { /// state's used resources made of it ([`used_resources`](Self::used_resources)), states: a /// buffer made later with the ID takes the slot (`address.rs`) without changing the residency. pub(super) fn holds_slots_as(&self, used: &[UsedResource]) -> bool { - self.indirect.iter().all(|&token| { + self.held.indirect.iter().all(|&token| { let stated = used .get(token as usize) .map(|used| used.gpu_address.is_some()); - match self.used.get(token as usize) { + match self.held.used.get(token as usize) { Some((Used::IndirectCommandBuffer(icb), ..)) => stated == Some(icb.holds_id_slot()), _ => false, } @@ -395,7 +459,7 @@ impl Residency { /// The heaps of what the encoder made resident: those it used, and those its resident /// buffers, textures and indirect command buffers lie in. pub(super) fn heaps(&self) -> impl Iterator + '_ { - self.used.iter().filter_map(|(used, ..)| match used { + self.held.used.iter().filter_map(|(used, ..)| match used { Used::Buffer(buffer) => buffer.heap().cloned(), Used::Texture(texture) => texture.heap().cloned(), Used::Heap { heap, .. } => Some(heap.clone()), @@ -456,10 +520,10 @@ impl Residency { /// The resources of [`join_encoder`](Self::join_encoder): each with its usage, in the render /// stages it named, or every render stage for a compute encoder's. How many `ended` holds. pub(super) fn join_encoder_resources(&mut self, ended: &Residency, compute: bool) -> usize { - for (used, usage, stages) in &ended.used { + for (used, usage, stages) in &ended.held.used { self.join(used.clone(), *usage, reached(*stages, compute)); } - ended.used.len() + ended.held.used.len() } /// The heaps of [`join_encoder`](Self::join_encoder): each in the render stages it named, or @@ -485,7 +549,7 @@ impl Residency { /// resource with its usage, and each heap with the textures it holds now (held as /// [`use_resource`](Self::use_resource) holds what it makes resident). pub(super) fn carry(&mut self, from: &Residency) { - for (used, usage, _) in &from.used { + for (used, usage, _) in &from.held.used { self.join(used.clone(), *usage, RenderStages::empty()); } for heap in &from.heaps { @@ -497,8 +561,11 @@ impl Residency { /// stages), so its plan is a kernel's of the same shape as the encoder's own dispatch's /// (`tile_resources` alike). pub(super) fn kernel(mut self) -> Residency { - for (_, _, stages) in &mut self.used { - *stages = RenderStages::empty(); + let staged = (self.held.used.iter()).any(|(_, _, stages)| !stages.is_empty()); + if staged { + for (_, _, stages) in &mut Held::changed(&mut self.held).used { + *stages = RenderStages::empty(); + } } for heap in &mut self.heaps { heap.stages = RenderStages::empty(); @@ -512,7 +579,7 @@ impl Residency { /// The indirect command buffers made resident for writing, each once. pub(super) fn writable_indirect_command_buffers(&self) -> Vec { let mut writable: Vec = Vec::new(); - for (used, usage, _) in &self.used { + for (used, usage, _) in &self.held.used { if let Used::IndirectCommandBuffer(icb) = used { if usage.contains(ResourceUsage::WRITE) && !writable.contains(icb) { writable.push(icb.clone()); @@ -524,7 +591,7 @@ impl Residency { /// The resources made resident. pub(super) fn resources(&self) -> impl Iterator { - self.used.iter().map(|(used, ..)| used) + self.held.used.iter().map(|(used, ..)| used) } /// What a recording that may reach every resource it holds may use of them, for the @@ -535,7 +602,7 @@ impl Residency { /// resident with; what the commands reach unnamed (`live_buffers.rs`) it does not order. pub(super) fn bound_uses(&self) -> Vec> { let stages = vk::PipelineStageFlags2::ALL_COMMANDS; - (self.used.iter()) + (self.held.used.iter()) .map(|(used, usage, _)| { let reads = usage.intersects(ResourceUsage::READ.union(ResourceUsage::SAMPLE)); let read = match reads { @@ -563,34 +630,37 @@ impl Residency { /// The resources it holds that `other` does not. pub(super) fn past<'a>(&'a self, other: &'a Residency) -> impl Iterator { - (self.used.iter()) + (self.held.used.iter()) .map(|(used, ..)| used) - .filter(|used| !other.tokens.contains_key(used)) + .filter(|used| !other.held.tokens.contains_key(used)) } /// `used` resident with `usage` in `stages`, joined to the usage and stages it had: `used`, /// when it is new here. fn join(&mut self, used: Used, usage: ResourceUsage, stages: RenderStages) -> Option { - if let Some(&token) = self.tokens.get(&used) { - let (_, had_usage, had_stages) = &mut self.used[token as usize]; + if let Some(&token) = self.held.tokens.get(&used) { + let (_, had_usage, had_stages) = &self.held.used[token as usize]; let (usage, stages) = (had_usage.union(usage), had_stages.union(stages)); if (usage, stages) != (*had_usage, *had_stages) { + let held = Held::changed(&mut self.held); + let (_, had_usage, had_stages) = &mut held.used[token as usize]; (*had_usage, *had_stages) = (usage, stages); self.generation = next_generation(); } return None; } - let token = u32::try_from(self.used.len()).expect("fewer than 2^32 resources resident"); + let held = Held::changed(&mut self.held); + let token = u32::try_from(held.used.len()).expect("fewer than 2^32 resources resident"); match &used { - Used::IndirectCommandBuffer(_) => self.indirect.push(token), + Used::IndirectCommandBuffer(_) => held.indirect.push(token), Used::Texture(texture) => { - self.textures.push(token); + held.textures.push(token); self.maps_addresses |= !texture.address_mode_map().is_identity(); } Used::Buffer(_) | Used::Heap { .. } => {} } - self.tokens.insert(used.clone(), token); - self.used.push((used.clone(), usage, stages)); + held.tokens.insert(used.clone(), token); + held.used.push((used.clone(), usage, stages)); self.generation = next_generation(); self.addresses = OnceLock::new(); Some(used) @@ -603,7 +673,8 @@ impl Residency { /// heap as its own buffer is (`Heap::bytes`), whose range holds every buffer placed in it; a /// texture by its facts and resource ID. pub(super) fn used_resources(&self) -> Vec { - self.used + self.held + .used .iter() .zip(0u32..) .map(|((resource, usage, stages), token)| { @@ -645,21 +716,53 @@ impl Residency { } /// What a kept recording of commands that resolved and bound against it was recorded from - /// (`kept_commands.rs`): its resources as the bind state states them, and each one's key, - /// in order. - pub(super) fn kept_key(&self) -> (Vec, Vec) { - let keys = self.used.iter().map(|(used, ..)| match used { - Used::Buffer(buffer) => buffer.identity().key, - Used::Heap { bytes, .. } => bytes.identity().key, - Used::Texture(texture) => texture.use_key(), - Used::IndirectCommandBuffer(icb) => icb.storage().identity().key, - }); - (self.used_resources(), keys.collect()) + /// (`kept_commands.rs`, [`KeptListing`]), listed once for what it holds (the module docs' + /// **Copies**), its copies' included: listed again only where a no-copy buffer moved since + /// (`buffer::host_cells_moved`: a buffer's statement), an image of `device` let its views go + /// (`DeviceShared::views_epoch`: a texture's key), or an indirect command buffer's hold on + /// its ID's slot changed ([`holds_slots_as`](Self::holds_slots_as)). Each listing counted + /// (`WorkCounts::resident_kept_keys_listed`). + pub(super) fn kept_key(&self, device: &Device) -> Arc { + let epoch = device.shared().views_epoch.load(Ordering::Acquire); + let at = (host_cells_moved(), epoch); + if let Some((moved, epoch, listing)) = &*lock(&self.held.kept) { + if (*moved, *epoch) == at && self.holds_slots_as(&listing.used) { + debug_assert!( + **listing == self.listing(), + "a kept key listing that is not its residency's" + ); + return Arc::clone(listing); + } + } + let listing = Arc::new(self.listing()); + let counts = &device.shared().counts; + counts.resident_kept_keys_listed(self.held.used.len() as u64); + *lock(&self.held.kept) = Some((at.0, at.1, Arc::clone(&listing))); + listing + } + + /// Its [`kept_key`](Self::kept_key), listed now. + fn listing(&self) -> KeptListing { + let keys: Vec = (self.held.used.iter()) + .map(|(used, ..)| match used { + Used::Buffer(buffer) => buffer.identity().key, + Used::Heap { bytes, .. } => bytes.identity().key, + Used::Texture(texture) => texture.use_key(), + Used::IndirectCommandBuffer(icb) => icb.storage().identity().key, + }) + .collect(); + let mut sorted = keys.clone(); + sorted.sort_unstable(); + KeptListing { + used: self.used_resources(), + keys, + sorted, + } } /// The resource of `token`. pub(super) fn get(&self, token: u32) -> Option<&Used> { - self.used.get(token as usize).map(|(used, ..)| used) + self.held.used.get(token as usize).map(|(used, ..)| used) } /// The command buffer's residency with `live`, the device's live buffers at its commit. @@ -711,7 +814,7 @@ impl Residency { /// resident: a look costs the logarithm of their count, not their count. pub(super) fn resolve(&self, address: u64) -> Option<(Buffer, u64)> { let index = self.addresses.get_or_init(|| { - let index = AddressIndex::of_used(&self.used); + let index = AddressIndex::of_used(&self.held.used); if let Some((buffer, _)) = self.buffers_written().next() { let counts = &buffer.device().shared().counts; counts.resident_address_index_made(); @@ -719,7 +822,7 @@ impl Residency { Arc::new(index) }); let found = index.first_holding(address).and_then(|token| { - let buffer = match self.used.get(token as usize)? { + let buffer = match self.held.used.get(token as usize)? { (Used::Buffer(buffer), ..) | (Used::Heap { bytes: buffer, .. }, ..) => buffer, (Used::Texture(_) | Used::IndirectCommandBuffer(_), ..) => return None, }; @@ -741,14 +844,14 @@ impl Residency { /// Look for the shadowed textures (`shadowed`) among those made resident since it last /// looked, in the order they were made resident. fn find_shadowed(&mut self) { - for &token in &self.textures[self.textures_looked_at..] { - if let Some((Used::Texture(texture), ..)) = self.used.get(token as usize) { + for &token in &self.held.textures[self.textures_looked_at..] { + if let Some((Used::Texture(texture), ..)) = self.held.used.get(token as usize) { if texture.shadow().is_some() { self.shadowed.push(token); } } } - self.textures_looked_at = self.textures.len(); + self.textures_looked_at = self.held.textures.len(); } /// Join onto `shadows`, what a command buffer's next compute or render (`render`) encoder @@ -759,7 +862,7 @@ impl Residency { pub(super) fn shadows_onto(&mut self, shadows: &mut Residency, render: bool, compute: bool) { self.find_shadowed(); for &token in &self.shadowed { - let Some((Used::Texture(texture), usage, stages)) = self.used.get(token as usize) + let Some((Used::Texture(texture), usage, stages)) = self.held.used.get(token as usize) else { continue; }; @@ -773,9 +876,10 @@ impl Residency { /// The textures made resident, each with its usage and render stages. fn resident_textures(&self) -> impl Iterator { - self.textures + self.held + .textures .iter() - .filter_map(|&token| match self.used.get(token as usize) { + .filter_map(|&token| match self.held.used.get(token as usize) { Some((Used::Texture(texture), usage, stages)) => Some((texture, *usage, *stages)), _ => None, }) @@ -813,7 +917,7 @@ impl Residency { /// The buffers made resident, a heap as its own buffer, each with whether a function's use /// of it may write, as [`textures_written`](Self::textures_written) says it of a texture. pub(super) fn buffers_written(&self) -> impl Iterator { - self.used.iter().filter_map(|(used, usage, _)| { + self.held.used.iter().filter_map(|(used, usage, _)| { let buffer = match used { Used::Buffer(buffer) => buffer, Used::Heap { bytes, .. } => bytes, diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 389be3943..31b4d98d7 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -348,6 +348,7 @@ pub(crate) struct Counters { resident_textures_looked_at: AtomicU64, resident_resources_joined: AtomicU64, resident_address_indexes_made: AtomicU64, + resident_kept_keys_listed: AtomicU64, root_table_ranges_noted: AtomicU64, heap_tables_worked_out: AtomicU64, argument_samplers_taken: AtomicU64, @@ -3230,6 +3231,13 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// A residency listed its `count` resources for the kept key of the executions that take it + /// (`Residency::kept_key`). + pub(crate) fn resident_kept_keys_listed(&self, count: u64) { + self.resident_kept_keys_listed + .fetch_add(count, Ordering::Relaxed); + } + /// A root table's own resident set listed `count` ranges, noted for its command buffer's /// resident set (`command_buffer::State::root_table`). pub(crate) fn root_table_ranges_noted(&self, count: u64) { @@ -6849,6 +6857,13 @@ pub struct WorkCounts { /// the first look after a resource was made resident into a residency holding a buffer or a /// heap, however many addresses the commands name. pub resident_address_indexes_made: u64, + /// Resources a residency listed for the kept key of the indirect command buffer executions + /// that take it, each listing every one (`Residency::kept_key`): one listing for what a + /// residency holds, shared by its copies, so by every execution of a command buffer's, at its + /// commit and at its host step, and listed again only where a no-copy buffer moved, an image + /// let its views go or an indirect command buffer's hold on its ID's slot changed since. + /// None for an execution whose residency's listing holds, however many resources it holds. + pub resident_kept_keys_listed: u64, /// Ranges the root tables of draws and dispatches listed of their own resident sets /// (`metal2vulkan::bind::RootTable::resident_ranges`), noted for their command buffer's /// resident set, which the commit points every table at: each table's bound buffers with @@ -9558,6 +9573,7 @@ impl Device { root_table_ranges_noted: (counters.root_table_ranges_noted).load(Ordering::Relaxed), resident_address_indexes_made: (counters.resident_address_indexes_made) .load(Ordering::Relaxed), + resident_kept_keys_listed: (counters.resident_kept_keys_listed).load(Ordering::Relaxed), heap_tables_worked_out: counters.heap_tables_worked_out.load(Ordering::Relaxed), argument_samplers_taken: counters.argument_samplers_taken.load(Ordering::Relaxed), bind_views_worked_out: commands(|counts| &counts.bind_views_worked_out), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/render_merged_indexed.rs b/crates/metal2vulkan-validation/src/runtime_lane/render_merged_indexed.rs index 41b3f03df..fbbc3b14b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/render_merged_indexed.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/render_merged_indexed.rs @@ -8,7 +8,9 @@ //! returns them with its command's tint into a `RGBA32Uint` target. They draw on the GPU alone, //! in one merged draw, each vertex its command's index plus its base vertex and each fragment its //! own command's tint: the same pixels as the host step's, which a barrier the CPU set and -//! cleared sends them to. +//! cleared sends them to. Executed again and again through the host step under a heap's textures +//! made resident, their recordings' keys list what the command buffer made resident once a +//! frame, however many executions take it. use super::degrade_notices::{assert_made_once, counts, made_compute_kinds, on_device_with}; use super::indirect_host_steps::{complete, HOST_STEPS}; @@ -24,9 +26,10 @@ use metal2vulkan::pipeline::{ }; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ - Buffer, ClearColor, ComputePipelineState, Device, IndirectCommandBufferDescriptor, Library, - LoadAction, PipelineOptions, Region, RenderPassDescriptor, RenderPipelineState, - ResourceOptions, Size, StoreAction, Texture, TextureDescriptor, + Buffer, ClearColor, ComputePipelineState, Device, HeapDescriptor, HeapType, + IndirectCommandBufferDescriptor, Library, LoadAction, PipelineOptions, Region, + RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, StoreAction, Texture, + TextureDescriptor, }; use std::collections::BTreeSet; @@ -288,3 +291,124 @@ fn merged_indexed_draws_draw_what_the_host_step_draws() { } }); } + +/// The textures a heap of the device's holds, which the frames of +/// [`a_host_step_lists_its_residency_once_for_every_execution`] make resident. +const HEAP_TEXTURES: u64 = 64; + +/// The executions of the buffer's commands in each frame's pass. +const EXECUTIONS: u64 = 4; + +/// A frame's command buffer whose pass executes the commands a kernel writes, a barrier the CPU +/// set and cleared sending them to the host step, [`EXECUTIONS`] times, both encoders using a +/// heap of [`HEAP_TEXTURES`] textures: from its second frame on, its executions keep their +/// commands' recordings (`render/executions/kept.rs`), each keyed by what the command buffer made +/// resident, which its residency lists once for all of them (`Residency::kept_key`), not once an +/// execution: the listing costs the resources a frame, not the resources times the executions. +#[test] +fn a_host_step_lists_its_residency_once_for_every_execution() { + on_device_with(at_plan, |device, _messages| { + let library = library(device); + let state = device + .new_render_pipeline_state(&state_descriptor(&library), &PipelineOptions::default()) + .unwrap(); + let writer = writer(device, &library, 32); + let draws: Vec = vec![[0, 3, 1, 0, 0], [3, 6, 2, 0, 1], [9, 4, 1, 0, 0]]; + let icb = icb(device, &inheriting(), COMMANDS); + let command = icb.indirect_render_command_at(COMMANDS - 1).unwrap(); + command.set_barrier().unwrap(); + command.clear_barrier().unwrap(); + let buffers: [Buffer; 7] = [ + buffer_with(device, &icb.gpu_resource_id().0.to_le_bytes()).unwrap(), + buffer_with(device, &words(draws.iter().flatten().copied())).unwrap(), + buffer_with(device, &words((0..COMMANDS as u32).map(|c| 100 + c))).unwrap(), + buffer_with(device, &floats([W as f32, H as f32, ROW, 0.0])).unwrap(), + buffer_with(device, &floats(triangles().into_iter().flatten())).unwrap(), + buffer_with(device, &words((0..COMMANDS as u32).map(|c| 200 + c))).unwrap(), + buffer_with(device, &words(indices())).unwrap(), + ]; + let heap = device + .new_heap(&HeapDescriptor::new( + HeapType::Placement, + 4 << 20, + ResourceOptions::private(), + )) + .unwrap(); + let mut placed = Vec::new(); + let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 64, 64, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = ResourceOptions::private(); + let fit = device.heap_texture_size_and_align(&descriptor).unwrap(); + let stride = fit.size.next_multiple_of(fit.align); + for at in 0..HEAP_TEXTURES { + placed.push( + heap.new_texture_at_offset(&descriptor, at * stride) + .unwrap(), + ); + } + let target = target(device); + let queue = device.new_command_queue().unwrap(); + let mut listed = Vec::new(); + for _ in 0..4 { + let command_buffer = queue.command_buffer().unwrap(); + let before = device.work_counts(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder + .use_resource(icb.as_resource(), ResourceUsage::WRITE) + .unwrap(); + encoder.use_heap(&heap).unwrap(); + encoder.set_compute_pipeline_state(&writer).unwrap(); + for (index, buffer) in buffers.iter().enumerate() { + encoder.set_buffer(Some(buffer), 0, index as u32).unwrap(); + } + let grid = Size::new(draws.len() as u64, 1, 1); + encoder.dispatch_threads(grid, grid).unwrap(); + encoder.end_encoding().unwrap(); + let mut pass = RenderPassDescriptor::new(); + let color = &mut pass.color_attachments[0]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::Clear; + color.store_action = StoreAction::Store; + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder + .use_heap(&heap, RenderStages::VERTEX | RenderStages::FRAGMENT) + .unwrap(); + encoder.set_render_pipeline_state(&state).unwrap(); + for (buffer, stages) in [ + (&buffers[2], RenderStages::VERTEX), + (&buffers[3], RenderStages::VERTEX), + (&buffers[4], RenderStages::VERTEX), + (&buffers[6], RenderStages::VERTEX), + (&buffers[5], RenderStages::FRAGMENT), + ] { + encoder + .use_resource(buffer.as_resource(), ResourceUsage::READ, stages) + .unwrap(); + } + for _ in 0..EXECUTIONS { + encoder + .execute_commands_in_buffer(&icb, 0..COMMANDS) + .unwrap(); + } + encoder.end_encoding().unwrap(); + complete(&command_buffer); + let after = device.work_counts(); + assert!( + after.host_steps_recorded > before.host_steps_recorded, + "the frame's executions take the host step" + ); + listed.push(after.resident_kept_keys_listed - before.resident_kept_keys_listed); + } + // What the command buffer made resident: the heap and its textures, the indirect command + // buffer and the five buffers. + let resident = 1 + HEAP_TEXTURES + 1 + 5; + for (frame, &listed) in listed.iter().enumerate().skip(1) { + assert!( + listed > 0 && listed <= 2 * resident, + "frame {frame}: {listed} listed of {resident} resident, {EXECUTIONS} executions \ + ({listed:?})" + ); + } + drop(placed); + }); +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 253626aaa..3c9638f86 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3217,6 +3217,7 @@ field metal2vulkan-runtime::WorkCounts.replayed_heap_draws_writing pub replayed_ field metal2vulkan-runtime::WorkCounts.requirement_images_made pub requirement_images_made: u64 field metal2vulkan-runtime::WorkCounts.requirement_limits_asked pub requirement_limits_asked: u64 field metal2vulkan-runtime::WorkCounts.resident_address_indexes_made pub resident_address_indexes_made: u64 +field metal2vulkan-runtime::WorkCounts.resident_kept_keys_listed pub resident_kept_keys_listed: u64 field metal2vulkan-runtime::WorkCounts.resident_keys_settled pub resident_keys_settled: u64 field metal2vulkan-runtime::WorkCounts.resident_resources_joined pub resident_resources_joined: u64 field metal2vulkan-runtime::WorkCounts.resident_textures_looked_at pub resident_textures_looked_at: u64