diff --git a/crates/metal2vulkan-runtime/src/blit_indirect.rs b/crates/metal2vulkan-runtime/src/blit_indirect.rs index 9d81fb7a3..0298d795c 100644 --- a/crates/metal2vulkan-runtime/src/blit_indirect.rs +++ b/crates/metal2vulkan-runtime/src/blit_indirect.rs @@ -26,7 +26,9 @@ //! as they stand once the work before them completed. An optimize records nothing. Counted as //! encoded, in the records' bytes of the range (`COMMAND_BYTES` a command, whatever the //! descriptor, a reset's flagged or not): `WorkCounts::indirect_record_bytes_gpu_copied` and -//! `indirect_record_bytes_gpu_reset`. +//! `indirect_record_bytes_gpu_reset`; and each reset dispatch's GPU time, between timestamps +//! written around it where the device writes them, as a rate-mapped pass's pieces are timed +//! (`rate_mapped_pass::PieceTimes`): `indirect_record_reset_gpu_nanos`. //! - **What a reset costs** (an RTX 2080 on a PCIe 3.0 x4 link, NVIDIA 620.70.06, release, the //! median GPU time of 15 command buffers of one reset each, two runs alike). A reset of 45,000 //! render commands (101 MB of records in host-cached system memory) took 0.26 ms with no command @@ -64,6 +66,7 @@ use super::blit::{reads, writes, writes_by, BlitCommandEncoder}; use super::error::{internal, Error}; use super::indirect_command_buffer::{IndirectCommandBuffer, Overflow}; use super::owned_kernel::{OwnedBinds, OwnedModule, OwnedSet}; +use super::rate_mapped_pass::PieceTimes; use super::replay::BlitCall; use super::tracker::Access; use super::write_routes::GpuWriter; @@ -259,28 +262,41 @@ impl BlitCommandEncoder { writes_by(storage, records, access), writes_by(storage, flags, access), ]; - self.command_in(compute, &uses, |device, command_buffer| { - // SAFETY: the encoder's command buffer is recording; the kernel is the device's, - // and the storage is live and retained until the command buffer completes (the - // caller); the bindings hold the run's records and flags, within the device's - // range and alignment, and the dispatch is one workgroup a command of the run. + // The dispatch's GPU time, where the device writes timestamps + // (`WorkCounts::indirect_record_reset_gpu_nanos`). + let times = PieceTimes::icb_reset(&device); + self.command_in(compute, &uses, |raw, command_buffer| { + // SAFETY: the encoder's command buffer is recording, outside a render pass; the + // kernel is the device's, and the storage is live and retained until the command + // buffer completes (the caller); the bindings hold the run's records and flags, + // within the device's range and alignment, and the dispatch is one workgroup a + // command of the run; the times are retained with the command buffer below. unsafe { - device.cmd_bind_pipeline( + if let Some(times) = × { + times.begin(raw, command_buffer, 0); + } + raw.cmd_bind_pipeline( command_buffer, vk::PipelineBindPoint::COMPUTE, kernel.pipeline, ); - binds.bind(device, command_buffer, &kernel, 0); - device.cmd_push_constants( + binds.bind(raw, command_buffer, &kernel, 0); + raw.cmd_push_constants( command_buffer, kernel.layout, vk::ShaderStageFlags::COMPUTE, 0, &firsts, ); - device.cmd_dispatch(command_buffer, x, y, z); + raw.cmd_dispatch(command_buffer, x, y, z); + if let Some(times) = × { + times.end(raw, command_buffer, 0); + } } })?; + if let Some(times) = times { + self.core().retain(times); + } if let OwnedBinds::Sets(sets) = binds { self.core().retain(sets); } diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 2e741d3a3..e0af3cb5c 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -3011,7 +3011,8 @@ impl Device { /// indirect command buffer's records or the slots past them: in fresh pages of its own at any /// length, whatever a held import costs, where the device takes them, so that a recovery's /// carry keeps its pages and its bytes (`FreshPages::Always`); else where - /// [`zeroed_buffer`](Device::zeroed_buffer) lays such a buffer. Refused as that is. + /// [`zeroed_buffer`](Device::zeroed_buffer) lays such a buffer ([`Buffer::in_own_pages`] + /// tells which). Refused as that is. pub(super) fn records_buffer( &self, call: &'static str, @@ -4104,6 +4105,15 @@ impl Buffer { } } + /// Whether the buffer lies in pages the runtime mapped and imported, fresh pages of its own or + /// a block of them ([`in_fresh_pages`](Buffer::in_fresh_pages), + /// [`in_page_block`](Buffer::in_page_block)): a recovery's carry of a buffer of the runtime's + /// own imports the same pages again, its bytes and `contents` pointer as they are + /// ([`carry_runtime`](Buffer::carry_runtime)). + pub(super) fn in_own_pages(&self) -> bool { + self.in_fresh_pages() || self.in_page_block() + } + /// Whether the buffer lies in a block of pages the runtime mapped and imported, among other /// buffers (`memory.rs`'s `Holds::PageBuffers`): an image over its bytes is made for host /// allocations, as over fresh pages, under their class's verdicts (`texture/route.rs`). diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs index 4562ca3ff..cd8c23d82 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs @@ -121,9 +121,13 @@ use std::sync::{Arc, Mutex, OnceLock, Weak}; pub(crate) mod carry; mod set_each; mod set_states; +mod writers; pub use set_each::{IndirectComputeSet, IndirectRenderSet}; use set_states::{Keyed, SetKeys, SetStates, StateKey}; +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) use writers::on_carry_waits; +use writers::Writers; /// The threadgroup lengths a fresh descriptor binds, as Metal's answers. const DEFAULT_THREADGROUP_LENGTHS: u32 = 31; @@ -652,6 +656,9 @@ impl Device { ResourceOptions::new(modes.storage, modes.cache, storage.hazard_tracking_mode()); let states = CommandStates::new(size); let set_keys = states.states.keys(); + // A recovery's carry keeps records in the runtime's own pages, and moves those in pooled + // memory, whose setters' writes without the lock it waits out (`writers.rs`). + let writers = Writers::new(!storage.in_own_pages()); let icb = IndirectCommandBuffer(Arc::new(IcbShared { storage, id, @@ -664,6 +671,7 @@ impl Device { pipelines: Mutex::new(states), set_keys, unlocked: UnlockedWrites::new(size), + writers, gpu_written: AtomicBool::new(false), gpu_writer: OnceLock::new(), unforeseen: Mutex::new(Vec::new()), @@ -1143,6 +1151,9 @@ struct IcbShared { /// The chunks a setter wrote without `pipelines` ([`Batch`]), for the kept recordings' next /// look to forget ([`UnlockedWrites`]). unlocked: UnlockedWrites, + /// The setters' writes without `pipelines` under way, which a recovery's carry of a buffer + /// of pooled memory waits out (`writers.rs`). + writers: Writers, /// A route that may write the buffer's records met it (`write_routes.rs`): the GPU may write /// them from then on (`written_by_gpu`). Set, and read where it decides, under /// `unforeseen`'s lock. @@ -1222,6 +1233,7 @@ const _: fn(&IcbShared) = |icb| { pipelines, set_keys, unlocked, + writers, gpu_written, gpu_writer, unforeseen, @@ -1248,6 +1260,7 @@ const _: fn(&IcbShared) = |icb| { shared(pipelines); shared(set_keys); shared(unlocked); + shared(writers); shared(gpu_written); shared(gpu_writer); shared(unforeseen); @@ -1780,6 +1793,13 @@ impl IndirectCommandBuffer { self.bytes().addr() } + /// Whether the records lie in the runtime's own pages, which a recovery's carry keeps, rather + /// than pooled memory, for a device test or benchmark of which path ran. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(super) fn records_in_own_pages(&self) -> bool { + self.0.storage.in_own_pages() + } + /// [`cpu_writes`](Self::cpu_writes) apart: those under `pipelines`, and the setters' without /// it ([`Batch`]), for a device test of which way a write went. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -2170,6 +2190,7 @@ impl IndirectCommandBuffer { icb: self, index, storage: self.bytes(), + begun: None, unlocked: 0, } } @@ -2323,17 +2344,22 @@ impl IndirectCommandBuffer { } /// Read `bytes` from `at` of the overflow, which holds them (as - /// [`write_overflow_at`](Self::write_overflow_at)'s); false where it is not mapped. + /// [`write_overflow_at`](Self::write_overflow_at)'s); false where it is not mapped. A host + /// read outside a command buffer's work, as a record's is ([`read_record`](Self::read_record)), + /// it holds the overflow's parts it reads: a recovery's carry that moves them to new memory + /// meanwhile lets go of the lost generation's once the read ended. fn read_overflow_at(&self, at: u64, bytes: &mut [u8]) -> bool { - let Some(contents) = self - .0 - .overflow - .as_ref() - .and_then(|overflow| overflow.storage.mapped_contents()) - else { + let Some(overflow) = self.0.overflow.as_ref() else { return false; }; - // SAFETY: as `write_overflow_at`'s; a write meanwhile is the program's race. + let _parts = overflow.storage.held_parts(); + let Some(contents) = overflow.storage.mapped_contents() else { + return false; + }; + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + set_hook(HoldAt::Read); + // SAFETY: as `write_overflow_at`'s, the parts read held; a write meanwhile is the + // program's race. unsafe { std::ptr::copy_nonoverlapping( contents.as_ptr().add(at as usize), @@ -3927,49 +3953,120 @@ enum Then { } /// One command's setters' writes, made in turn as each setter's checks pass: a setter's alone, or -/// the setters a call of `set_each` names (`set_each.rs`), each setter writing into the batch rather than handing its write back (a plan -/// value handed back cost a buffer setter about 9 ns, `tests::icb_encode_bench`). A field that sets no state and adds nothing to -/// what the records may hold ([`adds_nothing`](IndirectCommandBuffer::adds_nothing)) is written -/// without `pipelines`, the count of the CPU's writes and the kept recordings of the command's -/// chunk alone following it, as they follow a write under the lock -/// ([`wrote`](IndirectCommandBuffer::wrote)): once the batch ends, the chunk noted for the kept -/// recordings' next look to forget ([`UnlockedWrites`], `KeptChunks::settle`), then the writes -/// counted, by one atomic add; it writes the storage's bytes as the batch found them. A buffer the -/// GPU starts writing meanwhile is the race a write under the lock has with it too (`gpu_written` -/// is set under `unforeseen`'s lock). The lock's two locked instructions were most of a buffer -/// setter's cost (`tests::icb_encode_bench`). Another write is made under `pipelines` +/// the setters a call of `set_each` names (`set_each.rs`), each setter writing into the batch +/// rather than handing its write back (a plan value handed back cost a buffer setter about 9 ns, +/// `tests::icb_encode_bench`). A field that sets no state and adds nothing to what the records +/// may hold ([`adds_nothing`](IndirectCommandBuffer::adds_nothing)), and a pipeline state the +/// command names already ([`SetKeys`]), are written without `pipelines`, the count of the CPU's +/// writes and the kept recordings of the command's chunk alone following them, as they follow a +/// write under the lock ([`wrote`](IndirectCommandBuffer::wrote)): once the batch ends, the chunk +/// noted for the kept recordings' next look to forget ([`UnlockedWrites`], +/// `KeptChunks::settle`), then the writes counted, by one atomic add. In the runtime's own pages +/// such a write lands in the records a device recovery's carry keeps, whenever it lands; in +/// pooled memory each, from its look at what the command holds to its store, is one the carry +/// waits out, and none begins during the carry (`writers.rs`): it writes the records the carry +/// leaves or those it carries, never the lost generation's memory. A buffer the GPU starts +/// writing meanwhile is the race a write under the lock has with it too (`gpu_written` is set +/// under `unforeseen`'s lock). The lock's two locked instructions were most of a buffer setter's +/// cost (`tests::icb_encode_bench`). Another write is made under `pipelines` /// ([`edit_locked`](IndirectCommandBuffer::edit_locked)), in the bytes as they are under it. struct Batch<'i> { icb: &'i IndirectCommandBuffer, index: u32, - /// The storage's bytes ([`bytes`](IndirectCommandBuffer::bytes)). + /// The storage's bytes ([`bytes`](IndirectCommandBuffer::bytes)), read at the batch's + /// making: on a buffer of pooled memory read again by a write without `pipelines`, at its + /// first and where a carry began since (`begun`). storage: *mut u8, + /// On a buffer of pooled memory, the carries of the buffer begun before a write without + /// `pipelines` read [`storage`](Self::storage) (`Writing::carries_begun`, `writers.rs`); none + /// until one did. + begun: Option, /// The writes made without `pipelines`, not yet counted. unlocked: u64, } impl Batch<'_> { /// Write `field`, which names no pipeline state, then note `then`: without `pipelines` where - /// it adds nothing to what the records may hold, else under it. + /// it adds nothing to what the records may hold, else under it. Records in the runtime's own + /// pages are the bytes the batch read at its making, whatever a recovery's carry does + /// meanwhile (`writers.rs`); in pooled memory the write without the lock is a + /// [`counted_write`](Self::counted_write). fn field(&mut self, field: RecordField, then: Then) -> Result<(), Error> { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - set_hook(); + set_hook(HoldAt::Set); let icb = self.icb; - match icb.adds_nothing(field) { - true => { - icb.write_field(self.storage, self.index, field)?; - self.unlocked += 1; + if icb.0.writers.counted() { + if !self.counted_write(field, None)? { + icb.edit_locked(self.index, field, None)?; } - false => icb.edit_locked(self.index, field, None)?, + } else if icb.adds_nothing(field) { + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + set_hook(HoldAt::Write); + icb.write_field(self.storage, self.index, field)?; + self.unlocked += 1; + } else { + icb.edit_locked(self.index, field, None)?; } icb.then(then); Ok(()) } + /// Write the ID of the pipeline state of key `key`, `id`, again, as [`field`](Self::field) + /// does, where the command names that state already as the CPU set it since the buffer's last + /// carry ([`SetKeys`]): whether it did. Else the caller sets the state, with every check, + /// under the lock. In pooled memory the look at the command's key too is the + /// [`counted_write`](Self::counted_write)'s, which goes without the lock or not at all. + fn named(&mut self, key: StateKey, id: NonZeroU64) -> Result { + let field = RecordField::Pipeline(id); + if self.icb.0.writers.counted() { + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + set_hook(HoldAt::Set); + return self.counted_write(field, Some(key)); + } + if !self.icb.0.set_keys.names(self.index, key) { + return Ok(false); + } + self.field(field, Then::Nothing)?; + Ok(true) + } + + /// Write `field` without `pipelines` on a buffer of pooled memory, where no carry of it is + /// under way, the command names the state of key `named` where given, and the field adds + /// nothing to what the records may hold: whether it did. The look and the write are one the + /// carry waits out (`writers.rs`), in the storage's bytes read again at the batch's first + /// such write and where a carry began since. Out of the way of the writes to records in the + /// runtime's own pages, where a device imports host pointers. + #[cold] + fn counted_write( + &mut self, + field: RecordField, + named: Option, + ) -> Result { + let icb = self.icb; + let Some(writing) = icb.0.writers.enter() else { + return Ok(false); + }; + if named.is_some_and(|key| !icb.0.set_keys.names(self.index, key)) + || !icb.adds_nothing(field) + { + return Ok(false); + } + let begun = writing.carries_begun(); + if self.begun != Some(begun) { + self.storage = icb.bytes(); + self.begun = Some(begun); + } + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + set_hook(HoldAt::Write); + icb.write_field(self.storage, self.index, field)?; + self.unlocked += 1; + Ok(true) + } + /// Set `set` on the command, as its pipeline of ID `id`, under `pipelines`. fn state(&mut self, id: NonZeroU64, set: StateSet<'_>) -> Result<(), Error> { #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] - set_hook(); + set_hook(HoldAt::Set); self.icb .edit_locked(self.index, RecordField::Pipeline(id), Some(set)) } @@ -4050,33 +4147,54 @@ impl Drop for Batch<'_> { } } +/// Where a test's hook holds a setter's write ([`hold_next_set`]). +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum HoldAt { + /// Once its batch is made, before anything of the write. + Set, + /// In a write without the lock, once it read the records' bytes and before its store + /// ([`Batch::field`], [`Batch::counted_write`]). + Write, + /// In a getter's read of the slots past the records, once it read their bytes' address and + /// before it copies them ([`IndirectCommandBuffer::read_overflow_at`]). + Read, +} + /// Whether a test armed a hook ([`hold_next_set`]): one load where none did. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] static SET_HOOKS: AtomicBool = AtomicBool::new(false); #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] thread_local! { - /// The hook this thread's next setter write runs first ([`hold_next_set`]). - static SET_HOOK: std::cell::RefCell>> = + /// The hook this thread's next setter write runs where it reaches its place + /// ([`hold_next_set`]). + static SET_HOOK: std::cell::RefCell)>> = const { std::cell::RefCell::new(None) }; } -/// Have this thread's next setter write of a field run `hook` first, once its batch is made and -/// before anything of the write: a device test holds a set there while a recovery carries the -/// buffer (`tests::icb_carry_race`). +/// Have this thread's next setter write, or getter read, run `hook` at `at`: a device test holds +/// it there while a recovery carries the buffer (`tests::icb_carry_race`). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -pub(crate) fn hold_next_set(hook: impl FnOnce() + 'static) { +pub(crate) fn hold_next_set(at: HoldAt, hook: impl FnOnce() + 'static) { SET_HOOKS.store(true, Ordering::Relaxed); - SET_HOOK.with(|armed| *armed.borrow_mut() = Some(Box::new(hook))); + SET_HOOK.with(|armed| *armed.borrow_mut() = Some((at, Box::new(hook)))); } -/// Run this thread's hook, where a test armed one ([`hold_next_set`]). +/// Run this thread's hook where a test armed one for `at` ([`hold_next_set`]). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] -fn set_hook() { +fn set_hook(at: HoldAt) { if !SET_HOOKS.load(Ordering::Relaxed) { return; } - if let Some(hook) = SET_HOOK.with(|armed| armed.borrow_mut().take()) { + let hook = SET_HOOK.with(|armed| { + let mut armed = armed.borrow_mut(); + match armed.as_ref() { + Some((place, _)) if *place == at => armed.take().map(|(_, hook)| hook), + _ => None, + } + }); + if let Some(hook) = hook { hook(); } } @@ -4580,8 +4698,8 @@ impl ComputeAt<'_> { id: id.get(), serial, }; - if self.icb.0.set_keys.names(self.index, key) { - return batch.field(RecordField::Pipeline(id), Then::Nothing); + if batch.named(key, id)? { + return Ok(()); } } // The state's program, held while the command takes it (`pipeline/carry.rs`): one hold @@ -5687,8 +5805,8 @@ impl RenderAt<'_> { id: id.get(), serial, }; - if self.icb.0.set_keys.names(self.index, key) { - return batch.field(RecordField::Pipeline(id), Then::Nothing); + if batch.named(key, id)? { + return Ok(()); } } // The state's program, held while the command takes it (`pipeline/carry.rs`): one hold diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs index c51f37864..3492c582c 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs @@ -10,11 +10,13 @@ //! host-visible memory, on a device that imports none or where the import failed, new memory //! there, the records lost with the `VkDevice`, whose memory Vulkan makes undefined (vkspec //! 5.2.3, "Lost Device"), written again as a new buffer's: its header, every command reset, its -//! slots past them zero. The CPU's writes of the records under `pipelines` wait for the carry; -//! a setter's write without it (`Batch`: one that adds nothing to what the records may hold) -//! does not: in the runtime's own pages it writes the pages the carry keeps, and in pooled -//! memory one meanwhile races the carry. A host read outside a command buffer's work holds the -//! storage's parts it reads. +//! slots past them zero. The CPU's writes of the records under `pipelines` wait for the carry +//! and read the records' bytes under it. A setter's write without it (`Batch`: one that adds +//! nothing to what the records may hold) in the runtime's own pages writes the pages the carry +//! keeps, whenever it lands; in pooled memory it is waited out before the carry begins, and one +//! begun meanwhile goes under the lock (`writers.rs`): each writes the records the carry leaves +//! or those it carries, never the lost generation's memory. A host read outside a command +//! buffer's work holds the storage's parts it reads. //! - **What stays.** The object, its records ID, address, `gpuResourceID`, `uniqueIdentifier` and //! label, which are the device's line's rather than a generation's (`device/line.rs`'s //! `Carried`); the threadgroup lengths past the last command's, which the host keeps; what its @@ -68,6 +70,9 @@ impl IndirectCommandBuffer { if shared.storage.generation().same(to) { return Ok(Contents::Kept); } + // In pooled memory, the setters' writes without the lock under way end first, and none + // begins until the records and the keys are the next generation's (`writers.rs`). + let stopped = shared.writers.stop(); let mut commands = lock(&shared.pipelines); // Each command's next set of its state checked again against the generation it meets, // under the lock, whether the carry succeeds or not. @@ -89,6 +94,7 @@ impl IndirectCommandBuffer { commands.kept.clear(); commands.step_kept.clear(); drop(commands); + drop(stopped); lock(&shared.kept).carry(to); if shared.keeping.load(Ordering::Acquire) { to.shared().keepers.add(&shared.kept); diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer/set_each.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer/set_each.rs index cfb2921a9..553e0162f 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer/set_each.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer/set_each.rs @@ -374,6 +374,7 @@ impl RenderAt<'_> { } /// The setter `set` names: in `batch` where the setter writes a field, else the setter. + #[inline(always)] fn set_one(&self, batch: &mut Batch<'_>, set: IndirectRenderSet<'_>) -> Result<(), Error> { use IndirectRenderSet as S; match set { @@ -540,6 +541,7 @@ impl ComputeAt<'_> { } /// The setter `set` names: in `batch` where the setter writes a field, else the setter. + #[inline(always)] fn set_one(&self, batch: &mut Batch<'_>, set: IndirectComputeSet<'_>) -> Result<(), Error> { use IndirectComputeSet as S; match set { diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer/writers.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer/writers.rs new file mode 100644 index 000000000..807ea8d8e --- /dev/null +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer/writers.rs @@ -0,0 +1,140 @@ +//! The setters' writes of an indirect command buffer's records made without its lock (`Batch`), +//! and a device recovery's carry of the buffer, which waits out those of a buffer of pooled +//! memory ([`Writers`]). +//! +//! A write without the lock reads the records' bytes and writes them. A recovery's carry of a +//! buffer whose records lie in the runtime's own pages, as they do on a device that imports host +//! pointers (`fresh_pages.rs`), imports the same pages again: the bytes and their address stay, +//! so such a write lands in the records the carry keeps, before it or after it, and nothing here +//! looks at it. A carry of a buffer of pooled memory, on a device that imports none or where the +//! import failed, moves its records to new memory and resets every command there, and the lost +//! generation's memory goes at that generation's rest, which can come at once (`carry.rs`). So a +//! write to such a buffer that read the bytes, or looked at what the command holds, before the +//! move and wrote after it would write the lost generation's memory, memory let go of, or a +//! command the carry reset. Instead each such write, from its look at what the command holds to +//! its last store, counts itself under way in the buffer by an atomic add; the carry marks +//! itself begun, then waits until none is under way. A write that finds a carry begun and not +//! ended is not made without the lock, and goes under it instead, after the carry. Each write +//! lands before the carry or after it. + +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + +/// A carry begun, in [`Writers::carries`]: above the carries under way. +const BEGUN: u64 = 1 << 32; + +/// One buffer's writes without its lock and its carries (the module docs). +pub(super) struct Writers { + /// Whether the buffer's records lie in pooled memory, which a carry moves: its writes + /// without the lock count themselves. Fixed at the buffer's making. + counted: bool, + /// The carries of the buffer begun so far, above those under way (in the low 32 bits), while + /// one of which no write without the lock begins. A write reads the records' bytes again + /// only where a carry began since it read them last ([`Writing::carries_begun`]). + carries: AtomicU64, + /// The writes without the lock under way. + under_way: AtomicU32, +} + +impl Writers { + /// The writers of a buffer whose records lie in pooled memory (`pooled`), or in the + /// runtime's own pages. + pub(super) fn new(pooled: bool) -> Writers { + Writers { + counted: pooled, + carries: AtomicU64::new(0), + under_way: AtomicU32::new(0), + } + } + + /// Whether the buffer's records lie in pooled memory, whose writes without the lock count + /// themselves ([`enter`](Self::enter)); else they need nothing of this. + #[inline] + pub(super) fn counted(&self) -> bool { + self.counted + } + + /// A write of a buffer of pooled memory without its lock, from now until the guard goes: + /// none where a carry of it is under way, the write then to go under the lock. + pub(super) fn enter(&self) -> Option> { + self.under_way.fetch_add(1, Ordering::SeqCst); + let carries = self.carries.load(Ordering::SeqCst); + if !carries.is_multiple_of(BEGUN) { + self.under_way.fetch_sub(1, Ordering::Release); + return None; + } + Some(Writing { + under_way: &self.under_way, + begun: carries / BEGUN, + }) + } + + /// Stop the writes without the lock of a buffer of pooled memory for a carry, until the guard + /// goes: none begins, and those under way have ended. None for a buffer in the runtime's own + /// pages, whose writes need no stop. + pub(super) fn stop(&self) -> Option> { + if !self.counted { + return None; + } + self.carries.fetch_add(BEGUN + 1, Ordering::SeqCst); + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + if self.under_way.load(Ordering::SeqCst) != 0 { + waits_hook(); + } + while self.under_way.load(Ordering::SeqCst) != 0 { + std::thread::yield_now(); + } + Some(Stopped(self)) + } +} + +/// A write without the lock under way ([`Writers::enter`]). +pub(super) struct Writing<'a> { + /// The count it is under way in. + under_way: &'a AtomicU32, + /// The carries of the buffer begun before it, all ended. + begun: u64, +} + +impl Writing<'_> { + /// The carries of the buffer begun before the write, all ended: the records' bytes read in + /// an earlier write that found as many are the bytes now. + pub(super) fn carries_begun(&self) -> u64 { + self.begun + } +} + +impl Drop for Writing<'_> { + fn drop(&mut self) { + self.under_way.fetch_sub(1, Ordering::Release); + } +} + +/// A carry's stop of the writes without the lock ([`Writers::stop`]). +pub(super) struct Stopped<'a>(&'a Writers); + +impl Drop for Stopped<'_> { + fn drop(&mut self) { + self.0.carries.fetch_sub(1, Ordering::Release); + } +} + +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +thread_local! { + /// The hook this thread's next carry runs where it finds a write under way. + static WAITS_HOOK: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; +} + +/// Have this thread's next carry that finds a write without the lock under way run `hook` +/// before it waits: a device test's proof that the carry waits (`tests::icb_carry_race`). +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) fn on_carry_waits(hook: impl FnOnce() + 'static) { + WAITS_HOOK.with(|armed| *armed.borrow_mut() = Some(Box::new(hook))); +} + +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +fn waits_hook() { + if let Some(hook) = WAITS_HOOK.with(|armed| armed.borrow_mut().take()) { + hook(); + } +} diff --git a/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs b/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs index 3e84d635b..e71848be5 100644 --- a/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs +++ b/crates/metal2vulkan-runtime/src/rate_mapped_pass.rs @@ -702,11 +702,25 @@ pub(super) fn index_range(regions: u64, per_primitive: u32) -> u32 { /// its end after its last; read, counted (`WorkCounts::rate_map_piece_gpu_nanos`) and given back /// as the command buffer lets go of what it retained, once its work completed or it failed. Or /// the GPU time of a host step's probe (the module docs, **Fan-out**), one piece, counted -/// (`WorkCounts::rate_map_probe_gpu_nanos`) and given back once the step waited for it. +/// (`WorkCounts::rate_map_probe_gpu_nanos`) and given back once the step waited for it. Or the +/// GPU time of a blit's dispatch that resets an indirect command buffer's commands +/// (`blit_indirect.rs`), one piece, counted (`WorkCounts::indirect_record_reset_gpu_nanos`) as a +/// pass's pieces are. pub(super) struct PieceTimes { device: Device, slots: Vec, - probe: bool, + timed: Timed, +} + +/// What a [`PieceTimes`] times, which names the count its times go to. +#[derive(Clone, Copy)] +enum Timed { + /// A pass's pieces (`WorkCounts::rate_map_piece_gpu_nanos`). + Pieces, + /// A host step's probe (`WorkCounts::rate_map_probe_gpu_nanos`). + Probe, + /// A blit's reset dispatch (`WorkCounts::indirect_record_reset_gpu_nanos`). + IcbReset, } impl PieceTimes { @@ -718,22 +732,36 @@ impl PieceTimes { if pieces < 2 { return None; } - PieceTimes::slots(device, pieces, false) + PieceTimes::slots(device, pieces, Timed::Pieces) } /// A slot for a host step's probe recorded on `device` (the module docs, **Fan-out**), its one /// piece; `None` as for [`take`](Self::take). pub(super) fn probe(device: &Device) -> Option { - PieceTimes::slots(device, 1, true) + PieceTimes::slots(device, 1, Timed::Probe) } - /// `pieces` slots of `device`'s, a probe's where `probe` says. - fn slots(device: &Device, pieces: usize, probe: bool) -> Option { - let shared = device.shared(); - // Timestamps that wait for every queue's would serialize the device's queues. - if shared.timing.host_clock_reason() == Some(FromHost::Driver) { + /// A slot for a blit's dispatch on `device` that resets an indirect command buffer's + /// commands (`blit_indirect.rs`), its one piece; `None` as for [`take`](Self::take): such a + /// device counts no time of it. + pub(super) fn icb_reset(device: &Device) -> Option { + PieceTimes::slots(device, 1, Timed::IcbReset) + } + + /// Whether `device` times what these time: it writes timestamps, and its driver's + /// timestamps do not wait for every queue's, which would serialize the device's queues (a + /// device asked to answer command buffers' GPU times from the host still times them). + pub(super) fn timed_on(device: &Device) -> bool { + let timing = &device.shared().timing; + timing.clock().is_some() && timing.host_clock_reason() != Some(FromHost::Driver) + } + + /// `pieces` slots of `device`'s, for what `timed` says. + fn slots(device: &Device, pieces: usize, timed: Timed) -> Option { + if !PieceTimes::timed_on(device) { return None; } + let shared = device.shared(); let raw = shared.vk(); let slots = (0..pieces) // SAFETY: the timing is the live device's. @@ -742,7 +770,7 @@ impl PieceTimes { Some(PieceTimes { device: device.clone(), slots, - probe, + timed, }) } @@ -812,9 +840,10 @@ impl Drop for PieceTimes { let [[start, started], [end, ended]] = result; if matches!(read, Ok(()) | Err(vk::Result::NOT_READY)) && started != 0 && ended != 0 { let nanos = clock.duration(start, end); - match self.probe { - true => shared.counts.rate_map_probe_time(nanos), - false => shared.counts.rate_map_piece_time(nanos), + match self.timed { + Timed::Pieces => shared.counts.rate_map_piece_time(nanos), + Timed::Probe => shared.counts.rate_map_probe_time(nanos), + Timed::IcbReset => shared.counts.indirect_record_reset_time(nanos), } } } diff --git a/crates/metal2vulkan-runtime/src/tests/device_recovery.rs b/crates/metal2vulkan-runtime/src/tests/device_recovery.rs index f53adf297..edf7dc7b1 100644 --- a/crates/metal2vulkan-runtime/src/tests/device_recovery.rs +++ b/crates/metal2vulkan-runtime/src/tests/device_recovery.rs @@ -18,6 +18,7 @@ use crate::{ DegradeNotice, Device, DeviceKind, DeviceOptions, Error, EventRef, MessageSink, ResourceOptions, ShaderCacheOptions, }; +use metal2vulkan::device::VkExtension; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; @@ -53,7 +54,14 @@ impl Drop for Scratch { /// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU, its shader cache /// in `cache`. pub(super) fn device(cache: &Path) -> Device { - device_with(cache, None) + device_with(cache, None, &[]) +} + +/// [`device`] made without `VK_EXT_external_memory_host` (`DeviceOptions::withheld_extensions`), +/// as a device whose driver lists none is: the runtime's own buffers lie in pooled memory, an +/// indirect command buffer's records among them, which a recovery's carry moves. +pub(super) fn pooled_device(cache: &Path) -> Device { + device_with(cache, None, &[VkExtension::ExtExternalMemoryHost]) } /// The degrade notices a device's sink heard, in order. @@ -69,11 +77,13 @@ pub(super) fn heard_device(cache: &Path, heard: &Heard) -> Device { heard.lock().unwrap().push(notice.clone()); } })), + &[], ) } -/// [`device`], its messages sent to `messages` where given. -fn device_with(cache: &Path, messages: Option) -> Device { +/// [`device`], its messages sent to `messages` where given, made without the extensions +/// `withheld`. +fn device_with(cache: &Path, messages: Option, withheld: &[VkExtension]) -> Device { let options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { true => vec![DeviceKind::Cpu], @@ -88,6 +98,7 @@ fn device_with(cache: &Path, messages: Option) -> Device { ..ShaderCacheOptions::default() }, messages, + withheld_extensions: withheld.iter().copied().collect(), ..DeviceOptions::default() }; Device::system_default_with(&options).unwrap() diff --git a/crates/metal2vulkan-runtime/src/tests/icb_carry_race.rs b/crates/metal2vulkan-runtime/src/tests/icb_carry_race.rs index 27e9af8eb..6000ba416 100644 --- a/crates/metal2vulkan-runtime/src/tests/icb_carry_race.rs +++ b/crates/metal2vulkan-runtime/src/tests/icb_carry_race.rs @@ -3,11 +3,16 @@ //! //! - the commands the CPU encoded before it read back and run after it, as Metal keeps a //! buffer's records across its GPU's restart, where the records lie in the runtime's own pages, -//! as they do on a device that imports host pointers; -//! - a set held by a hook (`hold_next_set`) once its batch is made, while the recovery runs to the -//! end, writes the records the recovered buffer holds once let go, as a set made after the -//! carry does, where the carry moved them to new memory (a buffer of pooled memory: its records -//! reset there) as where it kept them. +//! as they do on a device that imports host pointers; and a setter's write without the lock, +//! held by a hook (`hold_next_set`) inside it while the recovery runs to the end, lands there; +//! - on a device that imports none, whose buffers' records lie in pooled memory, which the carry +//! moves to new memory and resets: a set held once its batch is made, while the recovery runs to +//! the end, writes the records the recovered buffer holds once let go, as a set made after the +//! carry does, under the lock or without it; a set of the state the command named before the +//! carry takes the lock; and one held inside its write without the lock, once it read the +//! records' bytes, is waited for by the carry (`indirect_command_buffer/writers.rs`), so it +//! lands before the carry; a getter of the slots past the records held once it read their +//! address reads what they held before the carry. //! //! The tests print whether the carry kept the records' pages (`Kept`) or moved them (`Lost`). //! @@ -15,91 +20,380 @@ //! the cfg selects (docs/VALIDATION.md). No GPU fault: the loss is marked (`Device::recover_for_test`). //! The function is the owned fixture `examples/runtime_examples.ll` (`llvm-as`). -use super::device_recovery::{device, Scratch}; +use super::device_recovery::{device, pooled_device, Scratch}; use super::device_recovery_carry::BYTES; use super::device_recovery_live_table::{ dispatched, dispatches, encode_command, execute, indirect_state, WORDS, }; -use crate::indirect_command_buffer::hold_next_set; +use crate::indirect_command_buffer::{hold_next_set, on_carry_waits, HoldAt}; use crate::{ - Device, Error, IndirectCommandBuffer, IndirectCommandBufferDescriptor, ResourceOptions, Size, + Buffer, ComputePipelineState, Device, Error, IndirectCommandBuffer, + IndirectCommandBufferDescriptor, ResourceOptions, Size, }; use metal2vulkan::metal::IndirectCommandType; use std::sync::mpsc; +use std::time::{Duration, Instant}; -/// `set` of `icb` on a thread of its own, held by its first field's hook while `device` recovers, -/// then let go: its answer, and whether the recovery's carry moved the records to new memory. +/// How long a test waits for the carry to reach the write it holds. +const WAIT: Duration = Duration::from_secs(60); + +/// What a recovery's carry did with a buffer's records, from their address before it: kept +/// their pages, or moved them to new memory. +fn carried(icb: &IndirectCommandBuffer, before: usize) -> &'static str { + match icb.records_address() == before { + true => "Kept", + false => "Lost", + } +} + +/// A racing setter's thread, held by its hook until let go. +struct Racer { + thread: std::thread::JoinHandle>, + go: mpsc::Sender<()>, +} + +impl Racer { + /// `set` of `icb` on a thread of its own, held at `at` by its hook, once it is held there. + fn held( + icb: &IndirectCommandBuffer, + at: HoldAt, + set: impl FnOnce(&IndirectCommandBuffer) -> Result<(), Error> + Send + 'static, + ) -> Racer { + let (held_tx, held) = mpsc::channel(); + let (go, go_rx) = mpsc::channel::<()>(); + let thread = { + let icb = icb.clone(); + std::thread::spawn(move || { + hold_next_set(at, move || { + held_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + }); + set(&icb) + }) + }; + held.recv().unwrap(); + Racer { thread, go } + } + + /// Let it go: its answer. + fn go(self) -> Result<(), Error> { + self.go.send(()).unwrap(); + self.thread.join().unwrap() + } +} + +/// `set` of `icb` held once its batch is made while `device` recovers to the end, then let go: +/// its answer, and what the recovery's carry did with the records ([`carried`]). fn raced( device: &Device, icb: &IndirectCommandBuffer, set: impl FnOnce(&IndirectCommandBuffer) -> Result<(), Error> + Send + 'static, -) -> (Result<(), Error>, bool) { - let (held_tx, held) = mpsc::channel(); - let (go, go_rx) = mpsc::channel::<()>(); +) -> (Result<(), Error>, &'static str) { let before = icb.records_address(); - let racer = { - let icb = icb.clone(); - std::thread::spawn(move || { - hold_next_set(move || { - held_tx.send(()).unwrap(); - go_rx.recv().unwrap(); - }); - set(&icb) - }) - }; - held.recv().unwrap(); + let racer = Racer::held(icb, HoldAt::Set, set); device.recover_for_test().unwrap(); - let moved = icb.records_address() != before; - go.send(()).unwrap(); - (racer.join().unwrap(), moved) + let carry = carried(icb, before); + (racer.go(), carry) } -/// The first dispatch set on a buffer, which adds to what its records may hold and so is written -/// under the buffer's lock, held once its batch is made while a recovery carries the buffer: -/// let go, it takes the lock after the carry and writes the records there. The recovered -/// command answers the dispatch, and runs it once its state and buffers are set. Without the -/// records read under the lock, the write landed in the lost generation's memory the batch found. -#[test] -fn a_locked_set_held_across_a_recovery_lands_on_the_recovered_records() { - let scratch = Scratch::new(); - let device = device(&scratch.0); - let compute = indirect_state(&device); - let icb = dispatches(&device); - let (locked, unlocked) = icb.writes_apart(); - let (answer, moved) = raced(&device, &icb, |icb| { - icb.indirect_compute_command_at(0)? - .concurrent_dispatch_threads(Size::new(WORDS, 1, 1), Size::new(32, 1, 1)) - }); - answer.unwrap(); - eprintln!("ICB-CARRY-RACE locked set: the carry moved the records: {moved}"); - // The racing write went under the lock: the path under test ran. - let (locked_now, unlocked_now) = icb.writes_apart(); - assert_eq!((locked_now - locked, unlocked_now - unlocked), (1, 0)); - let command = icb.indirect_compute_command_at(0).unwrap(); - assert_eq!( - command.command_type().unwrap(), - IndirectCommandType::CONCURRENT_DISPATCH_THREADS, - "the dispatch set across the recovery (records moved: {moved})" - ); - let queue = device.new_command_queue().unwrap(); +/// Three `Private` buffers of `device`: a dispatch's input, output and scale. +fn buffers(device: &Device) -> [Buffer; 3] { let private = || { device .new_buffer(BYTES, ResourceOptions::private()) .unwrap() }; - let (input, output, scale) = (private(), private(), private()); - command.set_compute_pipeline_state(&compute).unwrap(); - for (slot, buffer) in [&input, &output, &scale].into_iter().enumerate() { - command - .set_kernel_buffer(Some(buffer), 0, slot as u32) - .unwrap(); + [private(), private(), private()] +} + +/// The writes of `icb` since `before`, `writes_apart`'s: those under the lock and those without. +fn writes_since(icb: &IndirectCommandBuffer, before: (u64, u64)) -> (u64, u64) { + let (locked, unlocked) = icb.writes_apart(); + (locked - before.0, unlocked - before.1) +} + +/// `icb`'s command 0, with `state` and each of `buffers` but at slot `unset`, run: what +/// `execute` reads back. +fn run_but( + device: &Device, + icb: &IndirectCommandBuffer, + state: &ComputePipelineState, + buffers: &[Buffer; 3], + unset: Option, +) -> Vec { + let command = icb.indirect_compute_command_at(0).unwrap(); + command.set_compute_pipeline_state(state).unwrap(); + for (slot, buffer) in (0..).zip(buffers) { + if Some(slot) != unset { + command.set_kernel_buffer(Some(buffer), 0, slot).unwrap(); + } } + let queue = device.new_command_queue().unwrap(); + let [input, output, scale] = buffers; + execute(device, &queue, icb, [input, output, scale]) +} + +/// The first dispatch set on a buffer of pooled memory, which adds to what its records may hold +/// and so is written under the buffer's lock, held once its batch is made while a recovery +/// carries the buffer: let go, it takes the lock after the carry and writes the records there. +/// The recovered command answers the dispatch, and runs it once its state and buffers are set. +/// Without the records read under the lock, the write landed in the lost generation's memory the +/// batch found. +#[test] +fn a_locked_set_held_across_a_recovery_lands_on_the_recovered_records() { + let scratch = Scratch::new(); + let device = pooled_device(&scratch.0); + let compute = indirect_state(&device); + let icb = dispatches(&device); + let before = icb.writes_apart(); + let (answer, carry) = raced(&device, &icb, |icb| { + icb.indirect_compute_command_at(0)? + .concurrent_dispatch_threads(Size::new(WORDS, 1, 1), Size::new(32, 1, 1)) + }); + answer.unwrap(); + eprintln!("ICB-CARRY-RACE locked set, pooled: {carry}"); + // The racing write went under the lock: the path under test ran. + assert_eq!(writes_since(&icb, before), (1, 0)); + let command = icb.indirect_compute_command_at(0).unwrap(); assert_eq!( - execute(&device, &queue, &icb, [&input, &output, &scale]), + command.command_type().unwrap(), + IndirectCommandType::CONCURRENT_DISPATCH_THREADS, + "the dispatch set across the recovery ({carry})" + ); + let buffers = buffers(&device); + assert_eq!( + run_but(&device, &icb, &compute, &buffers, None), dispatched() ); } +/// A buffer slot's set on a buffer of pooled memory, written without the lock, held once its +/// batch is made while a recovery carries the buffer: let go, it reads the records' bytes after +/// the carry and writes the records there. The recovered command answers the buffer, and runs +/// with it once the rest is set. Without the bytes read in the write, the batch's bytes were the +/// lost generation's. +#[test] +fn an_unlocked_set_held_across_a_recovery_lands_on_the_recovered_records() { + let scratch = Scratch::new(); + let device = pooled_device(&scratch.0); + let compute = indirect_state(&device); + let icb = dispatches(&device); + let buffers = buffers(&device); + let output = buffers[1].clone(); + let address = output.gpu_address(); + let before = icb.writes_apart(); + let (answer, carry) = raced(&device, &icb, move |icb| { + icb.indirect_compute_command_at(0)? + .set_kernel_buffer(Some(&output), 0, 1) + }); + answer.unwrap(); + eprintln!("ICB-CARRY-RACE unlocked set, pooled: {carry}"); + // The racing write went without the lock: the path under test ran. + assert_eq!(writes_since(&icb, before), (0, 1)); + let command = icb.indirect_compute_command_at(0).unwrap(); + let slot = command.kernel_buffer(1).unwrap(); + assert_eq!( + slot.map(|binding| binding.address), + Some(address), + "the buffer set across the recovery ({carry})" + ); + command + .concurrent_dispatch_threads(Size::new(WORDS, 1, 1), Size::new(32, 1, 1)) + .unwrap(); + assert_eq!( + run_but(&device, &icb, &compute, &buffers, Some(1)), + dispatched() + ); +} + +/// A set of the state the command names, on a buffer of pooled memory, held once its batch is +/// made while a recovery carries the buffer (which resets the command and forgets the commands' +/// keys): let go, it finds the command naming no state since the carry, and sets the state under +/// the lock with every check, rather than writing its ID again without it. The command runs the +/// state. +#[test] +fn a_set_of_the_named_state_across_a_recovery_takes_the_lock() { + let scratch = Scratch::new(); + let device = pooled_device(&scratch.0); + let compute = indirect_state(&device); + let icb = dispatches(&device); + let buffers = buffers(&device); + let [input, output, scale] = &buffers; + encode_command(&icb, &compute, [input, output, scale]); + // Set again before the recovery: the command names the state, so it goes without the lock. + let before = icb.writes_apart(); + let command = icb.indirect_compute_command_at(0).unwrap(); + command.set_compute_pipeline_state(&compute).unwrap(); + assert_eq!(writes_since(&icb, before), (0, 1)); + let before = icb.writes_apart(); + let state = compute.clone(); + let (answer, carry) = raced(&device, &icb, move |icb| { + icb.indirect_compute_command_at(0)? + .set_compute_pipeline_state(&state) + }); + answer.unwrap(); + eprintln!("ICB-CARRY-RACE named state, pooled: {carry}"); + assert_eq!( + writes_since(&icb, before), + (1, 0), + "the set after the carry took the lock ({carry})" + ); + let command = icb.indirect_compute_command_at(0).unwrap(); + command + .concurrent_dispatch_threads(Size::new(WORDS, 1, 1), Size::new(32, 1, 1)) + .unwrap(); + for (slot, buffer) in (0..).zip(&buffers) { + command.set_kernel_buffer(Some(buffer), 0, slot).unwrap(); + } + let queue = device.new_command_queue().unwrap(); + assert_eq!( + execute(&device, &queue, &icb, [input, output, scale]), + dispatched() + ); +} + +/// A buffer slot's set on a buffer of pooled memory, held inside its write without the lock once +/// it read the records' bytes: a recovery on another thread reaches the buffer's carry, which +/// waits for the write (the carry's hook says so, the recovery not ended), and ends once the +/// write is let go. The write landed before the carry, which moved the records to new memory and +/// reset the command there, so it holds no buffer. Without the wait, the recovery ended while the +/// write held the lost generation's bytes. +#[test] +fn a_recovery_s_carry_waits_for_a_write_without_the_lock() { + let scratch = Scratch::new(); + let device = pooled_device(&scratch.0); + let compute = indirect_state(&device); + let icb = dispatches(&device); + let buffers = buffers(&device); + let output = buffers[1].clone(); + let records = icb.records_address(); + let before = icb.writes_apart(); + let racer = Racer::held(&icb, HoldAt::Write, move |icb| { + icb.indirect_compute_command_at(0)? + .set_kernel_buffer(Some(&output), 0, 1) + }); + let (waits_tx, waits) = mpsc::channel(); + let recovery = { + let device = device.clone(); + std::thread::spawn(move || { + on_carry_waits(move || waits_tx.send(()).unwrap()); + device.recover_for_test() + }) + }; + let began = Instant::now(); + loop { + match waits.recv_timeout(Duration::from_millis(10)) { + Ok(()) => break, + Err(_) => { + assert!( + !recovery.is_finished(), + "the recovery ended while a write without the lock held the records' bytes" + ); + assert!(began.elapsed() < WAIT, "the carry never reached the write"); + } + } + } + // The carry waits for the write held: the recovery cannot end before it is let go. + assert!(!recovery.is_finished()); + racer.go().unwrap(); + recovery.join().unwrap().unwrap(); + let carry = carried(&icb, records); + eprintln!("ICB-CARRY-RACE held write, pooled: {carry}"); + assert_eq!(carry, "Lost", "pooled records moved by the carry"); + assert_eq!(writes_since(&icb, before), (0, 1)); + let slot = icb + .indirect_compute_command_at(0) + .unwrap() + .kernel_buffer(1) + .unwrap() + .map(|binding| binding.address); + assert_eq!(slot, None, "the command reset by the carry"); + let [input, output, scale] = &buffers; + encode_command(&icb, &compute, [input, output, scale]); + let queue = device.new_command_queue().unwrap(); + assert_eq!( + execute(&device, &queue, &icb, [input, output, scale]), + dispatched() + ); +} + +/// A buffer slot's set on a buffer whose records lie in the runtime's own pages, held inside its +/// write without the lock once it read the records' bytes while a recovery runs to the end: the +/// carry keeps the pages and waits for nothing, and the write, let go, lands in the records the +/// recovered buffer holds. The command answers the buffer and runs with it. +#[test] +fn a_write_held_across_a_recovery_lands_on_the_records_it_keeps() { + let scratch = Scratch::new(); + let device = device(&scratch.0); + let compute = indirect_state(&device); + let icb = dispatches(&device); + let buffers = buffers(&device); + let output = buffers[1].clone(); + let address = output.gpu_address(); + let records = icb.records_address(); + let before = icb.writes_apart(); + let racer = Racer::held(&icb, HoldAt::Write, move |icb| { + icb.indirect_compute_command_at(0)? + .set_kernel_buffer(Some(&output), 0, 1) + }); + device.recover_for_test().unwrap(); + let carry = carried(&icb, records); + eprintln!("ICB-CARRY-RACE held write, own pages: {carry}"); + racer.go().unwrap(); + assert_eq!( + carry, "Kept", + "records in the runtime's own pages kept by the carry" + ); + assert_eq!(writes_since(&icb, before), (0, 1)); + let command = icb.indirect_compute_command_at(0).unwrap(); + let slot = command.kernel_buffer(1).unwrap(); + assert_eq!(slot.map(|binding| binding.address), Some(address)); + command + .concurrent_dispatch_threads(Size::new(WORDS, 1, 1), Size::new(32, 1, 1)) + .unwrap(); + assert_eq!( + run_but(&device, &icb, &compute, &buffers, Some(1)), + dispatched() + ); +} + +/// A getter of a threadgroup length past the record's, which the slots past the records hold, on +/// a buffer of pooled memory, held once it read their bytes' address while a recovery carries the +/// buffer to the end (the slots moved to new memory, where they read zero): let go, it reads the +/// length set before the carry from the lost generation's bytes, which its hold kept. Without the +/// hold, the read reached memory the lost generation let go of at its rest. +#[test] +fn a_getter_held_across_a_recovery_reads_the_slots_it_found() { + let scratch = Scratch::new(); + let device = pooled_device(&scratch.0); + let icb = dispatches(&device); + let command = icb.indirect_compute_command_at(0).unwrap(); + command.set_threadgroup_memory_length(64, 31).unwrap(); + let records = icb.records_address(); + let (held_tx, held) = mpsc::channel(); + let (go, go_rx) = mpsc::channel::<()>(); + let reader = { + let icb = icb.clone(); + std::thread::spawn(move || { + hold_next_set(HoldAt::Read, move || { + held_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + }); + icb.indirect_compute_command_at(0)? + .threadgroup_memory_length(31) + }) + }; + held.recv().unwrap(); + device.recover_for_test().unwrap(); + go.send(()).unwrap(); + assert_eq!(reader.join().unwrap().unwrap(), Some(64)); + // Read again, the carried slots, moved to new memory: zero. + let carry = carried(&icb, records); + let now = command.threadgroup_memory_length(31).unwrap(); + eprintln!("ICB-CARRY-RACE held read, pooled: {carry}, the slot after the carry: {now:?}"); + assert_eq!((carry, now), ("Lost", Some(0))); +} + /// The render commands of [`a_recovery_keeps_the_commands_the_cpu_encoded`]'s buffer of draws. const DRAWS: u64 = 64; diff --git a/crates/metal2vulkan-runtime/src/tests/icb_encode_bench.rs b/crates/metal2vulkan-runtime/src/tests/icb_encode_bench.rs index 9c5945371..e00f88789 100644 --- a/crates/metal2vulkan-runtime/src/tests/icb_encode_bench.rs +++ b/crates/metal2vulkan-runtime/src/tests/icb_encode_bench.rs @@ -17,22 +17,30 @@ //! - **draw only**: the command and its draw; //! - **command only**: `indirect_render_command_at(i)` alone. //! +//! Each case runs on the device the cfg selects, whose indirect command buffers' records lie in +//! the runtime's own pages where it imports host pointers, then (`pooled`) on one made without +//! `VK_EXT_external_memory_host`, whose records lie in pooled memory, where each setter's write +//! without the lock counts itself under way for a recovery's carry (`writers.rs`). +//! //! Printed as `ICB-ENCODE` lines, beside the sizes of `Result<(), Error>` and `Error`. Nothing is -//! submitted. Ignored: run it in release, under the GPU safety cfg. +//! submitted. Beside it, what live indirect command buffers add to a submission +//! ([`icb_submission_costs`]), printed as `ICB-SUBMIT` lines. Ignored: run them in release, under +//! the GPU safety cfg. //! //! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on the kind of device the cfg selects. -use super::blit_holds::{device, Scratch}; +use super::blit_holds::{device, options, Scratch}; use super::indirect_command_buffer_device::{compute_state, render_state, EXAMPLES}; use crate::{ - DrawPrimitiveType, Error, IndirectCommandBuffer, IndirectCommandBufferDescriptor, + Device, DrawPrimitiveType, Error, IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectComputeSet, IndirectRenderSet, ResourceOptions, Size, }; use metal2vulkan::bind::indirect_commands::COMMAND_BYTES; +use metal2vulkan::device::VkExtension; use metal2vulkan::metal::IndirectCommandType; use std::hint::black_box; -use std::time::Instant; +use std::time::{Duration, Instant}; /// The commands of the large buffer, and the commands encoded a loop. const COMMANDS: u64 = 16384; @@ -68,7 +76,14 @@ fn print(case: &str, (median, least): (f64, f64)) { #[ignore = "a release-mode benchmark"] fn icb_encode_costs() { let scratch = Scratch::new("icb-encode"); - let device = device(&scratch.0); + encode_costs(&device(&scratch.0), ""); + let mut pooled = options(&scratch.0); + pooled.withheld_extensions = [VkExtension::ExtExternalMemoryHost].into_iter().collect(); + encode_costs(&Device::system_default_with(&pooled).unwrap(), ", pooled"); +} + +/// [`icb_encode_costs`]'s cases on `device`, each named after `of`. +fn encode_costs(device: &Device, of: &str) { let mut descriptor = IndirectCommandBufferDescriptor::new(); descriptor.command_types = IndirectCommandType::DRAW | IndirectCommandType::DRAW_INDEXED @@ -83,8 +98,8 @@ fn icb_encode_costs() { ); let strip = DrawPrimitiveType::from_raw(4).unwrap(); let triangle = DrawPrimitiveType::from_raw(3).unwrap(); - let render = render_state(&device, true); - let compute = compute_state(&device, EXAMPLES, "scale_and_offset", true); + let render = render_state(device, true); + let compute = compute_state(device, EXAMPLES, "scale_and_offset", true); let mut compute_descriptor = IndirectCommandBufferDescriptor::new(); compute_descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH; compute_descriptor.max_kernel_buffer_bind_count = 2; @@ -101,8 +116,10 @@ fn icb_encode_costs() { .new_indirect_command_buffer(&descriptor, size, shared) .unwrap(); let records = size * COMMAND_BYTES as u64 / 1024; + let own = icb.records_in_own_pages(); + eprintln!("ICB-ENCODE {size} commands{of}: records in the runtime's own pages: {own}"); print( - &format!("{size} commands ({records} KiB of records), full slot"), + &format!("{size} commands{of} ({records} KiB of records), full slot"), per_command(size, |i| { let command = icb.indirect_render_command_at(i).unwrap(); command.set_render_pipeline_state(&render).unwrap(); @@ -142,14 +159,14 @@ fn icb_encode_costs() { ] }; print( - &format!("{size} commands, full slot, set_each"), + &format!("{size} commands{of}, full slot, set_each"), per_command(size, |i| { let command = icb.indirect_render_command_at(i).unwrap(); command.set_each(render_sets(i)).unwrap(); }), ); print( - &format!("{size} commands, full slot, set_render_command"), + &format!("{size} commands{of}, full slot, set_render_command"), per_command(size, |i| { icb.set_render_command(i, render_sets(i)).unwrap(); }), @@ -158,7 +175,7 @@ fn icb_encode_costs() { .new_indirect_command_buffer(&compute_descriptor, size, shared) .unwrap(); print( - &format!("{size} commands, compute slot"), + &format!("{size} commands{of}, compute slot"), per_command(size, |i| { let command = dispatches.indirect_compute_command_at(i).unwrap(); command.set_compute_pipeline_state(&compute).unwrap(); @@ -191,20 +208,20 @@ fn icb_encode_costs() { ] }; print( - &format!("{size} commands, compute slot, set_each"), + &format!("{size} commands{of}, compute slot, set_each"), per_command(size, |i| { let command = dispatches.indirect_compute_command_at(i).unwrap(); command.set_each(compute_sets(i)).unwrap(); }), ); print( - &format!("{size} commands, compute slot, set_compute_command"), + &format!("{size} commands{of}, compute slot, set_compute_command"), per_command(size, |i| { dispatches.set_compute_command(i, compute_sets(i)).unwrap(); }), ); print( - &format!("{size} commands, three fields"), + &format!("{size} commands{of}, three fields"), per_command(size, |i| { let command = icb.indirect_render_command_at(i).unwrap(); command @@ -217,17 +234,78 @@ fn icb_encode_costs() { }), ); print( - &format!("{size} commands, draw only"), + &format!("{size} commands{of}, draw only"), per_command(size, |i| { let command = icb.indirect_render_command_at(i).unwrap(); command.draw_primitives(strip, 1, 3, 2, 7).unwrap(); }), ); print( - &format!("{size} commands, command only"), + &format!("{size} commands{of}, command only"), per_command(size, |i| { black_box(icb.indirect_render_command_at(i).unwrap()); }), ); } } + +/// The submissions each case of [`icb_submission_costs`] times, after one untimed. +const SUBMITS: usize = 400; + +/// The indirect command buffers [`icb_submission_costs`] holds alive. +const LIVE: [u64; 2] = [64, 256]; + +/// What live indirect command buffers add to a submission: the median and least of [`SUBMITS`] +/// commits of a command buffer of one 16-byte fill, each waited for, with none of the bench's +/// buffers alive, then with [`LIVE`] of them alive, each of 64 commands. Where the device imports +/// host pointers each one's records are a held import of their own (`fresh_pages.rs`, counted by +/// `WorkCounts::fresh_page_buffers_made`), which a driver that lists every held import in every +/// submission pays for each (the import tax, `submit_check.rs`). +#[test] +#[ignore = "a release-mode benchmark"] +fn icb_submission_costs() { + let scratch = Scratch::new("icb-submit"); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let target = device.new_buffer(4096, ResourceOptions::private()).unwrap(); + let submit = || { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&target, 0..16, 1).unwrap(); + blit.end_encoding().unwrap(); + let start = Instant::now(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed().unwrap(); + start.elapsed() + }; + let costs = || { + submit(); + let mut times: Vec = (0..SUBMITS).map(|_| submit()).collect(); + times.sort(); + (times[times.len() / 2], times[0]) + }; + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::DRAW; + descriptor.max_vertex_buffer_bind_count = 2; + eprintln!("ICB-SUBMIT {}", device.name()); + let (median, least) = costs(); + eprintln!("ICB-SUBMIT none alive: median {median:?} a submission, least {least:?}"); + for live in LIVE { + let before = device.work_counts().fresh_page_buffers_made; + let held: Vec = (0..live) + .map(|_| { + device + .new_indirect_command_buffer(&descriptor, 64, ResourceOptions::shared()) + .unwrap() + }) + .collect(); + let imports = device.work_counts().fresh_page_buffers_made - before; + let own = held.iter().filter(|icb| icb.records_in_own_pages()).count(); + let (median, least) = costs(); + eprintln!( + "ICB-SUBMIT {live} alive ({own} in the runtime's own pages, {imports} fresh-page \ + buffers made): median {median:?} a submission, least {least:?}" + ); + drop(held); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer_device.rs b/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer_device.rs index 5dc241146..f8f5bf0ec 100644 --- a/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/indirect_command_buffer_device.rs @@ -306,6 +306,61 @@ fn a_blit_counts_the_record_bytes_the_gpu_moves() { ); } +/// A blit's reset of commands counts its dispatch's GPU time +/// (`WorkCounts::indirect_record_reset_gpu_nanos`) once its command buffer completed and let go +/// of what it retained, where the device times it (`rate_mapped_pass::PieceTimes::timed_on`: +/// lavapipe does); a command buffer of a copy of commands alone, which dispatches no reset, +/// counts none. +#[test] +fn a_blit_s_reset_counts_its_dispatch_s_gpu_time() { + let scratch = Scratch::new("icb-reset-time"); + let device = device(&scratch.0); + let timed = crate::rate_mapped_pass::PieceTimes::timed_on(&device); + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::DRAW; + let shared = ResourceOptions::shared(); + let icb = device + .new_indirect_command_buffer(&descriptor, 4, shared) + .unwrap(); + let copy = device + .new_indirect_command_buffer(&descriptor, 4, shared) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let nanos = || device.work_counts().indirect_record_reset_gpu_nanos; + // One command buffer of the blit `encode` encodes, completed. + let run = |encode: &dyn Fn(&mut crate::BlitCommandEncoder)| { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + encode(&mut blit); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed().unwrap(); + }; + let before = nanos(); + run(&|blit| { + blit.copy_indirect_command_buffer(&icb, 0..2, ©, 0) + .unwrap() + }); + let copied = nanos() - before; + let before = nanos(); + run(&|blit| blit.reset_commands_in_buffer(&icb, 0..4).unwrap()); + // The time is read as the command buffer lets go of what it retained, once it completed. + let began = std::time::Instant::now(); + while timed && nanos() == before && began.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let reset = nanos() - before; + eprintln!("ICB-RESET-TIME timed {timed}: copy alone {copied} ns, reset {reset} ns"); + assert_eq!( + copied, 0, + "a command buffer with no reset counts no reset time" + ); + match timed { + true => assert!(reset > 0, "the reset's dispatch counted no GPU time"), + false => assert_eq!(reset, 0, "a device that times no reset counts none"), + } +} + /// Render commands: each setter's record, what the records may hold and the CPU's writes are /// the model's, through fields that add, fields that add nothing new, refusals and calls taken /// mid-command, a command's reset and a range's, a record the GPU may have written and one that diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 9428c5e79..0501fe951 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -205,6 +205,7 @@ pub(crate) struct Counters { indirect_record_bytes_copied: AtomicU64, indirect_record_bytes_gpu_copied: AtomicU64, indirect_record_bytes_gpu_reset: AtomicU64, + indirect_record_reset_gpu_nanos: AtomicU64, indirect_write_residencies_unmarked: AtomicU64, indirect_chunks_kept: AtomicU64, indirect_commands_kept: AtomicU64, @@ -2599,6 +2600,12 @@ impl Counters { (self.indirect_record_bytes_gpu_reset).fetch_add(bytes, Ordering::Relaxed); } + /// A blit's dispatch that reset an indirect command buffer's commands ran for `nanos` of the + /// GPU's time (`blit_indirect.rs`, `rate_mapped_pass::PieceTimes`). + pub(crate) fn indirect_record_reset_time(&self, nanos: u64) { + (self.indirect_record_reset_gpu_nanos).fetch_add(nanos, Ordering::Relaxed); + } + /// `count` records of an indirect command buffer's commands were read from its storage and /// decoded (`indirect_command_buffer.rs`). pub(crate) fn indirect_records_read(&self, count: u64) { @@ -6556,6 +6563,14 @@ pub struct WorkCounts { /// (`resetCommandsInBuffer:withRange:`, `blit_indirect.rs`), counted as each reset is /// encoded: `COMMAND_BYTES` a command, written into the buffer's storage. pub indirect_record_bytes_gpu_reset: u64, + /// Nanoseconds of the GPU's time the dispatches of those resets took + /// (`resetCommandsInBuffer:withRange:`, `blit_indirect.rs`), each between timestamps written + /// before and after it in its command buffer and read as the command buffer lets go of what it + /// retained, once it completed: the same timing as a rate-mapped pass's pieces + /// ([`rate_map_piece_gpu_nanos`](Self::rate_map_piece_gpu_nanos)). Counted only where the + /// device writes timestamps and its driver's timestamps do not wait for every queue's + /// (`DriverFact::TimestampsWaitForEveryQueue`); elsewhere none is written and this stays 0. + pub indirect_record_reset_gpu_nanos: u64, /// Indirect command buffers a committed command buffer made resident for writing /// (`use_resource` or `use_resources` with `ResourceUsage::WRITE`, in any of its encoders) and /// left unmarked (`IndirectCommandBuffer::gpu_written` still `false`): it set no pipeline state @@ -10448,6 +10463,8 @@ impl Device { .load(Ordering::Relaxed), indirect_record_bytes_gpu_reset: (counters.indirect_record_bytes_gpu_reset) .load(Ordering::Relaxed), + indirect_record_reset_gpu_nanos: (counters.indirect_record_reset_gpu_nanos) + .load(Ordering::Relaxed), indirect_record_bytes_copied: (counters.indirect_record_bytes_copied) .load(Ordering::Relaxed), indirect_write_residencies_unmarked: (counters.indirect_write_residencies_unmarked) diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index d6bc26dee..a05d4fe29 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 520; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2248; +pub const RUNTIME_VERSION: u32 = 2249; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index e3432d718..f6c944e8d 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3147,6 +3147,7 @@ field metal2vulkan-runtime::WorkCounts.indirect_draws_recorded pub indirect_draw field metal2vulkan-runtime::WorkCounts.indirect_record_bytes_copied pub indirect_record_bytes_copied: u64 field metal2vulkan-runtime::WorkCounts.indirect_record_bytes_gpu_copied pub indirect_record_bytes_gpu_copied: u64 field metal2vulkan-runtime::WorkCounts.indirect_record_bytes_gpu_reset pub indirect_record_bytes_gpu_reset: u64 +field metal2vulkan-runtime::WorkCounts.indirect_record_reset_gpu_nanos pub indirect_record_reset_gpu_nanos: u64 field metal2vulkan-runtime::WorkCounts.indirect_record_runs_read pub indirect_record_runs_read: u64 field metal2vulkan-runtime::WorkCounts.indirect_records_read pub indirect_records_read: u64 field metal2vulkan-runtime::WorkCounts.indirect_write_residencies_unmarked pub indirect_write_residencies_unmarked: u64 diff --git a/docs/API.md b/docs/API.md index 1c1f8aab1..f77fac6b7 100644 --- a/docs/API.md +++ b/docs/API.md @@ -5077,7 +5077,10 @@ each item named states the rule in full. may not have written, takes no lock: a buffer slot, a draw, dispatch or barrier the CPU's writes added already, and a pipeline state the command names already, which is not held either. Each command's first set of a state, and every set after a device recovery carried - the buffer, takes the lock and checks the state. + the buffer, takes the lock and checks the state. Records in the runtime's own pages, as they + are on a device that imports host pointers, are the pages a recovery's carry keeps, so such a + write needs nothing more; in pooled memory, which the carry moves, the carry waits for such a + write under way, and one begun during the carry takes the lock: an atomic add a write. - **A command's read-back answers Metal's private getters**: `command_type`, the buffer addresses and attribute strides, as Metal's `get*` getters answer them. `IndirectComputeCommand` and `IndirectRenderCommand` read one field of their record alone (`command_type`, `has_barrier`, diff --git a/docs/HOWTO.md b/docs/HOWTO.md index b4bd5a57e..35c422283 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -321,6 +321,12 @@ released: MoltenVK 1.4.2 on an M3 Max), a pointer import stays imported: releasing it would save nothing and cost the next blit an import. +An indirect command buffer's records, and the slots past them, lie in an import of the runtime's +own pages wherever the device imports host pointers, whatever the import tax, held for the +buffer's life and never released: a device's recovery keeps the records only there, as Metal keeps +them across its GPU's restart. Each live indirect command buffer is so one more held import, about +0.35 us a submission on ANV on i915 (the tax check's measure) and by its pages on RADV. + A buffer stays imported for good once its Metal address is handed out (`gpu_address`, a binding, an argument buffer or table, an indirect command buffer, `use_resource`), its `VkBuffer` is read, a texture that reads its memory is made over its bytes (a shadow, or an image in place in an import