From aa2be705d554f9e6d37cd1113cd417b071ed1040 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 19 Oct 2026 00:16:00 +0300 Subject: [PATCH] Let a new texture register while a batch is replayed or submitted, waiting for no submission A batch's submission takes the new resources' first work (FirstMoves::take), which holds the device's place in the submissions' order until its vkQueueSubmit returns, and every registration of a new resource (a texture's, buffer's, fill's, bytes' or texels' first move, as a Shared or Private texture is made) waited for that order, so that no texture's heap set elements were written between a batch's take and its submission. Two things made a texture's making wait long inside that span: the batch's deferred command buffers were replayed after the take, and MoltenVK encodes a command buffer's Metal commands inside vkQueueSubmit on the calling thread (5 to 32 ms for 4096 to 65536 fills on the M3 Max). In the consumer's guest on the Iris Xe with deferred recording, the guest's task thread blocked 1311 ms over 110 such waits (about 17 ms a frame). Metal's makes wait for no submission. Now: - A batch's deferred command buffers replay before the take (crate::recorder::resolve on each, waiting for a replay in progress), with no lock a registration takes; their handles stay as encoded until the vkQueueSubmit, which finds them replayed. Only the barrier command buffers the submission records after the take replay inside the order. What replays, and the commands, are unchanged. - On a device whose heap sets take writes while a command buffer that binds them is pending (descriptorBindingUpdateUnusedWhilePending: every committed profile but the Vulkan 1.2 floor's), a batch holds the texture slots' writes over that span instead (FirstMoves::take_holding, heap_sets::hold): elements asked meanwhile are written in order as the hold ends, before the batch's place in the order goes, and a registration takes no place. A device without the feature keeps its registrations ordered (FirstMoves::ordered). - New WorkCounts fields: heap_slot_writes_deferred (the writes a hold deferred) and registrations_waited (registrations that found a submission holding the order and waited for it, counted only where registrations are ordered). - Docs: texture/first_move.rs's order, heap_sets.rs, and the lane's module docs. Verified, as the commits state: - runtime_lane::first_use::a_new_texture_waits_for_no_submission_s_replay times a Private texture's making (a Shared one moves on the host where VK_EXT_host_image_copy exists and never waited) and now asserts the making added no wait for a place, printing its time. On the 780M and RX 7900 XTX (RADV) it took 0.04 to 0.19 ms while the command buffer was scheduled 58 to 64 ms after its commit; with the replay moved back after the take it took 56 to 60 ms. - On the M3 Max through MoltenVK (60 makings after commits of 4096 to 65536 fills): before the slot-write hold 20 makings waited for the order, up to 13.0 ms; with it none waited, the slowest taking 0.158 ms. - The FirstMoves unit tests, among them a registration that waits for no submission where batches hold the slots and one that waits where registrations are ordered, and the count's tests: first_move, heap_sets and exit_guard tests, 62 passed. - runtime_lane::first_use's 11 tests on the UHD 770 and lavapipe. Beside 128 busy threads and as 8 parallel copies, on lavapipe and the UHD 770, every run passed with 0 waits for a place (183 makings, the longest 0.55 ms on lavapipe and 0.23 ms on ANV); the earlier time-ratio failures were the host's load and the validation layer's lock, not a wait of the runtime's. - clippy plain, --cfg m2v_gpu and --cfg m2v_cpu_icd; Rustdoc -D warnings. --- .../src/command_buffer/submit.rs | 16 ++ .../metal2vulkan-runtime/src/device/submit.rs | 13 -- crates/metal2vulkan-runtime/src/heap_sets.rs | 108 +++++++++++-- crates/metal2vulkan-runtime/src/texture.rs | 8 +- .../src/texture/first_move.rs | 151 ++++++++++++++++-- .../metal2vulkan-runtime/src/work_counts.rs | 23 +++ .../src/runtime_lane/first_use.rs | 94 +++++++++++ 7 files changed, 378 insertions(+), 35 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 140c58f4c..c6bc3eb2e 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -522,6 +522,18 @@ impl CommandBufferShared { exit_uses.push(image.transition_use()); } } + // Its encoders' deferred command buffers replayed now, where the recorder's thread has + // not yet (`recorder`), waiting for a replay in progress: before the first work's take, + // which holds the submissions' order until the submission is made, and which a new + // resource's registration waits for where registrations wait for their place + // (`texture/first_move.rs`). A texture made meanwhile so waits for no replay. Each keeps + // its handle as encoded until the submission (below), which finds it replayed. + for buffer in encoders.iter().flat_map(|recorded| &recorded.raws) { + // SAFETY: each ended, and its command buffer committed; inside the scheduler's + // section. + unsafe { crate::recorder::resolve(raw, *buffer) } + .map_err(|error| recording_error(device, crate::error::vulkan(error)))?; + } // The new resources' first work, before every command (`texture/first_move.rs`), given // back if the submission is not made. A batch's commands may reach every texture // unnamed, so it takes every move, those of images bound to host pages among them, whose @@ -837,6 +849,10 @@ impl CommandBufferShared { true => (&signal_semaphores[..], &signal_values[..]), false => (&[][..], &[][..]), }; + // Its deferred command buffers go as their replays (`recorder`), after every check above + // that compares them as encoded: its encoders', replayed before the first work's take + // (above); the barriers recorded since, replayed here where the recorder's thread has + // not yet reached them. for buffer in work.iter_mut() { // SAFETY: each ended, and its command buffer committed; inside the scheduler's // section. diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs index b49b87e99..88795a739 100644 --- a/crates/metal2vulkan-runtime/src/device/submit.rs +++ b/crates/metal2vulkan-runtime/src/device/submit.rs @@ -291,19 +291,6 @@ impl Device { } } - /// submission made before on each `VkQueue` completed ([`drain_submitted`]), each image's - /// [`drain_submitted`]: Self::drain_submitted - let taken = firsts.take_keeps(named); - if !taken.has_keeps() { - return Ok(()); - } - // batch's last barrier, `tracker.rs`'s `to_host`). - self.drain_submitted()?; - /// Wait until every batch submitted to each `VkQueue` before now completed. - fn drain_submitted(&self) -> Result<(), Error> { - let shared = self.shared(); - let (timelines, values): (Vec, Vec) = (shared.queues.iter()) - .unzip(); /// Bind `binds` to `buffer`, a sparse buffer no command has used, with one /// `vkQueueBindSparse` on the device's first `VkQueue` that signals the internal timeline, /// and return without waiting for it: every submission made after it, on every `VkQueue`, diff --git a/crates/metal2vulkan-runtime/src/heap_sets.rs b/crates/metal2vulkan-runtime/src/heap_sets.rs index f529b5611..5c62389b3 100644 --- a/crates/metal2vulkan-runtime/src/heap_sets.rs +++ b/crates/metal2vulkan-runtime/src/heap_sets.rs @@ -20,6 +20,11 @@ //! each image array holds the texture at ID `i` as the array's class takes it //! (`bind::heap_element`: its view where it fits the class, else the neutral), written as the //! texture takes the slot ([`place`]), for each set that lives then, and by a set made later +//! for each texture that lives then. A batch holds those writes from its first work's take +//! until its submission was made ([`hold`]): one asked meanwhile is made then, before the next +//! submission takes its first work, so no texture registered after the take, whose move is +//! not the batch's, is in its sets or table in `UNDEFINED` (`texture/first_move.rs`), and its +//! making waits for no submission. A rebind or a detach of host pages writes again the //! elements of the textures whose images or texel views lie in those bytes ([`renew_over`]), //! and of no other texture (`WorkCounts::heap_slots_rewritten`). A texture the class fits that it cannot view (a format //! the device cannot sample or store formatless, or that needs its function's decode) is the @@ -125,6 +130,11 @@ pub(super) struct DeviceHeaps { /// What a rebind or a detach replaced ([`retire`]), which waits for the command buffers /// committed before it. replaced: Retirement, + /// The batches holding the texture slots' writes ([`hold`]): while one is, a write waits in + /// `deferred`. + holds: usize, + /// The slot writes asked while a batch held them, in order, made as the last hold ends. + deferred: VecDeque, } /// A texture the table and the heap sets hold: its slot's generation and hold serial when it @@ -363,6 +373,37 @@ impl DeviceHeaps { .ok_or_else(|| internal("a texture table not made")) } + /// Write `slots` ([`sync`]): the slots that failed, each with its error, their entries the + /// neutral's. Their holders go to `held`, to drop once the lock is free. + fn write_slots( + &mut self, + device: &Device, + slots: Slots, + held: &mut Vec, + notes: &mut Notes, + ) -> Vec<(u64, Error)> { + let (ids, force): (Vec, bool) = match slots { + Slots::Changed(id) => (vec![id], false), + Slots::All => (self.textures.keys().copied().collect(), true), + Slots::Over(key) => { + let over = self.textures.iter(); + let over = over.filter(|(_, placed)| placed.bytes == Some(key)); + (over.map(|(&id, _)| id).collect(), true) + } + }; + if force { + device.shared().counts.heap_slots_rewritten(ids.len()); + } + let mut failed = Vec::new(); + for id in ids { + if let Err(error) = self.sync(device, id, force, held, notes) { + let cleared = self.clear(device, id); + failed.push((id, cleared.err().unwrap_or(error))); + } + } + failed + } + /// Write texture slot `id` into the table and every heap set where its holder changed since /// (whatever changed where `force`, a rebind's): its holder's elements, or the neutral's entry where /// it has none. The holder goes to `held`, to drop once the lock is free. @@ -1083,31 +1124,76 @@ enum Slots { Over(ResourceKey), } +/// Write `slots`: a changed one where its holder changed, the others whatever changed. While a +/// batch holds the slots' writes ([`hold`]), they wait for it. fn sync(device: &Device, slots: Slots) { let mut held = Vec::new(); let mut notes = Notes::default(); let failed = { let mut heaps = lock(&device.shared().heaps); - let ids: Vec = match force { - true => heaps.textures.keys().copied().collect(), - false => vec![id], - }; - let mut failed = None; - for id in ids { - if let Err(error) = heaps.sync(device, id, force, &mut held, &mut notes) { - let cleared = heaps.clear(device, id); - failed = Some((id, cleared.err().unwrap_or(error))); + match heaps.holds { + 0 => heaps.write_slots(device, slots, &mut held, &mut notes), + _ => { + heaps.deferred.push_back(slots); + device.shared().counts.heap_slot_writes_deferred(); + Vec::new() } } - failed }; drop(held); notes.announce(device); - if let Some((id, error)) = failed { + for (id, error) in failed { failed_write(device, id, &error); } } +/// A batch's hold of the device's texture slots' writes ([`hold`]), from before its first work's +/// take until its submission was made or the work given back (`texture/first_move.rs`'s +/// `Taken`). The writes asked meanwhile ([`place`], [`renew_over`], [`renew`]) are made as the +/// last hold ends, before the batch lets go of its place in the first work's order: so no +/// texture's elements reach the table or a heap set between the take and the `vkQueueSubmit` +/// (a texture registered after the take, whose move the batch did not take, would be in them in +/// `UNDEFINED`), and every later batch, which takes its place after, finds them written. +pub(super) struct HeldSlots { + device: Device, +} + +/// Hold `device`'s texture slots' writes for a batch taking its first work (the module docs): only +/// on a device whose heap sets take writes while a command buffer that binds them is pending, as +/// the writes made as it ends reach the sets the batch's commands bound, which it is by then +/// (`texture/first_move.rs` takes no hold elsewhere). +pub(super) fn hold(device: &Device) -> HeldSlots { + lock(&device.shared().heaps).holds += 1; + HeldSlots { + device: device.clone(), + } +} + +impl Drop for HeldSlots { + fn drop(&mut self) { + let device = &self.device; + let mut held = Vec::new(); + let mut notes = Notes::default(); + let failed = { + let mut heaps = lock(&device.shared().heaps); + heaps.holds -= 1; + let mut failed = Vec::new(); + while heaps.holds == 0 { + let Some(slots) = heaps.deferred.pop_front() else { + break; + }; + failed.extend(heaps.write_slots(device, slots, &mut held, &mut notes)); + } + failed + }; + drop(held); + notes.announce(device); + for (id, error) in failed { + failed_write(device, id, &error); + } + } +} + /// Announce that writing the heap elements of texture slot `id` failed with `error`: its entry /// is the neutral's. fn failed_write(device: &Device, id: u64, error: &Error) { diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 5906bda32..1fc79242d 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -248,7 +248,13 @@ impl TextureState { modifier_features: Mutex::new(HashMap::new()), heap_types: std::sync::OnceLock::new(), storage_forms: storage_form::StorageForms::default(), - first_moves: first_move::FirstMoves::default(), + // A batch holds the texture slots' writes in place of each registration waiting for + // its place where the heap sets take writes while pending, the + // `UPDATE_UNUSED_WHILE_PENDING` the device's profile derives from the same feature + // (`heap_sets.rs`). + first_moves: first_move::FirstMoves::new( + !description.has(VkFeature::DescriptorBindingUpdateUnusedWhilePending), + ), twin_decodes: twin_decode::TwinDecodes::default(), second_decodes: Mutex::new(Vec::new()), held: held_depth::HeldImages::default(), diff --git a/crates/metal2vulkan-runtime/src/texture/first_move.rs b/crates/metal2vulkan-runtime/src/texture/first_move.rs index 213aef8db..b099b49fd 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move.rs @@ -84,7 +84,15 @@ //! the M3 Max waited up to 13 ms, in 20 of 60 makings: MoltenVK encodes a command buffer's Metal //! commands inside `vkQueueSubmit`, on the calling thread (4.5 to 17 ms for those batches); with //! the hold, no making of 60 took past 0.16 ms. A device whose heap sets take no writes while a +//! command buffer that binds them is pending (no `descriptorBindingUpdateUnusedWhilePending`) +//! holds no slots, as a write made after a command buffer committed misses the version it binds +//! (`heap_sets.rs`): there each registration waits for its place ([`FirstMoves::ordered`]), so +//! for no replay and no GPU work (a batch replays its encoders' deferred command buffers, //! `recorder`, before its take), only for the recording of a submission's own barriers and its +//! `vkQueueSubmit`. An internal submission signals a timeline of its own, which a batch on +//! another `VkQueue` waits for while one that did first work may not have completed +//! ([`FirstMoves::internal_wait`]). Seen without it on RADV: a batch submitted with images in +//! `UNDEFINED` in its texture table, under the validation layer. //! - **Failure.** A submission that fails gives its work back, still to be done. //! - **Out of reach of a submission.** A texture's `VkImage` handed out (`Texture::vk_image`) //! rests in `GENERAL` as its contract says: handing it out does its work first, by an internal @@ -94,7 +102,7 @@ use super::super::creation; use super::super::device::lock; use super::super::error::{internal, vulkan, Error, MemoryKind}; use super::super::exit_guard::{self, Call}; -use super::super::host_memory::host_writable; +use super::super::heap_sets::HeldSlots; use super::super::image_barrier::{image_barrier, ImageDst}; use super::super::memory::{Memory, MemoryClass, Placement}; use super::super::release; @@ -107,9 +115,8 @@ use crate::device::functions::Vk; use ash::vk; use metal2vulkan::vk::Format; use std::any::Any; -use std::ops::Range; -use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; -use std::sync::{Arc, Mutex, MutexGuard, Weak}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard, TryLockError, Weak}; /// One `VkImage`'s first move: from `old` to `GENERAL`, then, where it reads zero, the copies of /// the device's zeros that write every texel, or a clear of them. @@ -769,9 +776,17 @@ struct Zeros { #[derive(Default)] pub(crate) struct FirstMoves { /// The submissions' order: held by each from its take until its submission was made - /// ([`Taken`]), and by each registration, so no submission is made between another's take - /// and its submission, and no resource registers meanwhile (the module docs). + /// ([`Taken`]), so no submission is made between another's take and its submission; and by + /// each registration where [`ordered`](Self::ordered), so no resource registers meanwhile + /// (the module docs). order: Mutex<()>, + /// Each registration waits for its place in the order: on a device whose heap sets take no + /// writes while a command buffer that binds them is pending, where a batch cannot hold the + /// texture slots' writes instead (`heap_sets::hold`). + ordered: bool, + /// The registrations that found a submission holding the order and waited for its place + /// (`WorkCounts::registrations_waited`). + waited: AtomicU64, waiting: Mutex>, /// The point of the last batch on each `VkQueue` that did some, by queue. done_at: Mutex>, @@ -823,9 +838,37 @@ fn past_bound(waiting: &[Waiting]) -> bool { } impl FirstMoves { + /// The first moves of a device whose registrations wait for their place in the order where + /// `ordered` ([`FirstMoves::ordered`]). + pub(crate) fn new(ordered: bool) -> FirstMoves { + FirstMoves { + ordered, + ..FirstMoves::default() + } + } + + /// The submissions' order, for a registration: held where registrations wait for their + /// place (the module docs), else not taken. One that finds a submission holding it is + /// counted as it waits. + fn registration_place(&self) -> Option> { + self.ordered.then(|| match self.order.try_lock() { + Ok(order) => order, + Err(TryLockError::Poisoned(poisoned)) => poisoned.into_inner(), + Err(TryLockError::WouldBlock) => { + self.waited.fetch_add(1, Ordering::Relaxed); + lock(&self.order) + } + }) + } + + /// The registrations that waited for a submission's place in the order so far. + pub(crate) fn registrations_waited(&self) -> u64 { + self.waited.load(Ordering::Relaxed) + } + /// `fresh`, just shared, has moves waiting. pub(crate) fn register(&self, fresh: Weak) { - let _order = lock(&self.order); + let _order = self.registration_place(); lock(&self.waiting).push(Waiting::Moves(fresh)); } @@ -840,7 +883,7 @@ impl FirstMoves { ) -> Result<(), Error> { let zeros = self.zeros(device, 0)?; let fill = FirstFill::new(buffer, range.start, range.end - range.start, zeros); - let _order = lock(&self.order); + let _order = self.registration_place(); lock(&self.waiting).push(Waiting::Fill(keeper, fill)); Ok(()) } @@ -859,7 +902,7 @@ impl FirstMoves { staging: Box, ) -> bool { let fill = FirstFill::bytes(buffer, start, source, length, staging); - let _order = lock(&self.order); + let _order = self.registration_place(); let mut waiting = lock(&self.waiting); waiting.push(Waiting::Fill(keeper, fill)); past_bound(&waiting) @@ -873,7 +916,7 @@ impl FirstMoves { keeper: Weak, copy: TexelCopy, ) -> bool { - let _order = lock(&self.order); + let _order = self.registration_place(); let mut waiting = lock(&self.waiting); waiting.push(Waiting::Texels(keeper, copy)); past_bound(&waiting) @@ -886,7 +929,29 @@ impl FirstMoves { /// The submission's place in the order is held until it was made or the work given back /// ([`Taken`]): every submission takes, whether or not anything waits. pub(crate) fn take(&self, named: impl Fn(ResourceKey) -> bool) -> Taken<'_> { + self.take_with(named, || None) + } + + /// As [`take`](Self::take), for a submission whose commands may bind the heap sets (a + /// batch's): where registrations do not wait for their place ([`FirstMoves::ordered`]), it + /// also holds the texture slots' writes (`heap_sets::hold`, which `hold` makes) from before it + /// takes until its submission was made or the work given back (the module docs). + pub(crate) fn take_holding( + &self, + named: impl Fn(ResourceKey) -> bool, + hold: impl FnOnce() -> HeldSlots, + ) -> Taken<'_> { + self.take_with(named, || (!self.ordered).then(hold)) + } + + /// As [`take`](Self::take), holding the slots `hold` gives once its place is taken. + fn take_with( + &self, + named: impl Fn(ResourceKey) -> bool, + hold: impl FnOnce() -> Option, + ) -> Taken<'_> { let order = lock(&self.order); + let slots = hold(); let mut held = Vec::new(); let mut left: Vec> = Vec::new(); { @@ -895,6 +960,7 @@ impl FirstMoves { return Taken { moves: self, held, + _slots: slots, _order: order, }; } @@ -946,6 +1012,7 @@ impl FirstMoves { Taken { moves: self, held, + _slots: slots, _order: order, } } @@ -1271,6 +1338,9 @@ impl Zeros { pub(crate) struct Taken<'a> { moves: &'a FirstMoves, held: Vec, + /// The texture slots' writes it holds ([`FirstMoves::take_holding`]), made as this drops, + /// before its place goes: the field before `_order`, which drops after it. + _slots: Option, /// The submission's place in the order ([`FirstMoves::take`]), let go as this drops. _order: MutexGuard<'a, ()>, } @@ -1640,6 +1710,67 @@ mod tests { drop(buffer); } + /// A resource registered on another thread while a submission holds its place: whether the + /// registration returned within `within`, and the resource once it did. + fn register_beside( + moves: &Arc, + within: std::time::Duration, + ) -> (bool, std::thread::JoinHandle>) { + let (sent, got) = std::sync::mpsc::channel(); + let registering = Arc::clone(moves); + let thread = crate::exit_guard::spawn(std::thread::Builder::new(), move || { + let image = registered(®istering, 7, None); + // Received, or not where the wait for it ended first. + sent.send(()).ok(); + image + }) + .unwrap(); + (got.recv_timeout(within).is_ok(), thread) + } + + /// Where a batch holds the texture slots' writes ([`FirstMoves::ordered`] false), a resource + /// registers while a submission holds its place, without waiting for it, and the next + /// submission takes its move. + #[test] + fn a_registration_waits_for_no_submission_where_batches_hold_the_slots() { + let moves = Arc::new(FirstMoves::new(false)); + let taken = moves.take(|_| false); + let (returned, thread) = register_beside(&moves, std::time::Duration::from_secs(30)); + assert!( + returned, + "the registration waited for the submission's place" + ); + assert!( + taken.submitted(None).is_empty(), + "registered after the take" + ); + let image = thread.join().unwrap(); + assert_eq!(moves.registrations_waited(), 0, "counted as waiting"); + let next = moves.take(|_| false); + assert_eq!(next.held.len(), 1, "the next submission takes the move"); + assert!(lock(&image.moves).is_empty()); + } + + /// Where registrations wait for their place ([`FirstMoves::ordered`]), a resource registers + /// only once the submission holding its place let go of it, counted as it waits, and the next + /// submission takes its move. + #[test] + fn a_registration_waits_for_the_submission_where_registrations_are_ordered() { + let moves = Arc::new(FirstMoves::new(true)); + let taken = moves.take(|_| false); + let (returned, thread) = register_beside(&moves, std::time::Duration::from_millis(200)); + assert!( + !returned, + "the registration came between a take and its submission" + ); + assert!(taken.submitted(None).is_empty()); + let image = thread.join().unwrap(); + assert_eq!(moves.registrations_waited(), 1, "the wait counted"); + let next = moves.take(|_| false); + assert_eq!(next.held.len(), 1, "the next submission takes the move"); + assert!(lock(&image.moves).is_empty()); + } + #[test] fn a_submission_holds_a_filled_buffer_s_memory_not_the_buffer() { let moves = FirstMoves::default(); diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 745492d0f..4263fca13 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -81,6 +81,7 @@ pub(crate) struct Counters { stale_detached_reaches: AtomicU64, detached_storage_reaches: AtomicU64, heap_slots_rewritten: AtomicU64, + heap_slot_writes_deferred: AtomicU64, heap_textures_tiled: AtomicU64, heap_texture_lossless_layouts: AtomicU64, heap_texture_block_compressed_layouts: AtomicU64, @@ -1679,6 +1680,11 @@ impl Counters { } } + /// A write of texture slots waited for a batch's hold of them to end (`heap_sets::hold`). + pub(crate) fn heap_slot_writes_deferred(&self) { + (self.heap_slot_writes_deferred).fetch_add(1, Ordering::Relaxed); + } + /// A texture in a heap over host pages was made tiled as Metal lays it out /// (`texture/heap_tiled.rs`). pub(crate) fn heap_texture_tiled(&self) { @@ -1982,6 +1988,13 @@ pub struct WorkCounts { /// detach, one for each live texture whose images or texel views lie in those bytes (in a /// no-copy heap or over one of its buffers, for the heap's), and none for any other texture. pub heap_slots_rewritten: u64, + /// Writes of texture slots of the device's heap (a new texture's, or those a rebind, a detach + /// or a change of storage form writes again) that waited for a batch: asked between its + /// first work's take and its `vkQueueSubmit`, they were made once its submission was made, + /// before the next batch took its first work. So a texture's making waits for no batch's + /// submission. A device whose heap sets take no writes while a command buffer is pending + /// defers none: there a texture's registration waits for the batch instead. + pub heap_slot_writes_deferred: u64, /// Uses of a buffer over host pages that looked up by address the ranges of host bytes their /// bytes meet (`host_aliases.rs`): a use of a range met by no more ranges than the classes of /// length that lookup visits reads those its range keeps instead. @@ -2147,6 +2160,14 @@ pub struct WorkCounts { /// Of those, the groups that went at once because a thread began to wait for one of their /// command buffers' completion (`CommandBuffer::wait_until_completed`). pub groups_sent_for_waits: u64, + /// Registrations of a new resource's first work (as a texture or buffer is made) that found + /// a submission holding its place in the submissions' order and waited until that submission + /// was made: only on a device whose heap sets take no writes while a command buffer that binds + /// them is pending (no `descriptorBindingUpdateUnusedWhilePending`), where a submission holds + /// the order from its take of the first work, after replaying its encoders' deferred command + /// buffers, to its `vkQueueSubmit` (`texture/first_move.rs`). Elsewhere a registration takes + /// no place, and this stays 0. + pub registrations_waited: u64, /// Times the scheduler's thread found no work and slept (`scheduler/mod.rs`), each until it /// was woken or [`scheduler_sleep_slices`](Self::scheduler_sleep_slices) says it timed out. pub scheduler_sleeps: u64, @@ -2979,6 +3000,7 @@ impl Device { stale_detached_reaches: counters.stale_detached_reaches.load(Ordering::Relaxed), detached_storage_reaches: counters.detached_storage_reaches.load(Ordering::Relaxed), heap_slots_rewritten: counters.heap_slots_rewritten.load(Ordering::Relaxed), + heap_slot_writes_deferred: counters.heap_slot_writes_deferred.load(Ordering::Relaxed), host_range_lookups: self.shared().aliases.range_lookups(), heap_textures_tiled: counters.heap_textures_tiled.load(Ordering::Relaxed), heap_texture_lossless_layouts: counters @@ -3037,6 +3059,7 @@ impl Device { batches_with_four_or_more_pending: pending(3), groups_kept_pending: counters.groups_kept_pending.load(Ordering::Relaxed), groups_sent_for_waits: counters.groups_sent_for_waits.load(Ordering::Relaxed), + registrations_waited: self.shared().textures.first_moves.registrations_waited(), scheduler_sleeps: sleeps, scheduler_wakes_commit: by_commit, scheduler_wakes_completion: by_completion, diff --git a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs index 434f09e35..fd8cf5239 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs @@ -16,10 +16,21 @@ //! bytes it lies over where it aliases, what a blit wrote. //! - **Making waits for no submission's replay.** A command buffer whose deferred command buffers //! take long to replay (`recorder`) and to submit is committed, and a `Private` texture made +//! while its submission replays and submits them waits for no submission's place +//! (`WorkCounts::registrations_waited` stays 0): a submission replays them before it takes the +//! new resources' first work, and from its take until its `vkQueueSubmit` returned (MoltenVK +//! encodes the Metal commands inside it) it holds the texture slots' writes, not the texture's +//! registration (`WorkCounts::heap_slot_writes_deferred`), or, on a device whose heap sets take +//! no writes while pending, the registrations, which then wait only for that span. The making's +//! time is printed, not bounded: it holds the host's and the driver's waits. On lavapipe under +//! the validation layer, beside 128 busy threads on 32 CPUs, its `vkCreateImage` slept up to +//! 6 ms on the layer's lock, which the replay's own Vulkan calls on the recorder's thread held +//! while the host ran another thread, and once waited 8 ms for a CPU. It makes a //! `Private` texture: its move waits for a submission, so its making registers it, where a new //! `Shared` texture's move is made on the host on a device with host image copies //! (`texture/host_copy.rs`), registering nothing, whatever the order. One is made before, //! untimed: a device's first texture making took 4 to 9 ms on RADV +//! and the Iris Xe, 32 ms on a loaded Iris Xe, waiting for nothing. //! - **The zeros come before every use, on every queue** (the coordinator's conditions). A new //! `Private` buffer whose memory held other bytes is read through its address unnamed, and //! through its heap made resident, by a command buffer on another queue, after a command @@ -872,6 +883,89 @@ fn new_resources_wait_for_no_gpu_work() { }); } +/// The fills the long replay's command buffer encodes at first +/// ([`a_new_texture_waits_for_no_submission_s_replay`]), doubled until its submission comes at +/// least [`LONG_REPLAY`] after its commit, up to [`MOST_REPLAY_FILLS`]. +const REPLAY_FILLS: usize = 1 << 12; +const MOST_REPLAY_FILLS: usize = 1 << 20; + +/// The least time from the long replay's commit until its command buffer is scheduled. +const LONG_REPLAY: Duration = Duration::from_millis(40); + +/// How long after that commit the texture is made: past the scheduler's first look at the +/// command buffer, well inside its replay. +const AFTER_COMMIT: Duration = Duration::from_millis(2); + +/// Making a texture waits for no submission's replay of deferred command buffers, nor for its +/// `vkQueueSubmit` (Metal's makes wait for no GPU work, nor for a submission). One blit encoder of +/// fills of distinct words, whose replay into a `VkCommandBuffer` (`recorder`) and submission take +/// at least [`LONG_REPLAY`] (its fills doubled until they do), is committed, and a `Private` +/// texture, whose making registers its move and writes its slot (the module docs), is made +/// [`AFTER_COMMIT`] later, after one made untimed before: its registration waits for no +/// submission's place (`WorkCounts::registrations_waited`), and its time is printed. A device that +/// records as it encodes (no recorder) replays nothing, printed. +#[test] +fn a_new_texture_waits_for_no_submission_s_replay() { + on_device(|device| { + let queue = device.new_command_queue().unwrap(); + let name = device.name(); + let first = device.new_texture(&descriptor(tracked_private())).unwrap(); + let mut fills = REPLAY_FILLS; + loop { + let target = (device.new_buffer(4 * fills as u64, ResourceOptions::private())).unwrap(); + let deferred = device.work_counts().command_buffers_deferred; + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + for at in 0..fills as u64 { + blit.fill_buffer(&target, 4 * at..4 * at + 4, at as u8) + .unwrap(); + } + blit.end_encoding().unwrap(); + if device.work_counts().command_buffers_deferred == deferred { + eprintln!("FIRST-USE {name}: records as it encodes, so no submission replays"); + return; + } + let committed = Instant::now(); + command_buffer.commit().unwrap(); + std::thread::sleep(AFTER_COMMIT); + let waited = device.work_counts().registrations_waited; + let making = Instant::now(); + let texture = device.new_texture(&descriptor(tracked_private())).unwrap(); + let made = making.elapsed(); + let waited = device.work_counts().registrations_waited - waited; + scheduled(&command_buffer); + let submitted = committed.elapsed(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + drop(texture); + eprintln!( + "FIRST-USE {name}: a Private texture made {:.1} ms after the commit of {fills} \ + fills took {:.3} ms, its registration waiting {waited} times for a \ + submission's place; the command buffer was scheduled {:.1} ms after its commit", + AFTER_COMMIT.as_secs_f64() * 1e3, + made.as_secs_f64() * 1e3, + submitted.as_secs_f64() * 1e3, + ); + if submitted < LONG_REPLAY && fills < MOST_REPLAY_FILLS { + fills *= 2; + continue; + } + assert!( + submitted >= LONG_REPLAY, + "{MOST_REPLAY_FILLS} fills were scheduled {submitted:?} after their commit, \ + short of {LONG_REPLAY:?}" + ); + assert_eq!( + waited, 0, + "a texture made {AFTER_COMMIT:?} after the commit, {submitted:?} before its \ + command buffer was scheduled, waited for a submission's place" + ); + break; + } + drop(first); + }); +} + /// A `Private` buffer of `len` bytes made where a buffer that held `node(A)` was just released /// (most likely its memory): a fill that did not run would leave those bytes. Whether the /// memory was the released one's, printed.