diff --git a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs index e2b73bc3e..fd68bc02d 100644 --- a/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs +++ b/crates/metal2vulkan-runtime/examples/host_ab/runtime.rs @@ -1294,6 +1294,7 @@ impl Gpu for Runtime { ("completed_waits", c.completed_waits), ("device_memory_bytes", c.device_memory_allocated), ("cleared_bytes", c.new_buffer_bytes_cleared), + ("new_buffer_zero_fills", c.new_buffer_zero_fills), ( "replayed_begin_command_buffer", replayed.begin_command_buffer, @@ -1932,6 +1933,7 @@ impl Gpu for Runtime { c.shadow_copies_back_dispatched, ), ("shadow_copies_in_dispatched", c.shadow_copies_in_dispatched), + ("shadow_keeps_from_staging", c.shadow_keeps_from_staging), ( "shadow_merge_copies_dispatched", c.shadow_merge_copies_dispatched, diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 2a90eafb8..6ab175dd2 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -702,7 +702,10 @@ impl CommandBufferShared { // SAFETY: the command buffer is recording, outside a render pass; it is // submitted first in the batch, before any later one, and every batch on // another `VkQueue` waits for the batch (`FirstMoves::waits`). - unsafe { first_work.record(raw, buffer, shared.queue_flags_of(queue)) }; + unsafe { + let family = shared.queue_flags_of(queue); + first_work.record((raw, &shared.counts), buffer, family); + }; } if has_staged { // SAFETY: the command buffer is recording, outside a render pass; every diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs index e09eb3f0d..e6b0aa51e 100644 --- a/crates/metal2vulkan-runtime/src/device/submit.rs +++ b/crates/metal2vulkan-runtime/src/device/submit.rs @@ -200,7 +200,10 @@ impl Device { // SAFETY: recording, outside a render pass, for the queue family; it is submitted // first in the work's submission, which is waited for before anything that uses the // resources is submitted after it. - unsafe { taken.record(raw, objects.buffer, shared.queue_flags_of(0)) }; + unsafe { + let family = shared.queue_flags_of(0); + taken.record((raw, &shared.counts), objects.buffer, family); + }; } // Host calls' staged copies, after the first work, before the work. // SAFETY: recording, outside a render pass; every image's move is recorded before it diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 1341b54b7..4267c51bf 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -1570,8 +1570,10 @@ impl EncoderCore { pub(super) fn shadow_copies(&mut self, copies: &[ShadowCopy]) { let device = self.device().clone(); let mut run = ShadowRun::default(); - // The keeps a dispatch at their copy in took, which record nothing. + // The keeps a dispatch at their copy in took, which record nothing, and those that copy + // the staging buffer their copy in filled. let mut taken = Vec::new(); + let mut staged = Vec::new(); for (i, copy) in copies.iter().enumerate() { if taken.contains(&i) { continue; @@ -1621,15 +1623,32 @@ impl EncoderCore { (self.open.command_buffer.dirty()).gate((log, ©.copies, texel), shadows) }), }; + // A keep may copy the staging buffer its copy in filled only where that copy in + // copies the texture's bytes whole: recorded here, ungated. + if dispatched.is_none() && gate.is_none() { + staged.extend(staged_keep(copies, i)); + } + let from_staging = staged.contains(&i); + let kept = std::cell::Cell::new(false); let record = |device: &Vk, raw: vk::CommandBuffer| match &dispatched { // SAFETY: the encoder's command buffer is recording outside a render pass; its // commands retain the shadowed textures (and their views) and the dispatch until // it completes, and every image rests in the `GENERAL` layout. Some(back) => unsafe { back.record(device, raw) }, + None if from_staging => { + // SAFETY: as above; the keep follows its texture's copy in, after the barrier + // its read of the shadow takes from that copy's write, with no copy of the + // shadow between them (`staged_keep`). + unsafe { copy.record_keep_from_staging(device, raw) }; + kept.set(true); + } // SAFETY: as above; the rows are the copy's own, made just now. None => unsafe { copy.record_gated(device, raw, rows.as_ref(), gate) }, }; self.shadow_command(&mut run, (stages, &uses, copy.writes_truth()), record); + if kept.get() { + device.shared().counts.shadow_keep_from_staging(); + } if let Some(back) = dispatched { device.shared().counts.shadow_copy_back_dispatched(); self.retain(back); @@ -2457,6 +2476,21 @@ fn meets(earlier: &[Use], later: &[Use]) -> bool { }) } +/// The place in `copies` of the keep that copies the staging buffer the copy in at `copies[i]` +/// fills (`ShadowCopy::keeps_from_staging`): its texture's next copy, the copies between them +/// other textures' shadows', which leave its shadow and staging buffer as the copy in left them. +/// `None` where the keep moves its texels out of the image, or no keep follows. +fn staged_keep(copies: &[ShadowCopy], i: usize) -> Option { + let copy = &copies[i]; + if !matches!(copy.step, Step::Into) { + return None; + } + let shadow = copy.copies.shadow_key; + let (j, keep) = (copies.iter().enumerate().skip(i + 1)) + .find(|(_, later)| later.copies.shadow_key == shadow)?; + (Arc::ptr_eq(&keep.copies, ©.copies) && keep.keeps_from_staging()).then_some(j) +} + /// The dispatch that takes the copy in at `copies[i]` and its texture's keep after it together /// (`ShadowMerge::keep_in`, `shadow_copy_in.rs`), where `device` takes one: the keep's place in /// `copies`, the dispatch and its uses. The copies between them are of other textures' shadows, diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index e60499e50..b8f26c7f3 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -835,6 +835,67 @@ impl ShadowCopies { } } + /// Whether a merge's keep and changed copy ([`record_kept`](Self::record_kept), + /// [`record_out`](Self::record_out)) each write every one of the first `length` bytes of its + /// part: a heap's tiled texture's do, as they copy the staging buffer's span of the texture's + /// bytes whole (`HeapTiledCopies::record_out`), or the heap's. + pub(super) fn copies_out_whole(&self, length: u64) -> bool { + match &self.source { + ShadowSource::Bytes { + target: ShadowTarget::Tiled { staging, .. }, + .. + } => staging.into.size >= length, + _ => false, + } + } + + /// Whether a merge's keep right after this shadow's copy in, with no copy of the shadow + /// between, may copy the staging buffer that copy in filled + /// ([`record_kept_from_staging`](Self::record_kept_from_staging)): a heap's tiled texture's + /// whose moves give back each byte they took (`HeapTiledCopies::moves_bits`). + pub(super) fn keeps_from_staging(&self) -> bool { + matches!( + &self.source, + ShadowSource::Bytes { + target: ShadowTarget::Tiled { tiles, .. }, + .. + } if tiles.moves_bits() + ) + } + + /// Record a merge's keep into `to` from `at` as a copy of the staging buffer, right after the + /// shadow's copy in filled it with the heap's bytes and moved them into the image + /// ([`keeps_from_staging`](Self::keeps_from_staging)): the bytes a keep's move out of the + /// image would leave there ([`record_kept`](Self::record_kept)), the texture's bytes from its + /// first, without the move. Nothing for any other shadow. + /// + /// # Safety + /// + /// As `record_out`'s, after a barrier that orders the copy after the copy in, and with no + /// command between them that writes the shadow or its staging buffer. + pub(super) unsafe fn record_kept_from_staging( + &self, + device: &Vk, + command_buffer: vk::CommandBuffer, + (to, at): (vk::Buffer, u64), + ) { + let ShadowSource::Bytes { + target: ShadowTarget::Tiled { staging, .. }, + .. + } = &self.source + else { + return; + }; + let region = vk::BufferCopy { + src_offset: staging.into.dst_offset, + dst_offset: at, + size: staging.into.size, + }; + // SAFETY: the caller's contract; the staging buffer holds the texture's bytes from its + // start (`HeapTiledCopies::staging`), and `to` holds them from `at`. + unsafe { device.cmd_copy_buffer(command_buffer, staging.raw(), to, &[region]) }; + } + /// Record a merge's keep of the shadow's texels into `to` from `at`, laid out as in the /// buffer from the texture's first byte (`shadow_merge.rs`): as /// [`record_out`](Self::record_out) copies them; but where a heap's tiled texture's image @@ -1444,6 +1505,38 @@ impl ShadowCopy { } } + /// Whether this keep may copy the staging buffer its texture's copy in just filled + /// ([`ShadowCopies::keeps_from_staging`]): a keep whose kept part a copy writes. + pub(super) fn keeps_from_staging(&self) -> bool { + matches!(&self.step, Step::Keep(merge) if merge.copied_kept_part().is_some()) + && self.copies.keeps_from_staging() + } + + /// Record this keep as a copy of its texture's staging buffer + /// ([`ShadowCopies::record_kept_from_staging`]), where it + /// [`keeps_from_staging`](Self::keeps_from_staging); any other copy as + /// [`record`](Self::record) records it. + /// + /// # Safety + /// + /// As `record`'s, right after its texture's copy in, with no copy of its shadow between. + pub(super) unsafe fn record_keep_from_staging( + &self, + device: &Vk, + command_buffer: vk::CommandBuffer, + ) { + if let Step::Keep(merge) = &self.step { + if let Some(to) = merge.copied_kept_part() { + // SAFETY: the caller's contract. + return unsafe { + (self.copies).record_kept_from_staging(device, command_buffer, to) + }; + } + } + // SAFETY: the caller's contract. + unsafe { self.record(device, command_buffer, None) } + } + /// Record the copy into `command_buffer`, its staged rows back (where it has them) by `back` /// ([`staged_back`](Self::staged_back)). /// diff --git a/crates/metal2vulkan-runtime/src/shadow_merge.rs b/crates/metal2vulkan-runtime/src/shadow_merge.rs index 97cc44559..b6f19da40 100644 --- a/crates/metal2vulkan-runtime/src/shadow_merge.rs +++ b/crates/metal2vulkan-runtime/src/shadow_merge.rs @@ -15,7 +15,11 @@ //! So the bytes the commands changed through the texture are merged into the buffer's instead: //! //! - **Kept.** Before the command, after its copies in, the shadow's texels are copied into the -//! *kept* part of a scratch buffer, laid out as in the buffer from the texture's first byte. +//! *kept* part of a scratch buffer, laid out as in the buffer from the texture's first byte. A +//! heap's tiled texture of one sample and colour aspects alone, kept right after its copy in +//! with no copy of its shadow between, copies the staging buffer that copy filled with the +//! heap's bytes: the bytes a move of its texels out of the image would leave there, without +//! the move (`ShadowCopies::record_kept_from_staging`, `WorkCounts::shadow_keeps_from_staging`). //! - **Merged in place**, where the texture's first byte is a whole word of its buffer, its last //! byte's word lies in the buffer, and the bytes lie in pages when the merge is planned (not //! detached, `detach.rs`): the shadow's texels are copied into the *changed* part, and the merge @@ -78,7 +82,9 @@ //! retained until its command buffer completes: one, two or three parts of the texture's bytes //! (a cut's rows) rounded up to 256, in one buffer where the device's buffers take it (else one //! each), or a kept image in place of them. A cut merge's copies write its parts' rows back to -//! back, every byte its kernel reads, so its scratch is not zeroed: one of those its shadow's +//! back, every byte its kernel reads, and a heap's tiled texture's merge in place copies the +//! texture's bytes whole (`texture/heap_tiled.rs`), the bytes its kernel reads, so neither +//! scratch is zeroed: one of those its shadow's //! earlier merges were done with, kept once their command buffers completed (at most two, //! `ScratchSpares`; `WorkCounts::shadow_merge_scratches_reused`), else a new one. A kept image //! is its queue's, of any merge of the queue of the same view and extent once the encoder that @@ -400,17 +406,19 @@ impl ShadowMerge { (Held::Image(image), Vec::new()) } else if length <= device.properties().max_buffer_length { // A cut's copies write every byte of its kept and changed parts the kernel reads (its - // rows of whole words, back to back), so its scratch needs no zero: one of the - // shadow's spares, else a new one unzeroed. Every other merge's scratch is new and - // zero. + // rows of whole words, back to back), and so do a heap's tiled texture's in place + // (the texture's bytes whole, which the kernel reads alone), so their scratch needs + // no zero: one of the shadow's spares, else a new one unzeroed. Every other merge's + // scratch is new and zero. + let written = cut.is_some() || (in_place && copies.copies_out_whole(rounded)); let spares = copies.merge_scratch.clone(); - let one = match (&cut, cut.as_ref().and_then(|_| spares.take(length))) { - (Some(_), Some(spare)) => { + let one = match (written, written.then(|| spares.take(length)).flatten()) { + (true, Some(spare)) => { counts.shadow_merge_scratch_reused(); spare } - (Some(_), None) => device.unzeroed_buffer(length, HazardTrackingMode::Default)?, - (None, _) => { + (true, None) => device.unzeroed_buffer(length, HazardTrackingMode::Default)?, + (false, _) => { counts.shadow_merge_scratch_zeroed(); device.own_buffer(length, options)? } @@ -672,6 +680,16 @@ impl ShadowMerge { Ok((merge, lease)) } + /// Where a copy writes the keep's kept part (the keep no dispatch, cut to no rectangle, into + /// no kept image): its `VkBuffer` and where the part starts there; `None` for any other + /// keep. + pub(super) fn copied_kept_part(&self) -> Option<(vk::Buffer, u64)> { + match (&self.keep_dispatch, self.kept_in, &self.cut) { + (None, KeptIn::Part(kept), None) => Some((kept.raw, kept.at)), + _ => None, + } + } + /// Whether the keep is a dispatch (`ShadowMerge::keep_dispatch`), which runs in the compute /// stage. pub(super) fn dispatches(&self) -> bool { diff --git a/crates/metal2vulkan-runtime/src/texture/first_move.rs b/crates/metal2vulkan-runtime/src/texture/first_move.rs index b0eb831ba..d059e6ad6 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move.rs @@ -63,7 +63,10 @@ //! byte over such pages (`in_place.rs`); elsewhere it is a shadow, whose copies address its texels //! alone (`texture.rs`'s `storage_over_buffer`). //! - **The work.** A barrier from every command before (memory other commands wrote), then the -//! buffers' fills with zeros, then their copies of staged bytes after a barrier, then a +//! buffers' fills with zeros (copies of the device's zeros; on a device without unified memory, +//! which would read those over the bus, one `vkCmdFillBuffer` each, counted: +//! `WorkCounts::new_buffer_zero_fills`, `FirstFill::zeros`), then their copies of staged bytes +//! after a barrier, then a //! barrier carrying each image's move (after the fills: an image placed in a new heap moves //! after the heap's fill, so the fill never overwrites what the move wrote), then the images' //! copies of zeros, then a barrier that makes them visible to every later command and to the @@ -109,6 +112,7 @@ use super::super::memory::{Memory, MemoryClass, Placement}; use super::super::release; use super::super::resource::ResourceKey; use super::super::tracker::Point; +use super::super::work_counts::Counters; use super::super::Device; use super::decoded_twin::DecodePass; use super::{buffer_image_copy, image_aspects, transfer_barrier, ImageRegion, ZERO_BYTES}; @@ -609,12 +613,17 @@ const STAGED_BYTES: u64 = 256 << 20; /// them, waited for (the module docs): a bound on the work waiting, whatever its bytes. const STAGED_COPIES: usize = 4096; -/// A new buffer's fill: copies of the device's zeros onto `range` of `buffer`, or of the bytes a -/// staging buffer holds, or a `Managed` buffer's upload from its host copy. +/// A new buffer's fill: copies of the device's zeros onto `range` of `buffer`, or a fill of its +/// words with zeros (`word_fill.rs`), or copies of the bytes a staging buffer holds, or a +/// `Managed` buffer's upload from its host copy. pub(crate) struct FirstFill { buffer: vk::Buffer, source: vk::Buffer, copies: Vec, + /// The words one `vkCmdFillBuffer` sets to zero in place of the copies (none then): on a + /// device without unified memory, whose zeros (`Zeros`, host-visible) a copy would read over + /// the bus ([`FirstFill::zeros`]). + filled: Option>, /// What keeps the staging buffer `source` is, held until the submission that makes the fill /// completed; `None` where `source` is the device's zeros. staging: Option>, @@ -637,10 +646,46 @@ impl FirstFill { buffer, source: zeros, copies, + filled: None, staging: None, } } + /// The zeros of `range` of `buffer` on `device`: one `vkCmdFillBuffer` of its words on a + /// device without unified memory whose fills are `vkCmdFillBuffer`'s (`word_fill.rs`), where + /// the range's ends are multiples of 4; else copies of the device's zeros, made now if they + /// are not yet. A discrete GPU reads those host-visible zeros over the bus: on the RX 7900 XTX + /// (RADV) 512 KiB of them took 66 us to copy and 11 us more in the barrier after it, where a + /// fill of the same bytes took 0.7 us and 2.5 us. The copy stays where the device shares the + /// host's memory, whose zeros lie in the memory the GPU reads anyway (not measured there), + /// and where fills go as transfers (`DriverFact::FillCompiledPerCommandPool`), whose copies + /// within the buffer need `TRANSFER_SRC` usage that a neutral buffer lacks. + fn zeros( + device: &Device, + moves: &FirstMoves, + buffer: vk::Buffer, + range: std::ops::Range, + ) -> Result { + let words = range.start.is_multiple_of(4) && range.end.is_multiple_of(4); + let discrete = !device.properties().has_unified_memory; + if words && discrete && !crate::word_fill::by_transfers(device) { + return Ok(FirstFill { + buffer, + source: vk::Buffer::null(), + copies: Vec::new(), + filled: Some(range), + staging: None, + }); + } + let zeros = moves.zeros(device, 0)?; + Ok(FirstFill::new( + buffer, + range.start, + range.end - range.start, + zeros, + )) + } + /// The copy of `length` bytes of `source` from byte `from` onto `buffer` from byte `start`, /// `staging` keeping `source`. fn bytes( @@ -658,6 +703,7 @@ impl FirstFill { dst_offset: start, size: length, }], + filled: None, staging: Some(staging), } } @@ -890,8 +936,7 @@ impl FirstMoves { buffer: vk::Buffer, range: std::ops::Range, ) -> Result<(), Error> { - let zeros = self.zeros(device, 0)?; - let fill = FirstFill::new(buffer, range.start, range.end - range.start, zeros); + let fill = FirstFill::zeros(device, self, buffer, range)?; let _order = self.registration_place(); lock(&self.waiting).push(Waiting::Fill(keeper, fill)); Ok(()) @@ -1465,7 +1510,7 @@ impl Taken<'_> { /// one of the resources, on the same `VkQueue` or waited for. pub(crate) unsafe fn record( &self, - device: &Vk, + (device, counts): (&Vk, &Counters), command_buffer: vk::CommandBuffer, family: vk::QueueFlags, ) { @@ -1519,6 +1564,18 @@ impl Taken<'_> { } exit_guard::called(Call::CmdPipelineBarrier); } + if let Some(words) = &fill.filled { + // SAFETY: as above; the words lie in the buffer, held, which has `TRANSFER_DST` + // usage as every buffer of the runtime's, their ends multiples of 4 + // (`FirstFill::zeros`). + unsafe { + let (buffer, words) = (fill.buffer, words.clone()); + crate::word_fill::record_command(device, command_buffer, buffer, words, 0); + } + exit_guard::called(Call::CmdFillBuffer); + counts.new_buffer_zero_filled(); + continue; + } // SAFETY: as above; every copy lies within its source, the device's zeros (live and // `ZERO_BYTES` long) or a staging buffer the fill keeps, and within the buffer, // held, which has `TRANSFER_DST` usage as every buffer of the runtime's. diff --git a/crates/metal2vulkan-runtime/src/texture/heap_tiled.rs b/crates/metal2vulkan-runtime/src/texture/heap_tiled.rs index 81f26b594..55eba6bd1 100644 --- a/crates/metal2vulkan-runtime/src/texture/heap_tiled.rs +++ b/crates/metal2vulkan-runtime/src/texture/heap_tiled.rs @@ -1855,6 +1855,18 @@ impl HeapTiledCopies { self.samples.is_some() } + /// Whether the moves between the image and the staging buffer give back each byte they took: + /// a single-sample image of colour aspects alone, whose copies to and from the tight buffer + /// move its texel blocks' bits (a depth aspect's copy writes values outside `[0, 1]` as + /// undefined, `VUID-vkCmdCopyBufferToImage-pRegions-07931`), and whose dispatches move words. + /// So, right after a move in, the staging buffer holds what a move out of the image would + /// leave there (`ShadowCopies::record_kept_from_staging`). + pub(crate) fn moves_bits(&self) -> bool { + self.samples.is_none() + && (self.regions.iter()) + .all(|region| region.image_subresource.aspect_mask == vk::ImageAspectFlags::COLOR) + } + /// Whether the image takes the heap's bytes inexactly: a multisample depth whose moves into /// it draw values the driver's fragment depth changes (`drawn-depth-copy`), which a merge's /// keep then reads from the heap's bytes (`ShadowCopies::record_kept`). diff --git a/crates/metal2vulkan-runtime/src/word_fill.rs b/crates/metal2vulkan-runtime/src/word_fill.rs index afecfa6d3..c09af3c56 100644 --- a/crates/metal2vulkan-runtime/src/word_fill.rs +++ b/crates/metal2vulkan-runtime/src/word_fill.rs @@ -16,8 +16,12 @@ //! (as `vkCmdCopyBuffer` requires), and every word ends as the fill's. //! - **Elsewhere** `vkCmdFillBuffer`, unchanged, on every other driver and release. //! - **Counted.** Each fill counts as one of the two forms (`WorkCounts::fills_recorded` and -//! `fills_by_transfers`), so a run shows which its device took. +//! `fills_by_transfers`), so a run shows which its device took; a new buffer's first zeros +//! filled on a device without unified memory count apart (`WorkCounts::new_buffer_zero_fills`, +//! `texture/first_move.rs`), which takes them only where the device's fills are +//! `vkCmdFillBuffer`'s ([`by_transfers`]). +use crate::device::functions::Vk; use crate::Device; use ash::vk; use metal2vulkan::device::DriverFact; @@ -78,25 +82,14 @@ pub(crate) unsafe fn record( word: u32, ) { let device = owner.shared().vk(); - let by_transfers = owner - .properties() - .driver_facts - .contains(&DriverFact::FillCompiledPerCommandPool); + let by_transfers = by_transfers(owner); if words.is_empty() { return; } owner.shared().counts.fill_recorded(by_transfers); if !by_transfers { // SAFETY: the caller's contract. - unsafe { - device.cmd_fill_buffer( - command_buffer, - buffer, - words.start, - words.end - words.start, - word, - ); - } + unsafe { record_command(device, command_buffer, buffer, words, word) }; return; } let first = (words.end - words.start).min(UPDATE_LIMIT) / 4; @@ -138,3 +131,35 @@ pub(crate) unsafe fn record( } } } + +/// Whether `owner`'s fills go as transfers ([`DriverFact::FillCompiledPerCommandPool`]). +pub(crate) fn by_transfers(owner: &Device) -> bool { + (owner.properties().driver_facts).contains(&DriverFact::FillCompiledPerCommandPool) +} + +/// Record a fill of `words` of `buffer` with `word` as one `vkCmdFillBuffer` with `device`'s +/// functions, uncounted: [`record`]'s form on a device whose fills do not go as transfers +/// ([`by_transfers`]). +/// +/// # Safety +/// +/// `command_buffer` is recording, outside a render pass; `buffer` is live until it completes, +/// made with `TRANSFER_DST` usage, and `words` lies in it, its ends multiples of 4. +pub(crate) unsafe fn record_command( + device: &Vk, + command_buffer: vk::CommandBuffer, + buffer: vk::Buffer, + words: Range, + word: u32, +) { + // SAFETY: the caller's contract. + unsafe { + device.cmd_fill_buffer( + command_buffer, + buffer, + words.start, + words.end - words.start, + word, + ); + } +} diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 0eeb8453a..a0db24d30 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -313,6 +313,7 @@ pub(crate) struct Counters { fresh_page_buffers_made: AtomicU64, fresh_page_bytes: AtomicU64, new_buffer_bytes_cleared: AtomicU64, + new_buffer_zero_fills: AtomicU64, shadow_copies: AtomicU64, shadow_texels_copied_in: AtomicU64, shadow_texels_first_copied_in: AtomicU64, @@ -347,6 +348,7 @@ pub(crate) struct Counters { shadow_texels_copied_back: AtomicU64, shadow_copies_back_dispatched: AtomicU64, shadow_copies_in_dispatched: AtomicU64, + shadow_keeps_from_staging: AtomicU64, shadow_merge_copies_dispatched: AtomicU64, shadow_merge_dispatches_planned: AtomicU64, shadow_merge_words_examined: AtomicU64, @@ -2123,6 +2125,12 @@ impl Counters { (self.new_buffer_bytes_cleared).fetch_add(bytes, Ordering::Relaxed); } + /// A submission's first work zeroed a new buffer's bytes the host cannot write with one + /// `vkCmdFillBuffer` in place of copies of the device's zeros (`texture/first_move.rs`). + pub(crate) fn new_buffer_zero_filled(&self) { + (self.new_buffer_zero_fills).fetch_add(1, Ordering::Relaxed); + } + /// An encoder planned `n` copies between shadowed textures' truths and their shadows /// (`shadow.rs`), whose copies in and back of buffers' textures' images move `texels_in` and /// `texels_back` texels. @@ -2215,6 +2223,13 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// An encoder recorded a heap's tiled texture's keep as a copy of the staging buffer its copy + /// in just filled (`ShadowCopies::record_kept_from_staging`). + pub(crate) fn shadow_keep_from_staging(&self) { + self.shadow_keeps_from_staging + .fetch_add(1, Ordering::Relaxed); + } + /// An encoder recorded a copy of `regions` rows between two buffers (`row_copies.rs`), as one /// dispatch where `dispatched`. pub(crate) fn row_copy(&self, regions: usize, dispatched: bool) { @@ -4331,6 +4346,12 @@ pub struct WorkCounts { /// data, since a command buffer's arena chunks are made without a clear and each region zeroes /// what its data does not cover (`upload.rs`). pub new_buffer_bytes_cleared: u64, + /// New buffers' bytes the host cannot write (`Private` storage, a `Managed` buffer's device + /// copy, the device's neutral buffers) that a submission's first work set to zero with one + /// `vkCmdFillBuffer`, on a device without unified memory whose fills are not transfers, in + /// place of copies of the device's host-visible zeros, which such a device reads over the bus + /// (`texture/first_move.rs`); fills apart from `fills_recorded`. + pub new_buffer_zero_fills: u64, /// Copies between a shadowed texture's truth and its shadow that encoders planned /// (`shadow.rs`): copies in before a command, copies back after one or as the encoder ends, /// and the keeps and merges of a command that writes the bytes two ways or writes through a @@ -4452,6 +4473,11 @@ pub struct WorkCounts { /// the shadow and in the merge's scratch, where the device runs them faster so /// (`DriverFact::ShadowCopyInDispatchFaster`): the same bytes either way. pub shadow_copies_in_dispatched: u64, + /// Of the keeps of merged shadowed textures, those of a heap's tiled texture recorded right + /// after its copy in as one copy of the staging buffer that copy filled with the heap's + /// bytes, in place of a move of the shadow's texels back into Metal's tiles: the same bytes + /// either way (`shadow.rs`). + pub shadow_keeps_from_staging: u64, /// The copies in of shadows over host pages a consumer logs whose regions the log decided as /// their command buffer replayed (`dirty_pages.rs`). pub dirty_copies_in_gated: u64, @@ -4497,7 +4523,8 @@ pub struct WorkCounts { /// The merges of shadowed textures whose scratch was made zero, as their kernel reads bytes /// no copy writes (those between the texture's rows): a merge not cut to rows of whole words, /// through a copy or of rows that start or end inside a word. A cut merge's copies write - /// every byte its kernel reads, so its scratch is not zeroed. + /// every byte its kernel reads, as a heap's tiled texture's merge in place copies the + /// texture's bytes whole, so neither scratch is zeroed. pub shadow_merge_scratches_zeroed: u64, /// Copies of rows of bytes between two buffers (`row_copies.rs`): a blit between a buffer and /// a texture over a buffer or between two textures over buffers, and a buffer-texture copy's @@ -5284,6 +5311,7 @@ impl Device { fresh_page_buffers_made: counters.fresh_page_buffers_made.load(Ordering::Relaxed), fresh_page_bytes: counters.fresh_page_bytes.load(Ordering::Relaxed), new_buffer_bytes_cleared: counters.new_buffer_bytes_cleared.load(Ordering::Relaxed), + new_buffer_zero_fills: counters.new_buffer_zero_fills.load(Ordering::Relaxed), views_through_swizzle: counters.views_through_swizzle.load(Ordering::Relaxed), view_shadows: counters.view_shadows.load(Ordering::Relaxed), attachment_reads_through_copies: counters @@ -5394,6 +5422,7 @@ impl Device { shadow_copies_in_dispatched: counters .shadow_copies_in_dispatched .load(Ordering::Relaxed), + shadow_keeps_from_staging: counters.shadow_keeps_from_staging.load(Ordering::Relaxed), dirty_copies_in_gated: dirty.gated.load(Ordering::Relaxed), dirty_copies_in_whole: dirty.whole.load(Ordering::Relaxed), dirty_copies_in_skipped: dirty.skipped.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index fbc20b3ea..3f0d09abe 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -ec4e574d095677009982b987db53730ab11c8a790d5deb679386daf96e84cab8 +66af4c03a23d3493ebef736c0e06922f655221a99d1ccf4235cca567bc750115 diff --git a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs index 1c0a44b6b..2298baf32 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/first_use.rs @@ -39,6 +39,10 @@ //! (`commit_failed`, a failing submission check) still runs it: a later read is zero. Bytes a //! command buffer writes through a resource placed in a new heap, and through one aliasing it, //! stay: the heap's fill comes before its first command. +//! - **A large `Private` buffer reads zero through its first fill.** One past the device's zeros' +//! length, over memory a released buffer had filled, reads all zero; on a device without unified +//! memory whose fills are not transfers its zeros are one `vkCmdFillBuffer` +//! (`WorkCounts::new_buffer_zero_fills`), elsewhere copies of the device's zeros. //! - **A heap texture's `replace_region` waits for nothing**: its copy is staged for the device's //! next submission; a later command buffer reads the later of two calls' bytes, and `get_bytes` //! the staged bytes. A new heap texture's staged copy lands where that submission also carries @@ -1123,6 +1127,60 @@ fn a_new_resource_s_zeros_come_before_every_use_on_every_queue() { }); } +/// A new `Private` buffer larger than the device's zeros (`ZERO_BYTES`, 4 MiB), made where one +/// whose every byte was `0xa7` was just released (most likely its memory), reads all zero after +/// the submission that took its first work: zeroed by one `vkCmdFillBuffer` on a device without +/// unified memory whose fills are not transfers (`WorkCounts::new_buffer_zero_fills` counts +/// exactly one), by copies of the device's zeros elsewhere (it counts none). +#[test] +fn a_new_private_buffer_reads_zero_through_its_first_fill() { + on_device(|device| { + let name = device.name(); + let len = (5 << 20) + 48; + let queue = device.new_command_queue().unwrap(); + let dirty = device.new_buffer(len, ResourceOptions::private()).unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&dirty, 0..len, 0xa7).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None, "the dirty fill on {name}"); + let address = dirty.gpu_address(); + drop((command_buffer, dirty)); + let before = device.work_counts().new_buffer_zero_fills; + let made = device.new_buffer(len, ResourceOptions::private()).unwrap(); + let reused = made.gpu_address() == address; + let command_buffer = queue.command_buffer().unwrap(); + let out = buffer_out(&command_buffer, &made, len); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None, "on {name}"); + let filled = device.work_counts().new_buffer_zero_fills - before; + let properties = device.properties(); + let by_transfers = + (properties.driver_facts).contains(&DriverFact::FillCompiledPerCommandPool); + let fills = !properties.has_unified_memory && !by_transfers; + println!( + "FIRST-USE on {name}: a new {len}-byte Private buffer {} the released one's memory, \ + its zeros {}", + if reused { "took" } else { "did not take" }, + if fills { "a fill" } else { "copies" } + ); + let bytes = read_buffer(&out, 0, len).unwrap(); + let other = bytes.iter().filter(|&&b| b != 0).count(); + assert_eq!( + other, 0, + "bytes of a new Private buffer that read other than zero on {name}" + ); + assert_eq!( + filled, + u64::from(fills), + "fills of the new Private buffer's zeros on {name}" + ); + }); +} + /// The kind [`neutrals_and_sparse_textures_wait_for_no_gpu_work`] takes where the driver's first /// sparse resource waits for every queue's work. pub(super) const FIRST_SPARSE: [Degradation; 1] = [Degradation::FirstSparseResourceWait]; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs b/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs index 344785306..de4991f85 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/heap_layouts.rs @@ -541,7 +541,9 @@ fn a_texture_made_again_beside_dispatches_takes_its_moves_pool_back() { /// A dispatch writes a tiled texture's texel (0, 0) and four bytes of a buffer over the heap, /// those of element (1, 0) or ones between the elements, and both writes stay: every other byte -/// is the heap's (the module docs), merged once (`shadow-merge`). +/// is the heap's (the module docs), merged once (`shadow-merge`). Each keep, right after its copy +/// in, copies the heap's bytes that copy took (`WorkCounts::shadow_keeps_from_staging`): a keep +/// of other bytes would have the merge put the copy in's back over the buffer's write. #[test] fn a_command_writing_a_tiled_texture_two_ways_keeps_both_writes() { on_device(|device, messages| { @@ -580,6 +582,7 @@ fn a_command_writing_a_tiled_texture_two_ways_keeps_both_writes() { .unwrap() .size; let buffer = heap.new_buffer_at_offset(span, shared(), OFFSET).unwrap(); + let counted = device.work_counts(); let before = named(HEAP, 7); mapping.write(0, &before); let at = buffer_with(device, &(off as u32).to_le_bytes()).unwrap(); @@ -606,6 +609,9 @@ fn a_command_writing_a_tiled_texture_two_ways_keeps_both_writes() { differ.len(), differ.first() ); + let staged = + device.work_counts().shadow_keeps_from_staging - counted.shadow_keeps_from_staging; + assert_eq!(staged, 1, "{what}: keeps from the staging buffer"); made = true; drop((buffer, texture, heap)); drop(mapping); @@ -622,6 +628,90 @@ fn a_command_writing_a_tiled_texture_two_ways_keeps_both_writes() { }); } +/// A dispatch writes a tiled texture's texel (0, 0) in three command buffers one after another, +/// each over bytes the CPU wrote anew, and its 4 bytes of a buffer of its own: each write goes +/// back by a merge in place (the CPU writes the heap's bytes too), every other byte the CPU's. +/// Its keep and changed copy write the texture's bytes whole, so no merge zeroes its scratch: +/// each takes one an earlier merge kept, else a new one +/// (`WorkCounts::shadow_merge_scratches_zeroed`, `shadow_merge_scratches_reused`); and each keep +/// copies the bytes its copy in took (`WorkCounts::shadow_keeps_from_staging`). +#[test] +fn a_tiled_texture_s_merges_take_kept_scratches_unzeroed() { + on_device(|device, _| { + let queue = device.new_command_queue().unwrap(); + let ll = + Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/public/engine/tob_renders.ll"); + let library = device + .new_library_with_air(&llvm_assemble(&ll).unwrap()) + .unwrap(); + let function = library.new_function_with_name("tob_two_ways").unwrap(); + let kernel = device + .new_compute_pipeline_state_with_function(&function, &PipelineOptions::default()) + .unwrap(); + let plain = Plain { + format: PixelFormat::RGBA8Unorm, + unit: 4, + extent: [64, 64], + }; + let mapping = Mapping::anonymous(HEAP); + let Some(heap) = heap_over(device, &mapping) else { + return; + }; + let made = device.work_counts(); + let texture = heap + .new_texture_at_offset(&plain.descriptor(), OFFSET) + .unwrap(); + let counts = device.work_counts(); + assert_eq!( + layouts_counted(&made, &counts), + [1, 0, 0, 0], + "the texture lies in Metal's tiles" + ); + let aside = buffer_with(device, &[0u8; 16]).unwrap(); + let at = buffer_with(device, &0u32.to_le_bytes()).unwrap(); + for run_at in 0..3 { + let before = named(HEAP, 11 + run_at); + mapping.write(0, &before); + let command_buffer = queue.command_buffer().unwrap(); + let mut e = command_buffer.compute_command_encoder().unwrap(); + e.set_compute_pipeline_state(&kernel).unwrap(); + e.set_texture(Some(&texture), 0).unwrap(); + e.set_buffer(Some(&aside), 0, 0).unwrap(); + e.set_buffer(Some(&at), 0, 1).unwrap(); + e.dispatch_threads(Size::new(1, 1, 1), Size::new(1, 1, 1)) + .unwrap(); + e.end_encoding().unwrap(); + run(&command_buffer); + let mut want = before; + let first = OFFSET as usize; + want[first..first + 4].copy_from_slice(&[0xff, 0, 0, 0xff]); + let after = mapping.read(0..HEAP); + let differ: Vec = (0..HEAP).filter(|&i| after[i] != want[i]).collect(); + assert!( + differ.is_empty(), + "command buffer {run_at}: {} bytes differ, the first at {:?}", + differ.len(), + differ.first() + ); + } + assert_eq!(read_buffer(&aside, 0, 4).unwrap(), [0x5a, 0x5b, 0x5c, 0x5d]); + let after = device.work_counts(); + let merged = after.shadow_merge_dispatches_planned - counts.shadow_merge_dispatches_planned; + let zeroed = after.shadow_merge_scratches_zeroed - counts.shadow_merge_scratches_zeroed; + let reused = after.shadow_merge_scratches_reused - counts.shadow_merge_scratches_reused; + assert!( + merged >= 3, + "a merge in each command buffer: {merged} dispatches" + ); + assert_eq!(zeroed, 0, "merge scratches zeroed"); + let staged = after.shadow_keeps_from_staging - counts.shadow_keeps_from_staging; + assert_eq!(staged, 3, "keeps from the staging buffer"); + drop((texture, heap)); + drop(mapping); + eprintln!("HEAPLAYOUT tiled merges: {merged} dispatches, {reused} scratches reused"); + }); +} + /// A texture Metal keeps losslessly compressed (a colour one, a `Depth32Float_Stencil8` one and an /// `X32_Stencil8` one), each in a heap over host pages, is counted in its kind's field and /// `Device::degraded_objects`, and the first is announced in the call that made it, with its ID; diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 2dbf673ce..d4bfe1438 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 477; /// 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 = 1687; +pub const RUNTIME_VERSION: u32 = 1688; /// 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 da66a659f..194028e58 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2658,6 +2658,7 @@ field metal2vulkan-runtime::WorkCounts.mipmaps_filtered pub mipmaps_filtered: u6 field metal2vulkan-runtime::WorkCounts.missed_completion_wakes pub missed_completion_wakes: u64 field metal2vulkan-runtime::WorkCounts.modifier_feature_queries pub modifier_feature_queries: u64 field metal2vulkan-runtime::WorkCounts.new_buffer_bytes_cleared pub new_buffer_bytes_cleared: u64 +field metal2vulkan-runtime::WorkCounts.new_buffer_zero_fills pub new_buffer_zero_fills: u64 field metal2vulkan-runtime::WorkCounts.no_copy_lies_read pub no_copy_lies_read: u64 field metal2vulkan-runtime::WorkCounts.object_churn pub object_churn: super::churn_counts::ObjectChurn field metal2vulkan-runtime::WorkCounts.own_pixel_reads pub own_pixel_reads: u64 @@ -2766,6 +2767,7 @@ field metal2vulkan-runtime::WorkCounts.shadow_copies pub shadow_copies: u64 field metal2vulkan-runtime::WorkCounts.shadow_copies_back_dispatched pub shadow_copies_back_dispatched: u64 field metal2vulkan-runtime::WorkCounts.shadow_copies_in_dispatched pub shadow_copies_in_dispatched: u64 field metal2vulkan-runtime::WorkCounts.shadow_keeps pub shadow_keeps: super::churn_counts::ShadowKeeps +field metal2vulkan-runtime::WorkCounts.shadow_keeps_from_staging pub shadow_keeps_from_staging: u64 field metal2vulkan-runtime::WorkCounts.shadow_merge_copies_dispatched pub shadow_merge_copies_dispatched: u64 field metal2vulkan-runtime::WorkCounts.shadow_merge_dispatches_planned pub shadow_merge_dispatches_planned: u64 field metal2vulkan-runtime::WorkCounts.shadow_merge_kept_images_followed pub shadow_merge_kept_images_followed: u64 diff --git a/docs/API.md b/docs/API.md index b6394607b..c76533e01 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1282,7 +1282,9 @@ bound. scissors copies in only the texels inside them (`WorkCounts::shadow_texels_copied_in`). Over a buffer's bytes that another writer may write while a command buffer runs, the image is kept in a scratch buffer before the first command - that writes through it, and each copy back is a dispatch that merges only the words the commands + that writes through it (a one-sample colour texture in Metal's tiles, right after its copy in, by + a copy of the bytes that copy took: `WorkCounts::shadow_keeps_from_staging`), and each copy back + is a dispatch that merges only the words the commands changed, so that writer's writes to the texels they left stay, as on Metal: the CPU's, over a `Shared` or `Managed` buffer's bytes, host pages or the caller's `VkBuffer`, and another queue's commands', over an untracked buffer's. A tracked `Private` buffer's bytes have no such writer (the