diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 9a3942c59..79229824c 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -744,6 +744,6 @@ impl BlitCommandEncoder { if let Some(pattern) = pattern { core.retain(pattern); } - core.end_with_replay(EncoderKind::Blit, None, log.map(Replay::Blit), None) + core.end_with_replay(EncoderKind::Blit, (None, None), log.map(Replay::Blit), None) } } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs index 2c3fdbe50..c181355b5 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs @@ -93,7 +93,9 @@ impl State { record.in_tail = true; } let (leader, batches) = (self.recorded.len() - 1, self.batches.all().len()); - let stashed = log.into_iter().collect(); + // Its stash takes the room the command buffer's lists keep (`record_storage.rs`). + let mut stashed = self.stash_room.take().unwrap_or_default(); + stashed.extend(log); self.fold = Some(Box::new(Fold::begun( tail, (leader, encoder), @@ -130,13 +132,16 @@ impl State { /// command predication, so a rebind can encode the group again; else they are held until the /// commit, whose failure may split the group ([`split_failure`](Self::split_failure)). A lone /// encoder's comes back, for the caller to give back to the device's spares without this lock - /// (`replay.rs`). + /// (`replay.rs`). A group of more gives the room of its stash back, emptied, for the next + /// group's (`record_storage.rs`). pub(crate) fn close_fold(&mut self, counts: &Counters) -> Vec { let Some(fold) = self.fold.take() else { return Vec::new(); }; let Fold { - members, stashed, .. + members, + mut stashed, + .. } = *fold; if members.len() < 2 { return stashed.into_iter().map(|stashed| stashed.log).collect(); @@ -146,7 +151,8 @@ impl State { } let logged = (self.ended[members.clone()].iter()).any(|record| record.replay.is_some()); if !logged || self.predicated { - self.held_logs.extend(stashed); + self.held_logs.append(&mut stashed); + self.stash_room = Some(stashed); return Vec::new(); } let mut unkept = Vec::new(); @@ -154,7 +160,7 @@ impl State { encoder, log, executions, - } in stashed + } in stashed.drain(..) { let bytes = log.bytes(); match self.keep_replay(encoder, Some(log), executions) { @@ -162,6 +168,7 @@ impl State { None => counts.replay_log_kept(bytes), } } + self.stash_room = Some(stashed); unkept } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 8c2cb27e1..e98e4cdd8 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -48,6 +48,7 @@ mod labels; pub(super) mod own; mod protection; pub(super) mod rebound_use; +pub(super) mod record_storage; pub(super) mod recovery; mod reencode; pub(super) mod rerun; @@ -64,6 +65,7 @@ pub(super) use first_submission::{NotedTable, ReplayTable}; use follow::{Follow, Release}; pub(super) use group::{Group, GroupEnd, GROUP_BATCHES}; use rebound_use::{ReboundUse, Unlogged}; +use record_storage::{RecordStorage, Room}; pub(crate) use stall::Stop; pub(super) use submit::{BatchLists, Submitting}; @@ -839,6 +841,17 @@ pub(super) struct State { /// failure may split a group (`fold.rs`'s `split_failure`), and given back to the device's /// spares in the release. pub(super) held_logs: Vec, + /// The storage the next group of its encoders recorded into one `VkCommandBuffer` stashes the + /// logs its members do not keep in (`encoder_fold::Fold`'s `stashed`), empty; `None` while a + /// group holds it. + stash_room: Option>, + /// The room its lists of records (`ended`, `recorded`, `held_logs` and `stash_room`) held as + /// it took their storage from the device's spares (`record_storage.rs`): its release counts + /// those that grew past it (`WorkCounts::record_lists_grown`). + room: Room, + /// What its last ended compute encoder parked for its next one, until the commit gives it back + /// to the device (`compute/live.rs`'s `Parked`). + parked_compute: Option, /// The encoders that run of each group the commit's failure split, which its call encodes /// again before the first submission (`reencode.rs`). pub(super) split_units: Vec>, @@ -1185,6 +1198,19 @@ impl State { self.ended.len() } + /// The storage of its lists of records, taken whole for its release to give back to the + /// device's spares (`record_storage.rs`), with the room they held as it took it: nothing reads + /// them after. + fn record_storage(&mut self) -> (RecordStorage, Room) { + let storage = RecordStorage { + ended: std::mem::take(&mut self.ended), + recorded: std::mem::take(&mut *self.recorded), + stashed: self.stash_room.take().unwrap_or_default(), + held_logs: std::mem::take(&mut self.held_logs), + }; + (storage, self.room) + } + /// An encoder of `kind` ended, its commands' uses and bindings having named `keys`, having /// made `residency` resident (a compute or render encoder's): it joins the ended encoders, /// with the event waits and signals encoded before it, and what it made resident joins the @@ -1489,6 +1515,21 @@ impl State { self.inherited(render, counts) } + /// Keep `parked`, what a compute encoder's end parks, for the next compute encoder that opens + /// (`compute/live.rs`): one kept already, which no encoder took, comes back. + pub(super) fn park_compute( + &mut self, + parked: crate::compute::Parked, + ) -> Option { + self.parked_compute.replace(parked) + } + + /// What the last compute encoder that ended parked, for a compute encoder that opens; `None` + /// where it is taken or given back already. + pub(super) fn unpark_compute(&mut self) -> Option { + self.parked_compute.take() + } + /// Note `work` of an encoder it ended, which its scheduling hands to the device's identifier /// allocations ([`UniqueIdentifiers::scheduled`](crate::unique_identifier::UniqueIdentifiers::scheduled)). pub(super) fn note_scheduled(&mut self, work: ScheduledWork) { @@ -2521,6 +2562,13 @@ impl Drop for CommandBufferShared { .spares .give_command_pool(shared, pool, false, recorded); } + // The storage of its lists of records goes on to the device's next command buffer, what + // they held going here (`record_storage.rs`). + let (storage, room) = lock(&self.state).record_storage(); + shared.counts.record_lists_grown(room.grown(&storage)); + if shared.record_storage.give(storage) { + shared.counts.record_storage_kept(); + } } } @@ -2537,6 +2585,14 @@ impl CommandBuffer { /// A new command buffer of `root`, on its place `queue`, holding `slot` of it. pub(super) fn new(queue: &QueueGen, root: &CommandQueue, slot: Slot) -> CommandBuffer { let footprints = Footprints::default(); + let storage = queue.device().shared().record_storage.take(); + let room = storage.room(); + let RecordStorage { + ended, + recorded, + stashed, + held_logs, + } = storage; CommandBuffer(Arc::new(CommandBufferShared { id: ObjectId::new(), generation: Arc::clone(queue.device().shared_arc()), @@ -2568,10 +2624,13 @@ impl CommandBuffer { rerun_pool: None, kept: None, own_reached: 0, - recorded: Revised::new(Vec::new(), &footprints.revision), + recorded: Revised::new(recorded, &footprints.revision), tail: None, fold: None, - held_logs: Vec::new(), + held_logs, + stash_room: Some(stashed), + room, + parked_compute: None, left_out_from: None, split_units: Vec::new(), folds: Vec::new(), @@ -2635,7 +2694,7 @@ impl CommandBuffer { joined: 0, inherits: [None, None], resident_writes: None, - ended: Vec::new(), + ended, root_tables: Vec::new(), root_ranges: HashSet::new(), resident: None, @@ -3898,10 +3957,18 @@ impl CommandBuffer { self.mark_gpu_written(); // No encoder joins the group its tail holds from here (`encoder_fold.rs`): its // encoders take a failure and a rebind together, and the logs it keeps for that are kept. - let unkept = self.state().close_fold(&device.shared().counts); + // What its last compute encoder parked goes back to the device (`compute/live.rs`). + let (unkept, parked) = { + let mut state = self.state(); + let unkept = state.close_fold(&device.shared().counts); + (unkept, state.unpark_compute()) + }; for log in unkept { device.shared().scheduler.spare_logs().give(log); } + if let Some(parked) = parked { + parked.give_back(device); + } let (segments, places, failure, reached, hangs, split): ( Vec<(Deferred, bool)>, Vec, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/record_storage.rs b/crates/metal2vulkan-runtime/src/command_buffer/record_storage.rs new file mode 100644 index 000000000..81fbedd45 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/command_buffer/record_storage.rs @@ -0,0 +1,101 @@ +//! The storage of a command buffer's lists of what its encoders ended with, kept by its device +//! from one command buffer to the next: its ended encoders' records (`State::encoder_ended`), their +//! recordings (`State::end_encoder`), the logs of a group of encoders recorded into one +//! `VkCommandBuffer` its members did not keep (`encoder_fold.rs`'s `Fold`), and those held for its +//! commit (`fold.rs`). A command buffer starts on the latest storage a released one left, emptied +//! with its room kept, so its encoders' ends push into room the lists already had rather than +//! grow them one reallocation at a time over fresh pages; its release empties the lists and gives +//! their storage back ([`SpareRecordStorage`]). What the lists held goes as it went before, at the +//! release; only the room goes on, and only to command buffers of the same device. + +use std::sync::Mutex; + +use crate::device::lock; +use crate::encoder::Recorded; +use crate::encoder_fold::Stashed; +use crate::used_resources::EncoderRecord; + +/// The storages a device keeps, at most: a command buffer made after another's release takes the +/// latest, so a program that makes one as one is released keeps one in use. +const SPARE_RECORD_STORAGES: usize = 2; + +/// The room a kept storage's lists hold, at most, in bytes: a command buffer of more encoders +/// than that room holds lets its storage go. A command buffer of a few thousand one-dispatch +/// encoders fits. +const RECORD_STORAGE_BYTES: usize = 8 << 20; + +/// The lists a command buffer keeps of what its encoders ended with, whose storage goes from one +/// command buffer of a device to the next (the module docs). +#[derive(Default)] +pub(crate) struct RecordStorage { + pub(super) ended: Vec, + pub(super) recorded: Vec, + /// The storage the command buffer's next group of encoders stashes its members' logs in. + pub(super) stashed: Vec, + pub(super) held_logs: Vec, +} + +impl RecordStorage { + /// The room its lists hold, each list's in entries. + pub(super) fn room(&self) -> Room { + Room([ + self.ended.capacity(), + self.recorded.capacity(), + self.stashed.capacity(), + self.held_logs.capacity(), + ]) + } + + /// The room its lists hold, in bytes. + fn bytes(&self) -> usize { + self.ended.capacity() * std::mem::size_of::() + + self.recorded.capacity() * std::mem::size_of::() + + (self.stashed.capacity() + self.held_logs.capacity()) * std::mem::size_of::() + } +} + +/// The room of each of a [`RecordStorage`]'s lists as a command buffer took it. +#[derive(Clone, Copy)] +pub(super) struct Room([usize; 4]); + +impl Room { + /// How many of `storage`'s lists hold more room than this: those that grew since. + pub(super) fn grown(self, storage: &RecordStorage) -> u64 { + let Room(now) = storage.room(); + let grown = (self.0.iter().zip(now)).filter(|&(&was, now)| now > was); + grown.count() as u64 + } +} + +/// A device's storages of the lists of records its released command buffers left, which the +/// command buffers it makes next start on (the module docs): at most [`SPARE_RECORD_STORAGES`], +/// each of at most [`RECORD_STORAGE_BYTES`], the latest given taken first. +#[derive(Default)] +pub(crate) struct SpareRecordStorage(Mutex>); + +impl SpareRecordStorage { + /// The storage a command buffer being made starts on: the latest a released one gave back, + /// else lists of no room. + pub(super) fn take(&self) -> RecordStorage { + lock(&self.0).pop().unwrap_or_default() + } + + /// Keep `storage`, a released command buffer's, emptied here (what its lists held goes) for + /// the next command buffer to start on, where its room is within [`RECORD_STORAGE_BYTES`] + /// and fewer than [`SPARE_RECORD_STORAGES`] are kept; else it goes. Whether it was kept. + pub(super) fn give(&self, mut storage: RecordStorage) -> bool { + storage.ended.clear(); + storage.recorded.clear(); + storage.stashed.clear(); + storage.held_logs.clear(); + if storage.bytes() > RECORD_STORAGE_BYTES { + return false; + } + let mut spare = lock(&self.0); + let keeps = spare.len() < SPARE_RECORD_STORAGES; + if keeps { + spare.push(storage); + } + keeps + } +} diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index ed1f97e6f..1aae12013 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -117,8 +117,8 @@ use std::sync::{Arc, Mutex, OnceLock, Weak}; mod live; -use live::LiveDispatch; -pub(crate) use live::SpareLiveDispatches; +use live::{Across, LiveDispatch}; +pub(crate) use live::{Parked, SpareLiveDispatches}; /// Entries of a compute encoder's threadgroup memory table. pub(super) const THREADGROUP_SLOTS: u32 = 31; @@ -283,19 +283,33 @@ impl CommandBuffer { let serial = dispatch_type == DispatchType::Serial; let counts = &self.device().shared().counts; // Under the core's one lock of the state: it joins its command buffer's unit of command - // predication, carrying on the loops open across its start, or starts the next; and it - // starts with the residency the ended encoders left (`State::inheriting`). - let (opened, (carried, residency, predicated)) = EncoderCore::open( + // predication, carrying on the loops open across its start, or starts the next; it starts + // with the residency the ended encoders left (`State::inheriting`); and it takes what the + // command buffer's last compute encoder parked (`compute/live.rs`). + let (opened, (carried, residency, predicated, parked)) = EncoderCore::open( self, call, EncoderKind::Compute, (serial, Some(joining)), |state| { let carried = state.enter_predication(dispatch_type); - (carried, state.inheriting(false, counts), state.predicated) + let residency = state.inheriting(false, counts); + (carried, residency, state.predicated, state.unpark_compute()) }, )?; - let mut core = opened.boxed(); + // The core in the box the command buffer's last compute encoder parked, and its bind state + // (`compute/live.rs`); else the device's spares'. + let (mut core, live) = match parked { + Some(parked) => { + counts.parked_compute_taken(); + let (room, live) = parked.into_parts(); + (opened.boxed_in(room), live) + } + None => { + let live = self.device().shared().live_dispatches.take(); + (opened.boxed(), live) + } + }; // The laying of a loop open across its start goes on in a command buffer of its own, which // the loop's check may submit again (`predication.rs`). if !carried.is_empty() && self.state().predication.laying() { @@ -315,8 +329,7 @@ impl CommandBuffer { captures: Captures::carried(carried, predicated), log: Some(self.device().shared().scheduler.spare_logs().compute()), dispatches: 0, - // The bind state the device's last ended compute encoder left (`compute/live.rs`). - live: self.device().shared().live_dispatches.take(), + live, heaps_noted: None, }) } @@ -1691,18 +1704,20 @@ impl ComputeCommandEncoder { self.end_predication()?; } self.table.let_go_all(&mut self.core); - // Its bind state goes on to the device's next compute encoder (`compute/live.rs`). - self.core.device().shared().live_dispatches.give(self.live); // Its log, which its command buffer keeps where a rebind may need it (`replay.rs`). let replay = self.log.map(|log| Replay::Compute { dispatch_type: self.dispatch_type, log, }); + // Its core's box and its bind state go on to its command buffer's next compute encoder + // (`compute/live.rs`). + let (core, room) = EncoderCore::unboxed_apart(self.core); + let parked = Parked::new(room, self.live); // What it made resident joins its command buffer's (`residency.rs`), and is its own // (`CommandBuffer::ended_encoders`). - EncoderCore::unboxed(self.core).end_with_replay( + core.end_with_replay( EncoderKind::Compute, - Some(self.residency), + (Some(self.residency), Some(parked)), replay, unit_work, ) @@ -2179,24 +2194,32 @@ fn settle_dispatch<'a>( /// states at `changed` changes of their slots: the state's shape kept where nothing brought in may /// have changed it, else found among those the pipeline state planned for lately or made /// (`LiveDispatch::shape`), and what it planned for that shape, the very one looked for first -/// (`ComputePipelineState::planned_for`). +/// (`ComputePipelineState::planned_for`). Where `refreshed` holds the table's samplers' maps, the +/// state was brought in place with them and `samplers` untrimmed already +/// (`LiveDispatch::settled_across`'s `Across::Refreshed`), which it is not again. fn settle_live<'a>( live: &mut LiveDispatch, tables: &DispatchTables<'_>, (direct, gpu): (Option, Option>), function_tables: Vec, - (changed, samplers): (u64, Vec), + ((changed, samplers), refreshed): ((u64, Vec), Option), ) -> Result)>, Error> { let pipeline = tables.pipeline; let counts = pipeline.generation().shared().counts.thread(); let mut argument_samplers = samplers; let mut unlisted = None; - let sampler_maps = tables.sampler_maps()?; + let (sampler_maps, mut in_place) = match refreshed { + Some(maps) => (maps, true), + None => (tables.sampler_maps()?, false), + }; // Whether the states were trimmed to those a variant's set-1 sampler arrays hold. let mut trimmed = false; let (planned, as_before, flat) = loop { let listing = (changed, &argument_samplers[..], trimmed); - live.refresh(tables, &sampler_maps, listing, &function_tables, counts); + if !in_place { + live.refresh(tables, &sampler_maps, listing, &function_tables, counts); + } + in_place = false; let shape = live.shape(counts, |state| pipeline.planned_shape(state)); let last = direct.and_then(|dispatch| pipeline.planned_for(&shape, &dispatch, tables.forms)); @@ -2309,6 +2332,11 @@ fn planned_as_before( /// dispatch, their regions keyed by the variant for the device (`Variant::keyed_regions`). /// - **A region's `VkPipeline`** found made is its variant's for the region's key, which its /// making never changes; regions not all made are looked up again at the next dispatch. +/// - **Another encoder's table.** The entry goes on with the state to the command buffer's next +/// compute encoder (`compute/live.rs`'s **Parked in its command buffer**), and a dispatch there +/// whose new table, read, brings in the very state the entry settled (no value of any kind +/// changed, the samplers' maps the same), with every other input above the same, takes it under +/// the new table's stamp (`WorkCounts::dispatches_settled_across_encoders`). /// - **A dispatch that settles again** (another table, another residency) takes the variant, the /// plan and the made `VkPipeline`s of one of its pipeline state's latest direct dispatches that /// planned, where its bind state has that one's shape ([`Planned`], [`settle_live`]): so does one @@ -2346,10 +2374,22 @@ impl DispatchMemo { tables: &DispatchTables<'_>, dispatch: &Dispatch, counted: (u64, u64), + ) -> bool { + (self.0.as_ref()).is_some_and(|kept| kept.stamp == tables.table.stamp()) + && self.holds_but_stamp(state, tables, dispatch, counted) + } + + /// [`holds`](Self::holds) in every input but the table's stamp: a table of another encoder + /// of the command buffer (`LiveDispatch::settled_across`). + fn holds_but_stamp( + &self, + state: &BindState, + tables: &DispatchTables<'_>, + dispatch: &Dispatch, + counted: (u64, u64), ) -> bool { self.0.as_ref().is_some_and(|kept| { kept.pipeline == *tables.pipeline - && kept.stamp == tables.table.stamp() && kept.settled.planned.dispatch == *dispatch && kept.counted == counted && kept.forms == tables.forms @@ -2383,11 +2423,35 @@ impl DispatchMemo { fn entry(&self) -> Option<&KeptDispatch> { self.0.as_ref() } + + /// The entry goes on under `stamp`, the stamp of a table that brings in the very state it + /// settled (`LiveDispatch::settled_across`), its sampler states listed again where its + /// parking let them go ([`unlist_samplers`](Self::unlist_samplers)): `samplers`, the + /// device's at the count of sampler slot changes the entry was settled at, so the very states + /// it listed (`DeviceShared::sampler_slots_changed`). + fn restamp(&mut self, stamp: Stamp, samplers: &[SamplerState]) { + if let Some(kept) = &mut self.0 { + kept.stamp = stamp; + if kept.settled.argument_samplers.is_empty() { + kept.settled.argument_samplers.extend_from_slice(samplers); + } + } + } + + /// Let go of the device's sampler states the entry listed, as its encoder's state parks in its + /// command buffer, which holds none of them (`compute/live.rs`'s `Parked`): a dispatch that + /// takes the entry lists them again ([`restamp`](Self::restamp)), at the same count of + /// sampler slot changes, which every other use of the entry compares first. + fn unlist_samplers(&mut self) { + if let Some(kept) = &mut self.0 { + kept.settled.argument_samplers.clear(); + } + } } /// The commands a compute encoder's last direct dispatch that instantiated made (its regions keyed /// for the device: `Variant::keyed_regions`), kept with the encoder's bind state -/// (`compute/live.rs`), whose kept state goes on to the device's next compute encoder: a later +/// (`compute/live.rs`), whose kept state goes on to the next compute encoder: a later /// dispatch, of the encoder or a later one, that takes the very [`Planned`] that one took takes /// them while the state binds the values they read, instantiating nothing /// (`WorkCounts::dispatches_instantiated_as_before`). Exact: @@ -2489,12 +2553,34 @@ fn record( let counted = (moved, core.generation().sampler_slots_changed()); live.memo.holds(&live.state, tables, &dispatch, counted) }); + // The sampler states, with the count of changes they are live at, where it is not. + let listing = (!held).then(|| core.device().argument_samplers_at()); + // Else an entry an earlier compute encoder of the command buffer settled and parked, + // where the table, read now, brings in the very state it settled (`compute/live.rs`). + let across = match (memo, &listing) { + (Some(dispatch), Some((changed, samplers))) => { + let thread = pipeline.generation().shared().counts.thread(); + live.settled_across( + tables, + (&dispatch, (moved, *changed)), + (*changed, samplers), + &function_tables, + thread, + )? + } + _ => Across::Missed, + }; if held { core.counts().dispatch_settled_as_before(); - } else { - // The sampler states, with the count of changes they are live at. - let (changed, samplers) = core.device().argument_samplers_at(); - let settling = (changed, samplers); + } else if let Across::Taken = across { + core.counts().dispatch_settled_across_encoders(); + } else if let Some(settling) = listing { + let changed = settling.0; + let refreshed = match across { + Across::Refreshed(maps) => Some(maps), + Across::Taken | Across::Missed => None, + }; + let settling = (settling, refreshed); let settled = settle_live(live, tables, (direct, gpu), function_tables, settling); // The kept state is no longer what the memo's entry settled. let Some((settled, flat_call)) = settled.inspect_err(|_| live.let_go())? else { diff --git a/crates/metal2vulkan-runtime/src/compute/live.rs b/crates/metal2vulkan-runtime/src/compute/live.rs index c5672cca6..11be46e3e 100644 --- a/crates/metal2vulkan-runtime/src/compute/live.rs +++ b/crates/metal2vulkan-runtime/src/compute/live.rs @@ -31,15 +31,17 @@ //! is made again, whole. The pipeline state's plan of a kept shape is found by identity first //! (`ComputePipelineState::planned_for`), so a dispatch whose offsets alone moved compares no //! shape at all, however many resources the encoder made resident. -//! - **Kept from one encoder to the next.** An encoder that ends gives its state, with its shape, -//! to its device ([`SpareLiveDispatches`]), and the next compute encoder opened starts from it, -//! as a dispatch starts from the one before it: exact for the reason a dispatch's is, every field -//! of the state a dispatch binds being derived again at each dispatch that settles. The memo of -//! what its last dispatch settled goes first ([`LiveDispatch::let_go`]): it holds the pipeline -//! state, sampler states and pipelines, where the state holds values alone (its bindings, its used -//! resources and argument samplers as a bind state lists them, its table's pipeline state held -//! weakly), so a kept one holds nothing alive. The lists of its resident textures' shadows and -//! carriers go too ([`ResidentShadows`], [`ResidentUnreadable`]). +//! - **Kept from one encoder to the next.** An encoder that ends leaves its state, with its shape, +//! to its command buffer's next compute encoder (**Parked in its command buffer**, below), and +//! the commit gives it to its device ([`SpareLiveDispatches`]), whose next compute encoder opened +//! starts from it, as a dispatch starts from the one before it: exact for the reason a dispatch's +//! is, every field of the state a dispatch binds being derived again at each dispatch that +//! settles. The memo of what its last dispatch settled goes as the device takes it +//! ([`LiveDispatch::let_go`]): it holds the pipeline state, sampler states and pipelines, where the +//! state holds values alone (its bindings, its used resources and argument samplers as a bind +//! state lists them, its table's pipeline state held weakly), so a kept one holds nothing alive. +//! The lists of its resident textures' shadows and carriers go at each end +//! ([`ResidentShadows`], [`ResidentUnreadable`]). //! - **Commands kept while the state binds what they read.** The commands its last direct dispatch //! that instantiated made are kept, with what that dispatch planned held weakly //! (`compute::Instantiated`), and go on with the state to the next encoder: a later dispatch of @@ -51,12 +53,29 @@ //! state to the next encoder: a dispatch that binds what one before it bound works none out //! again. The memo holds its textures, sampler states and host cells weakly, so a kept one holds //! nothing alive. +//! - **Parked in its command buffer.** A compute encoder's end parks its state, with what its last +//! dispatch settled, and the box of its core in its command buffer ([`Parked`]); the command +//! buffer's next compute encoder opens on them rather than on the device's spares +//! (`WorkCounts::parked_compute_taken`), and the commit gives them back to the device, the memo let +//! go. The memo's entry so goes on, and a dispatch whose new table, read, brings in the very state +//! the entry settled takes it ([`LiveDispatch::settled_across`], +//! `WorkCounts::dispatches_settled_across_encoders`): one encoder for each dispatch of the same +//! bindings settles once. Exact: the entry is a function of the bind state and of the inputs +//! `DispatchMemo` compares beside its table's stamp (`compute::DispatchMemo`), and the table's +//! stamp stands for the table-derived part of that state alone; bringing the state in place +//! notes every value it changed ([`Reshape::moved`]), so where it changed none, and the samplers' +//! maps (the table's and the residency's) are the entry's, the state is the one it settled. A +//! parked entry holds nothing its command buffer does not: its pipeline state, variant and +//! `VkPipeline`s the command buffer's dispatch held until it completes. The device's sampler +//! states the entry listed are let go as it parks, as are the resident textures' lists, and the +//! dispatch that takes it lists them again: those the device lists at the count of sampler slot +//! changes the entry compares, so the very states it listed. //! - **Resident textures looked at once a change.** A dispatch's look at the shadows of the //! textures the encoder made resident (`shadow::shadow_uses_of`), and a reading of texture //! handles' look for one a carrier holds (`pvrtc::degrade_unreadable`), read the lists kept here, //! made again only where they may have changed. -use metal2vulkan::bind::{BindShape, BindState, HeapPlacement, ImageblockSize}; +use metal2vulkan::bind::{BindShape, BindState, Dispatch, HeapPlacement, ImageblockSize}; use metal2vulkan::pipeline::Stage; use std::sync::{Arc, Mutex}; @@ -64,10 +83,12 @@ use super::{DispatchMemo, DispatchTables, Instantiated}; use crate::address_map::SamplerMaps; use crate::argument_table::Stamp; use crate::binding::{BindMemo, CommandUses}; -use crate::device::lock; +use crate::device::{lock, Device}; +use crate::encoder::{CoreBox, EncoderCore}; +use crate::error::Error; use crate::function_table::VisibleFunctionTable; use crate::heap_sets; -use crate::live_bind::Reshape; +use crate::live_bind::{Reshape, ValueKinds}; use crate::pipeline::{ComputePipelineState, WeakComputePipelineState}; use crate::pvrtc::ResidentUnreadable; use crate::sampler::SamplerState; @@ -158,7 +179,7 @@ impl LiveDispatch { /// resident, `samplers` listed (the device's sampler states at `changed` changes of their /// slots, those a variant's set-1 arrays hold alone where `trimmed`), and the live tables the /// pipeline state made. Each change that may change the shape is noted, and the shape kept only - /// where none may have. + /// where none may have. The kinds of values it changed. pub(in crate::compute) fn refresh( &mut self, tables: &DispatchTables<'_>, @@ -166,7 +187,7 @@ impl LiveDispatch { (changed, samplers, trimmed): (u64, &[SamplerState], bool), function_tables: &[VisibleFunctionTable], counts: Counting<'_>, - ) { + ) -> ValueKinds { let mut reshape = Reshape::default(); let pipeline = tables.pipeline; let views = pipeline.at_bind_views(); @@ -254,6 +275,45 @@ impl LiveDispatch { self.shape = None; } self.instantiated.moved(reshape.moved()); + reshape.moved() + } + + /// Whether the memo's entry, which an earlier compute encoder of the command buffer settled + /// and parked (the module docs, **Parked in its command buffer**), serves a direct dispatch of + /// `tables` and `dispatch` at `counted` moves and sampler slot changes: it holds in every + /// input but its table's stamp (`DispatchMemo::holds_but_stamp`), and the table, read now with + /// its samplers' maps and `listing` (the device's sampler states at their count of changes), + /// brings in the very state it settled, no value of any kind changed, with the samplers' maps + /// it was settled with. Then it goes on under the table's stamp ([`Across::Taken`]). Where the + /// entry holds but for the stamp, the state is brought in place either way, and a dispatch that + /// takes it not settles from the state as it lies ([`Across::Refreshed`]). + pub(in crate::compute) fn settled_across( + &mut self, + tables: &DispatchTables<'_>, + (dispatch, counted): (&Dispatch, (u64, u64)), + listing: (u64, &[SamplerState]), + function_tables: &[VisibleFunctionTable], + counts: Counting<'_>, + ) -> Result { + if !(self.memo).holds_but_stamp(&self.state, tables, dispatch, counted) { + return Ok(Across::Missed); + } + let maps = tables.sampler_maps()?; + let (changed, samplers) = listing; + let listing = (changed, samplers, false); + let moved = self.refresh(tables, &maps, listing, function_tables, counts); + let same = moved == ValueKinds::default() + && (self.memo.entry()).is_some_and(|kept| kept.settled.sampler_maps == maps); + if !same { + return Ok(Across::Refreshed(maps)); + } + debug_assert!( + (self.memo.entry()) + .is_some_and(|kept| *kept.settled.planned.shape == self.state.shape()), + "a parked dispatch memo taken for a state of another shape" + ); + self.memo.restamp(tables.table.stamp(), samplers); + Ok(Across::Taken) } /// That the state brought in place is the one a dispatch of `tables` makes whole @@ -378,3 +438,49 @@ impl SpareLiveDispatches { } } } + +/// What [`LiveDispatch::settled_across`] found of a dispatch. +pub(in crate::compute) enum Across { + /// The memo's entry serves it, under its table's stamp now. + Taken, + /// The entry holds but for the stamp, and the state was brought in place with these maps of + /// the table's samplers and the device's sampler states untrimmed; a value moved, or the maps + /// are not the entry's: the dispatch settles from the state as it lies, which a refresh of the + /// same inputs leaves as it is (`compute::settle_live`). + Refreshed(SamplerMaps), + /// The entry does not hold but for the stamp: nothing was done. + Missed, +} + +/// What a compute encoder's end parks in its command buffer for the command buffer's next compute +/// encoder, in place of the device's spares (the module docs, **Parked in its command buffer**): +/// the box of its core, emptied, and its bind state with what its last dispatch settled. +pub(crate) struct Parked { + room: CoreBox, + live: Box, +} + +impl Parked { + /// `room` and `live`, an ended compute encoder's: the lists of its resident textures' shadows + /// and carriers emptied, as the device's spares empty them, and the sampler states its memo's + /// entry listed let go (the device's live ones, which its command buffer holds none of: + /// `DispatchMemo::unlist_samplers`). + pub(in crate::compute) fn new(room: CoreBox, mut live: Box) -> Parked { + live.shadows.let_go(); + live.unreadable.let_go(); + live.memo.unlist_samplers(); + Parked { room, live } + } + + /// The core's box and the bind state, for the compute encoder that opens on them. + pub(in crate::compute) fn into_parts(self) -> (CoreBox, Box) { + (self.room, self.live) + } + + /// Give them back to `device`'s spares as their command buffer commits: the box to its + /// cores', the state to its bind states', its memo let go ([`SpareLiveDispatches::give`]). + pub(crate) fn give_back(self, device: &Device) { + EncoderCore::give_room(device, self.room); + device.shared().live_dispatches.give(self.live); + } +} diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 042cb2895..f39f13fe1 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -728,6 +728,9 @@ pub(super) struct DeviceShared { /// The bind states its ended compute encoders left, which the next ones start from /// (`compute/live.rs`). pub(super) live_dispatches: crate::compute::SpareLiveDispatches, + /// The storage of the lists of records its released command buffers left, which the next ones + /// start on (`command_buffer/record_storage.rs`). + pub(super) record_storage: crate::command_buffer::record_storage::SpareRecordStorage, /// The usage shadows its textures made (`texture/usage_shadow.rs`): a kept list of resident /// textures' shadows is listed again where it moved (`shadow::ResidentShadows`). pub(super) usage_shadows_made: std::sync::atomic::AtomicU64, @@ -3182,6 +3185,7 @@ impl Device { live_binds: Default::default(), coverage_pools: Default::default(), live_dispatches: Default::default(), + record_storage: Default::default(), usage_shadows_made: Default::default(), face_swaps: Default::default(), heap_textures_end: Default::default(), diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 57edd14bc..d2960ffcc 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -48,6 +48,7 @@ use super::buffer::Buffer; use super::churn_counts::KeepBy; use super::command_buffer::rebound_use::Unlogged; use super::command_buffer::{recording_error, CommandBuffer, State}; +use super::compute::Parked; use super::deferred::{Deferred, StepInputs}; use super::degradation::NoticesFor; use super::encoder_fold::{self, Fold, FoldEnd, Joining}; @@ -110,8 +111,11 @@ static CORES: AtomicU64 = AtomicU64::new(1); /// opens while more than these are open makes a box of its own. const SPARE_CORES: usize = 4; -/// The box of an ended render encoder's core, emptied: room for the next encoder's core. -struct CoreRoom(Box>); +/// The box of an ended render or compute encoder's core, emptied: room for the next encoder's core. +pub(crate) type CoreBox = Box>; + +/// A [`CoreBox`] its device keeps ([`SpareCores`]). +struct CoreRoom(CoreBox); /// The encoders of a command buffer whose barriers the scheduler plans and records before each in /// a command buffer of barriers of its own (the module docs): each later encoder's own begins @@ -129,14 +133,14 @@ pub(crate) struct SpareCores(Mutex>); impl SpareCores { /// Room for a core: the latest box an ended encoder gave back, else a new one. - fn take(&self) -> Box> { + fn take(&self) -> CoreBox { let room = lock(&self.0).pop(); room.map_or_else(Box::new_uninit, |CoreRoom(room)| room) } /// Keep `room`, an ended encoder's core's box, emptied, where fewer than [`SPARE_CORES`] are /// kept; else it goes. - fn give(&self, room: Box>) { + fn give(&self, room: CoreBox) { let mut spare = lock(&self.0); if spare.len() < SPARE_CORES { spare.push(CoreRoom(room)); @@ -657,21 +661,37 @@ impl EncoderCore { Box::write(room, self) } + /// The core in `room`, the box of an ended encoder's core its command buffer parked + /// (`compute/live.rs`'s `Parked`). + pub(super) fn boxed_in(self, room: CoreBox) -> Box { + Box::write(room, self) + } + /// The core out of its box, `core`, which its device keeps emptied for the next /// ([`SpareCores`]). pub(super) fn unboxed(core: Box) -> EncoderCore { + let (core, room) = EncoderCore::unboxed_apart(core); + core.device().shared().cores.give(room); + core + } + + /// The core out of its box, `core`, and the box, emptied, for the caller to keep. + pub(super) fn unboxed_apart(core: Box) -> (EncoderCore, CoreBox) { let raw = Box::into_raw(core); // SAFETY: `raw` is a box's pointer, its core live and read out once, here; the box is then // made again over the same allocation as room for a core (`MaybeUninit` has // `EncoderCore`'s layout), so the core is neither dropped through it nor read again. - let (core, room) = unsafe { + unsafe { ( raw.read(), Box::from_raw(raw.cast::>()), ) - }; - core.device().shared().cores.give(room); - core + } + } + + /// Give `room`, an emptied core's box, back to `device`'s spares ([`SpareCores`]). + pub(crate) fn give_room(device: &Device, room: CoreBox) { + device.shared().cores.give(room); } /// Open an encoder on `command_buffer` for Metal's `call`, `ordered` when Metal runs its @@ -3176,11 +3196,13 @@ impl EncoderCore { /// `unit_work`: a compute encoder's dispatches since its last record, which its unit of /// command predication takes under this end's one lock of the command buffer's state where /// the command buffer has no record (`predication.rs`); `None` where the encoder's end gave - /// them to its unit already, and for other encoders. + /// them to its unit already, and for other encoders. `parked`: a compute encoder's core box + /// and bind state, which the command buffer keeps for its next compute encoder under the same + /// lock (`compute/live.rs`). pub(super) fn end_with_replay( mut self, kind: EncoderKind, - residency: Option, + (residency, parked): (Option, Option), replay: Option, unit_work: Option, ) -> Result<(), Error> { @@ -3321,6 +3343,9 @@ impl EncoderCore { // Noted under the one lock its end takes: an end that fails before here abandons the // command buffer, which is never scheduled. state.note_scheduled(work); + // Kept for the command buffer's next compute encoder; one kept already, of an encoder that + // did not take it, goes back to the device after the lock. + let unparked = parked.and_then(|parked| state.park_compute(parked)); if let Some(worked) = unit_work { state.predication_mut().note_work(worked); } @@ -3509,6 +3534,9 @@ impl EncoderCore { let device = open.command_buffer.device(); device.shared().scheduler.spare_logs().give(log); } + if let Some(unparked) = unparked { + unparked.give_back(open.command_buffer.device()); + } open.ended = true; Ok(()) } diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index dbc4d95bf..1a2fd7df2 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -4531,7 +4531,7 @@ impl RenderLowering { } EncoderCore::unboxed(core).end_with_replay( EncoderKind::Render, - Some(residency), + (Some(residency), None), log.map(Replay::Render), None, ) diff --git a/crates/metal2vulkan-runtime/src/tests/compute_parked.rs b/crates/metal2vulkan-runtime/src/tests/compute_parked.rs new file mode 100644 index 000000000..582626416 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/compute_parked.rs @@ -0,0 +1,194 @@ +//! A compute encoder's end parks the box of its core and its bind state, with what its last +//! dispatch settled, in its command buffer, and the command buffer's next compute encoder opens on +//! them (`compute/live.rs`'s **Parked in its command buffer**): a dispatch whose new table brings in +//! the very state the last compute encoder's dispatch bound takes what that one settled +//! (`WorkCounts::dispatches_settled_across_encoders`), and one that binds otherwise settles again. +//! The commit gives them back to the device, so each command buffer's first compute encoder opens on +//! the device's spares (`WorkCounts::parked_compute_taken` counts the others). +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The kernel is `scale_and_offset` of the +//! owned fixture `validation/fixtures/public/examples/runtime_examples.ll` +//! (`output[i] = input[i] * scale + i`), with a scale of 1 and an input of `i`, so each word it +//! writes is `2 * i`. + +use super::blit_holds::{device, Scratch, WAIT}; +use super::dispatch_pending::state; +use super::encoder_holds::words_of; +use crate::{ + Buffer, CommandBuffer, CommandBufferStatus, ComputePipelineState, Device, ResourceOptions, + Size, WorkCounts, +}; +use metal2vulkan::bind::SamplerDescriptor; + +/// The words a dispatch writes, one threadgroup's. +const WORDS: u64 = 64; + +/// The compute encoders of a command buffer. +const ENCODERS: u64 = 8; + +/// The byte a blit encoder fills with. +const FILL: u8 = 0x5a; + +/// The device, the kernel's state, its scale of 1 and its input `0, 1, 2, ...` as floats. +pub(super) struct Kernel { + pub(super) device: Device, + state: ComputePipelineState, + scale: Buffer, + input: Buffer, +} + +impl Kernel { + pub(super) fn new(scratch: &Scratch) -> Kernel { + let device = device(&scratch.0); + let state = state(&device); + let scale = + (device.new_buffer_with_bytes(&1f32.to_le_bytes(), ResourceOptions::shared())).unwrap(); + let input: Vec = (0..WORDS).flat_map(|i| (i as f32).to_le_bytes()).collect(); + let input = (device.new_buffer_with_bytes(&input, ResourceOptions::shared())).unwrap(); + Kernel { + device, + state, + scale, + input, + } + } + + /// A `Shared` buffer of `count` dispatches' words of zeros. + pub(super) fn output(&self, count: u64) -> Buffer { + let bytes = vec![0; (count * WORDS * 4) as usize]; + (self + .device + .new_buffer_with_bytes(&bytes, ResourceOptions::shared())) + .unwrap() + } + + /// A compute encoder of `command_buffer` of one dispatch that writes `output` from byte + /// `offset` on, ended. + pub(super) fn dispatch( + &self, + command_buffer: &CommandBuffer, + (output, offset): (&Buffer, u64), + ) { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&self.state).unwrap(); + encoder.set_buffer(Some(&self.input), 0, 0).unwrap(); + encoder.set_buffer(Some(output), offset, 1).unwrap(); + encoder.set_buffer(Some(&self.scale), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(WORDS, 1, 1), Size::new(WORDS, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + } + + /// A blit encoder of `command_buffer` that fills `output`'s first dispatch's words with + /// [`FILL`], ended. + fn fill(&self, command_buffer: &CommandBuffer, output: &Buffer) { + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(output, 0..WORDS * 4, FILL).unwrap(); + blit.end_encoding().unwrap(); + } + + /// Commit `command_buffer` and wait for it: it completes with no error. + pub(super) fn run(&self, command_buffer: &CommandBuffer) { + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!( + command_buffer.status(), + CommandBufferStatus::Completed, + "{:?}", + command_buffer.error() + ); + } + + /// Warm: the kernel's pipelines made, so each dispatch below records at once. + pub(super) fn warm(&self) { + let output = self.output(1); + let queue = self.device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + self.dispatch(&command_buffer, (&output, 0)); + self.run(&command_buffer); + } +} + +/// What moved of the counts the parking names, from `before` to `after`. +#[derive(Debug, PartialEq, Eq)] +struct Moved { + /// `parked_compute_taken`. + parked: u64, + /// `dispatches_settled_across_encoders`. + across: u64, +} + +impl Moved { + fn of(before: &WorkCounts, after: &WorkCounts) -> Moved { + Moved { + parked: after.parked_compute_taken - before.parked_compute_taken, + across: after.dispatches_settled_across_encoders + - before.dispatches_settled_across_encoders, + } + } +} + +/// The words `2 * i` of `count` dispatches, as floats' bits. +fn written(count: u64) -> Vec { + (0..count) + .flat_map(|_| (0..WORDS).map(|i| (2.0 * i as f32).to_bits())) + .collect() +} + +/// Command buffers of [`ENCODERS`] compute encoders of the same bindings, each after a blit +/// encoder that fills their output, on a device with a live sampler state the kernel binds none +/// of (each dispatch lists it among the device's, and a parked entry lets it go): every compute +/// encoder but each command buffer's first opens on what the one before it parked and takes what +/// its dispatch settled, and the last one's words are what it wrote, after the fill before it. +#[test] +fn compute_encoders_of_the_same_bindings_settle_once_a_command_buffer() { + let scratch = Scratch::new("parked-same"); + let kernel = Kernel::new(&scratch); + let _sampler = (kernel.device.new_sampler_state(&SamplerDescriptor::new())).unwrap(); + kernel.warm(); + let queue = kernel.device.new_command_queue().unwrap(); + let output = kernel.output(1); + for round in 0..2 { + let before = kernel.device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for _ in 0..ENCODERS { + kernel.fill(&command_buffer, &output); + kernel.dispatch(&command_buffer, (&output, 0)); + } + let moved = Moved::of(&before, &kernel.device.work_counts()); + kernel.run(&command_buffer); + assert_eq!(words_of(&output), written(1), "round {round}: the words"); + let want = Moved { + parked: ENCODERS - 1, + across: ENCODERS - 1, + }; + assert_eq!(moved, want, "round {round}: the parked and settled across"); + } +} + +/// A command buffer of [`ENCODERS`] compute encoders that each write their own words of one +/// output: each but the first opens on what the one before it parked, and settles again, its +/// output's offset moved; every dispatch's words are what it wrote. +#[test] +fn a_compute_encoder_that_binds_another_offset_settles_again() { + let scratch = Scratch::new("parked-moved"); + let kernel = Kernel::new(&scratch); + kernel.warm(); + let queue = kernel.device.new_command_queue().unwrap(); + let output = kernel.output(ENCODERS); + let before = kernel.device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for k in 0..ENCODERS { + kernel.dispatch(&command_buffer, (&output, k * WORDS * 4)); + } + let moved = Moved::of(&before, &kernel.device.work_counts()); + kernel.run(&command_buffer); + assert_eq!(words_of(&output), written(ENCODERS), "the words"); + let want = Moved { + parked: ENCODERS - 1, + across: 0, + }; + assert_eq!(moved, want, "the parked and settled across"); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 11860facb..bbd1a2be2 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -86,6 +86,8 @@ mod compute_bind_memo; mod compute_create_bench; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod compute_instantiated; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod compute_parked; mod contexts; mod copied; #[cfg(any(m2v_gpu, m2v_cpu_icd))] @@ -598,6 +600,8 @@ mod recent_shape_keys; mod reclaim_submit_bench; mod record_pass_formats; #[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod record_storage; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] mod recorded_at_the_call; mod recorder_shards; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan-runtime/src/tests/record_storage.rs b/crates/metal2vulkan-runtime/src/tests/record_storage.rs new file mode 100644 index 000000000..bee41f7d8 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/record_storage.rs @@ -0,0 +1,58 @@ +//! A command buffer starts on the storage of the lists of records a released command buffer of +//! its device left, emptied with its room kept (`command_buffer/record_storage.rs`): one of no +//! more encoders than that one grows none of its lists (`WorkCounts::record_lists_grown`). +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. The kernel is `compute_parked.rs`'s. + +use super::blit_holds::{until, Scratch}; +use super::compute_parked::Kernel; +use crate::{Buffer, CommandQueue}; + +/// The compute encoders of each command buffer, one dispatch each. +const ENCODERS: u64 = 32; + +/// How many lists of a command buffer of [`ENCODERS`] compute encoders of `queue` grew, the +/// command buffer committed, completed and dropped: read once its device kept its storage +/// (`WorkCounts::record_storage_kept`), at its release. +fn grown(kernel: &Kernel, queue: &CommandQueue, output: &Buffer) -> u64 { + let before = kernel.device.work_counts(); + let command_buffer = queue.command_buffer().unwrap(); + for _ in 0..ENCODERS { + kernel.dispatch(&command_buffer, (output, 0)); + } + kernel.run(&command_buffer); + drop(command_buffer); + until("the command buffer's release kept its storage", || { + kernel.device.work_counts().record_storage_kept > before.record_storage_kept + }); + kernel.device.work_counts().record_lists_grown - before.record_lists_grown +} + +/// Command buffers of [`ENCODERS`] compute encoders each, one after another's release, the kernel's +/// pipelines made first (a dispatch whose pipeline is being made ends its group, so the groups +/// and the lists of a command buffer that meets one differ from the next one's): the first's lists +/// grow past the room the warming command buffer of one dispatch left (its ended encoders' +/// records and their recordings at least), and each later one starts on the room the one before +/// it left and grows none. +#[test] +fn a_command_buffer_of_as_many_encoders_as_the_last_grows_no_list() { + let scratch = Scratch::new("record-storage"); + let kernel = Kernel::new(&scratch); + kernel.warm(); + until( + "the warming command buffer's release kept its storage", + || kernel.device.work_counts().record_storage_kept > 0, + ); + let queue = kernel.device.new_command_queue().unwrap(); + let output = kernel.output(1); + let first = grown(&kernel, &queue, &output); + assert!( + first >= 2, + "the first command buffer's lists grown: {first}" + ); + for round in 1..3 { + let grown = grown(&kernel, &queue, &output); + assert_eq!(grown, 0, "round {round}: the lists grown"); + } +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index bd08b9290..e7f34f0a9 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -364,6 +364,9 @@ pub(crate) struct Counters { inline_passes_split: AtomicU64, encoders_barriered_at_open: AtomicU64, encoders_folded: AtomicU64, + parked_compute_taken: AtomicU64, + record_lists_grown: AtomicU64, + record_storage_kept: AtomicU64, kept_draws_carried: AtomicU64, kept_draws_carried_across: AtomicU64, kept_draws_carry_dropped: [AtomicU64; CarryDropped::COUNT], @@ -811,6 +814,7 @@ struct CommandCounters { dispatch_shapes_found: AtomicU64, dispatch_used_resources_listed: AtomicU64, dispatches_settled_as_before: AtomicU64, + dispatches_settled_across_encoders: AtomicU64, dispatches_instantiated: AtomicU64, dispatches_instantiated_as_before: AtomicU64, dispatches_skipped_inert: AtomicU64, @@ -1992,6 +1996,14 @@ impl Counting<'_> { self.0.add(|counts| &counts.dispatches_settled_as_before, 1); } + /// A compute encoder's dispatch that took what an earlier compute encoder of its command + /// buffer settled, its table bringing in the very state that one bound + /// (`compute::LiveDispatch::settled_across`). + pub(crate) fn dispatch_settled_across_encoders(&self) { + self.0 + .add(|counts| &counts.dispatches_settled_across_encoders, 1); + } + /// A dispatch whose commands `compute::record` instantiated. pub(crate) fn dispatch_instantiated(&self) { self.0.add(|counts| &counts.dispatches_instantiated, 1); @@ -3727,6 +3739,24 @@ impl Counters { self.encoders_folded.fetch_add(1, Ordering::Relaxed); } + /// A compute encoder opened on the core's box and the bind state its command buffer's last + /// compute encoder parked (`compute/live.rs`'s `Parked`). + pub(crate) fn parked_compute_taken(&self) { + self.parked_compute_taken.fetch_add(1, Ordering::Relaxed); + } + + /// `lists` of a released command buffer's lists of records held more room than it started + /// with (`command_buffer/record_storage.rs`). + pub(crate) fn record_lists_grown(&self, lists: u64) { + self.record_lists_grown.fetch_add(lists, Ordering::Relaxed); + } + + /// The device kept a released command buffer's storage of its lists of records for the next + /// (`command_buffer/record_storage.rs`). + pub(crate) fn record_storage_kept(&self) { + self.record_storage_kept.fetch_add(1, Ordering::Relaxed); + } + /// A render pass's first instance began inline in a primary command buffer of its encoder's /// (`render/inline_first.rs`). pub(crate) fn inline_pass(&self) { @@ -7163,6 +7193,22 @@ pub struct WorkCounts { /// command buffer for it, of barriers or of its own. Of `encoder_command_buffers_begun`'s /// encoders, those it does not count. pub encoders_folded: u64, + /// Compute encoders that opened on the box of their core and the bind state (with what its + /// last dispatch settled) the command buffer's last compute encoder left, rather than on the + /// device's spares: each compute encoder's end parks them in its command buffer for the next, + /// and the commit gives them back to the device (`compute/live.rs`'s `Parked`). + pub parked_compute_taken: u64, + /// The lists a released command buffer keeps of what its encoders ended with (its ended + /// encoders' records, their recordings, a group's logs its members did not keep and those held + /// for its commit) that held more room as it was released than the storage it started on: + /// counted once each, at the release. A command buffer starts on the storage a released one + /// of the device left (`record_storage_kept`), emptied with its room kept, so one of no more + /// encoders than that one's grows none. + pub record_lists_grown: u64, + /// Released command buffers whose storage of their lists of records the device kept, emptied, + /// for the command buffers it makes next to start on: at most 2 at once, each of at most + /// 8 MiB of room, the latest taken first. + pub record_storage_kept: u64, /// Of `command_buffers_begun`, the device's own submissions' and staging submissions'. pub command_buffers_begun_internal: u64, /// Of `encoder_command_buffers_begun`, the encoders' own `VkCommandBuffer`s begun ahead: a @@ -8972,6 +9018,12 @@ pub struct WorkCounts { /// visible-function table, while no no-copy buffer moved, no sampler state was made or went /// and no buffer took a resident indirect command buffer's ID (`compute::DispatchMemo`). pub dispatches_settled_as_before: u64, + /// Compute encoders' dispatches that took the bind state, variant, plan, commands and made + /// `VkPipeline`s an earlier compute encoder of their command buffer settled last, rather than + /// settling them again: those whose new table, read, brought in the very state that dispatch + /// bound (no value of any kind changed, the samplers' maps the same), with every other input + /// of `dispatches_settled_as_before`'s the same. Not counted there. + pub dispatches_settled_across_encoders: u64, /// Dispatches whose commands (`BindingPlan::instantiate_dispatch`'s) `compute::record` /// instantiated: of a compute encoder (direct, indirect), of an indirect command buffer's /// execution, or of a host step. None for a compute encoder's dispatch counted in @@ -11384,6 +11436,9 @@ impl Device { inline_passes: counters.inline_passes.load(Ordering::Relaxed), encoders_barriered_at_open: counters.encoders_barriered_at_open.load(Ordering::Relaxed), encoders_folded: counters.encoders_folded.load(Ordering::Relaxed), + parked_compute_taken: counters.parked_compute_taken.load(Ordering::Relaxed), + record_lists_grown: counters.record_lists_grown.load(Ordering::Relaxed), + record_storage_kept: counters.record_storage_kept.load(Ordering::Relaxed), kept_draws_carried: counters.kept_draws_carried.load(Ordering::Relaxed), kept_draws_carried_across: counters.kept_draws_carried_across.load(Ordering::Relaxed), kept_draws_carry_dropped_between: carry_dropped(CarryDropped::Between), @@ -11783,6 +11838,9 @@ impl Device { }), host_holds_looked_up: commands(|counts| &counts.host_holds_looked_up), dispatches_settled_as_before: commands(|counts| &counts.dispatches_settled_as_before), + dispatches_settled_across_encoders: commands(|counts| { + &counts.dispatches_settled_across_encoders + }), dispatches_instantiated: commands(|counts| &counts.dispatches_instantiated), dispatches_instantiated_as_before: commands(|counts| { &counts.dispatches_instantiated_as_before diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index e47219763..cd26664d6 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2875,6 +2875,7 @@ field metal2vulkan-runtime::WorkCounts.dispatches_instantiated pub dispatches_in field metal2vulkan-runtime::WorkCounts.dispatches_instantiated_as_before pub dispatches_instantiated_as_before: u64 field metal2vulkan-runtime::WorkCounts.dispatches_planned_as_before pub dispatches_planned_as_before: u64 field metal2vulkan-runtime::WorkCounts.dispatches_pushing_set_zero pub dispatches_pushing_set_zero: u64 +field metal2vulkan-runtime::WorkCounts.dispatches_settled_across_encoders pub dispatches_settled_across_encoders: u64 field metal2vulkan-runtime::WorkCounts.dispatches_settled_as_before pub dispatches_settled_as_before: u64 field metal2vulkan-runtime::WorkCounts.dispatches_skipped_inert pub dispatches_skipped_inert: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_buffer_imports_dedicated pub dma_buf_buffer_imports_dedicated: u64 @@ -3317,6 +3318,7 @@ field metal2vulkan-runtime::WorkCounts.owned_kernel_spirv_bytes pub owned_kernel field metal2vulkan-runtime::WorkCounts.owned_kernels_made pub owned_kernels_made: u64 field metal2vulkan-runtime::WorkCounts.page_buffer_blocks_made pub page_buffer_blocks_made: u64 field metal2vulkan-runtime::WorkCounts.page_buffer_blocks_plain pub page_buffer_blocks_plain: u64 +field metal2vulkan-runtime::WorkCounts.parked_compute_taken pub parked_compute_taken: u64 field metal2vulkan-runtime::WorkCounts.passes_not_inline_actions pub passes_not_inline_actions: u64 field metal2vulkan-runtime::WorkCounts.passes_not_inline_actions_dont_care_load pub passes_not_inline_actions_dont_care_load: u64 field metal2vulkan-runtime::WorkCounts.passes_not_inline_actions_resolve pub passes_not_inline_actions_resolve: u64 @@ -3437,6 +3439,8 @@ field metal2vulkan-runtime::WorkCounts.reading_draws_split_unreadable_own_pixel_ field metal2vulkan-runtime::WorkCounts.reading_draws_split_variant_refused pub reading_draws_split_variant_refused: u64 field metal2vulkan-runtime::WorkCounts.reading_draws_split_views pub reading_draws_split_views: u64 field metal2vulkan-runtime::WorkCounts.reading_draws_split_visibility_query pub reading_draws_split_visibility_query: u64 +field metal2vulkan-runtime::WorkCounts.record_lists_grown pub record_lists_grown: u64 +field metal2vulkan-runtime::WorkCounts.record_storage_kept pub record_storage_kept: u64 field metal2vulkan-runtime::WorkCounts.reencodes_refused pub reencodes_refused: u64 field metal2vulkan-runtime::WorkCounts.region_pipelines_evicted pub region_pipelines_evicted: u64 field metal2vulkan-runtime::WorkCounts.registrations_waited pub registrations_waited: u64