diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index a18b36a94..64524b055 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -4472,11 +4472,17 @@ impl Buffer { /// Whether the buffer's own pages, of the runtime's memory, lie in device-local memory; `None` /// for a heap's buffer, whose bytes are its heap's. A buffer's pages are its for good. pub(super) fn own_pages_device_local(&self) -> Option { + (self.own_pages_flags()).map(|flags| flags.contains(vk::MemoryPropertyFlags::DEVICE_LOCAL)) + } + + /// The property flags of the memory type the buffer's own pages lie in; `None` for a heap's + /// buffer, whose bytes are its heap's. + pub(super) fn own_pages_flags(&self) -> Option { let s = self.s(); match &s.bytes { Bytes::Own(own) => own.with(ReadApart::Binding, |pages| { let memory = lock(&s.device.shared().memory); - Some(memory.is_device_local(&pages.memory.placement)) + Some(memory.flags_of(&pages.memory.placement)) }), Bytes::Heap(_) => None, } diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 392cfbb15..fc59da731 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -88,7 +88,7 @@ use super::shadow::{ }; use super::shadow_copy_in::CopyIn; use super::shadow_merge::{MergeLease, ShadowMerge}; -use super::shadow_splice::{self, HostWrite, MergeDrain, ShadowSplices, SplicePlan}; +use super::shadow_splice::{self, HostWrite, ShadowSplices, SplicePlan}; use super::shadow_standing::Unskipped; use super::sparse::encoder::SparseUpdate; use super::texture::decoded_twin::TwinWrite; @@ -2988,8 +2988,8 @@ impl EncoderCore { spliced.extend(self.splice(&mut run, copy, plan)); continue; } - if let Some(drain) = splices.then(|| copy.merge_drain()).flatten() { - spliced.extend(self.merge_on_host(&mut run, copy, drain)); + if let Some(saves) = splices.then(|| copy.merge_saves()).flatten() { + spliced.extend(self.merge_on_host(&mut run, copy, saves)); continue; } // A shadow takes the view a dispatch reads on a device that dispatches alone. @@ -3151,23 +3151,52 @@ impl EncoderCore { Some((HostWrite::Splice(splice.drain), written)) } - /// Record `copy`, a merge on the host whose CPU part is `drain` (`shadow_splice.rs`, - /// **Merges**), in `run`, as [`shadow_command`](Self::shadow_command) records any shadowed - /// texture's copy: the copy of the texels the commands left into its scratch's changed part. - /// The CPU's part, and the merge's write of its truth's bytes, where it recorded. + /// Record `copy`, a merge on the host whose host step reads `saves` bytes of a region of the + /// command buffer's arena (`shadow_splice.rs`, **Merges**; none where it merges every byte), in + /// `run`, as [`shadow_command`](Self::shadow_command) records any shadowed texture's copy: the + /// copy of the texels the commands left into its scratch's changed part, and, where its kernel + /// merges the rest, the copies of the host step's pieces and its dispatches. The CPU's part, + /// and the merge's write of its truth's bytes, where it recorded. Where the region cannot be + /// had, the command buffer fails, as a recording that fails does. fn merge_on_host( &mut self, run: &mut ShadowRun, copy: &ShadowCopy, - drain: MergeDrain, + saves: u64, ) -> Option<(HostWrite, Use)> { + let device = self.device().clone(); + let region = match saves { + 0 => None, + saves => { + let line = device.shared().in_place.line(); + let mut state = self.open.command_buffer.state(); + Some(shadow_splice::region( + &mut state.uploads, + &device, + saves, + line, + )) + } + }; + let region = match region.transpose() { + Ok(region) => region, + Err(error) => { + self.fail_command_buffer(recording_error(&device, error)); + return None; + } + }; + let saved = region + .as_ref() + .map(|region| (region.raw(), region.offset())); + let drain = copy.merge_drain(region)?; let uses = copy.uses(); let recorded = std::cell::Cell::new(false); let record = |device: &Vk, raw: vk::CommandBuffer| { // SAFETY: the encoder's command buffer is recording outside a render pass; its - // commands retain the shadowed texture (its image) and the merge (its scratch) until - // it completes, and every image rests in the `GENERAL` layout. - unsafe { copy.record_changed(device, raw) }; + // commands retain the shadowed texture (its image), the merge (its scratch) and its + // arena (the region) until it completes, and every image rests in the `GENERAL` + // layout. + unsafe { copy.record_on_host(device, raw, saved) }; recorded.set(true); }; self.shadow_command(run, (copy.stages(), &uses, true), record); diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 9253c66a5..08a1c451d 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -4313,10 +4313,10 @@ impl Memory { (pool.payload(index)?.pages.as_ref()).map(Arc::clone) } - /// Whether `placement` lies in device-local memory. - pub(super) fn is_device_local(&self, placement: &Placement) -> bool { - self.type_flags(placement.type_index) - .is_some_and(|flags| flags.contains(vk::MemoryPropertyFlags::DEVICE_LOCAL)) + /// The property flags of the memory type `placement` lies in (none where the device has no + /// such type). + pub(super) fn flags_of(&self, placement: &Placement) -> vk::MemoryPropertyFlags { + (self.type_flags(placement.type_index)).unwrap_or_default() } /// Return `placement`'s memory, freeing its block when it empties. diff --git a/crates/metal2vulkan-runtime/src/shadow.rs b/crates/metal2vulkan-runtime/src/shadow.rs index 8f917722b..651db70f4 100644 --- a/crates/metal2vulkan-runtime/src/shadow.rs +++ b/crates/metal2vulkan-runtime/src/shadow.rs @@ -290,6 +290,7 @@ use super::texture::heap_two_planes::{HeapPlaneCopies, TwoPlaneHeapLayout}; use super::texture::surface_pairs::PairsConversion; use super::texture::Texture; use super::tracker::{Access, Barrier, Use, UseRange}; +use super::upload::Upload; use super::values::StorageMode; use super::view_plan::{reinterpretation_refused, ViewRecord}; use super::ycbcr::{YCbCrConversion, YCbCrWriteBack}; @@ -1378,6 +1379,14 @@ impl ShadowCopies { Some((buffer, class)) } + /// Where its truth lies in host pages the CPU writes ([`host_truth`](Self::host_truth)), the + /// base its `VkBuffer`'s bytes lie at among the host's addresses: its byte `v` at `v + base` + /// (wrapping). `None` for any other truth, and pages the CPU does not map. + pub(super) fn pages_base(&self) -> Option { + let (buffer, _) = self.host_truth()?; + host_base(&buffer).map(|(_, base)| base) + } + /// Whether its merges in place go on the host (`shadow_splice.rs`, **Merges**): over host /// pages ([`host_truth`](Self::host_truth)) on a device whose check splices their copies back /// (`shadow_splice::splices`). @@ -2185,32 +2194,49 @@ impl ShadowCopy { } } - /// This merge's CPU part, where it merges on the host (`ShadowMerge::on_host`, - /// `shadow_splice.rs`): over its truth's pages as they lie now. `None` for any other copy, and - /// a buffer whose pages went. - pub(super) fn merge_drain(&self) -> Option { + /// Where this copy is a merge on the host (`ShadowMerge::saves`, `shadow_splice.rs`) over its + /// truth's pages as they lie now, the bytes of the arena's region its host step reads the + /// pieces' kept bytes from (0 where it merges every byte). `None` for any other copy, and a + /// buffer whose pages went. + pub(super) fn merge_saves(&self) -> Option { let Step::Merge(merge) = &self.step else { return None; }; - if !merge.on_host() { + let saves = merge.saves()?; + self.copies.pages_base().map(|_| saves) + } + + /// This merge's CPU part, where it merges on the host ([`merge_saves`](Self::merge_saves)): + /// over its truth's pages as they lie now, the pieces' kept bytes in `region` where its kernel + /// merges the rest. `None` for any other copy, a buffer whose pages went, and a merge whose + /// kernel merges the rest given no region. + pub(super) fn merge_drain(&self, region: Option) -> Option { + let Step::Merge(merge) = &self.step else { return None; - } + }; let (buffer, _) = self.copies.host_truth()?; let (_, base) = host_base(&buffer)?; - merge.drain(buffer, base) + merge.drain(buffer, base, region) } /// Record the GPU's part of this merge on the host ([`merge_drain`](Self::merge_drain)): the - /// copy of the texels the commands left into its changed part. + /// copy of the texels the commands left into its changed part, and, where its kernel merges + /// all but its host step's pieces, `saved` their region's `VkBuffer` and offset, the copies of + /// their bytes and its dispatches (`ShadowMerge::record_on_host`). /// /// # Safety /// - /// As [`record`](Self::record). - pub(super) unsafe fn record_changed(&self, device: &Vk, command_buffer: vk::CommandBuffer) { + /// As [`record`](Self::record); the region lives until the command buffer completes. + pub(super) unsafe fn record_on_host( + &self, + device: &Vk, + command_buffer: vk::CommandBuffer, + saved: Option<(vk::Buffer, u64)>, + ) { if let Step::Merge(merge) = &self.step { let moves = self.moves.as_deref(); // SAFETY: the caller's contract, which the merge's record takes. - unsafe { merge.record_changed(device, command_buffer, (&self.copies, moves)) }; + unsafe { merge.record_on_host(device, command_buffer, (&self.copies, moves), saved) }; } } diff --git a/crates/metal2vulkan-runtime/src/shadow_merge.rs b/crates/metal2vulkan-runtime/src/shadow_merge.rs index 6a241a9c0..b44be046f 100644 --- a/crates/metal2vulkan-runtime/src/shadow_merge.rs +++ b/crates/metal2vulkan-runtime/src/shadow_merge.rs @@ -121,12 +121,16 @@ //! another writer may write meanwhile (`WorkCounts::shadow_merge_dispatches_in_blocks`). //! - **On the host** (`shadow_splice.rs`, **Merges**): a merge in place into a no-copy buffer's //! host pages, on a device whose stores write back the lines of memory they end in whole (or -//! whose check has not answered), keeps no image and fetches nothing: its keep and its copy of -//! the texels the commands left go into its two parts in a `Shared` scratch (its pool's -//! `ScratchKind::ShadowHost`, its shadow's spares that the CPU maps), and where the encoder's -//! own copies record it, a host step after them compares the parts and stores each byte that -//! differs ([`ShadowMerge::drain`], `WorkCounts::shadow_merges_on_host`). Its kernel's sets are -//! made as for any merge in place, for the places that record it (between a pass's instances). +//! whose check has not answered), where a line that holds bytes of its rows also holds a byte +//! beside the texture's texels (`shadow_splice::beside_texels`; else it merges as anywhere), +//! keeps no image and fetches nothing: its keep and its copy of the texels the commands left go +//! into its two parts in a `Shared` scratch (its pool's `ScratchKind::ShadowHost`, its shadow's +//! spares that the CPU maps). Where the encoder's own copies record it, its kernel merges the +//! rows' bytes in the other lines, storing changed words alone (`ShadowMergeStores::Words`), and +//! a host step after them compares and stores the rest ([`ShadowMerge::record_on_host`], +//! [`ShadowMerge::drain`], `WorkCounts::shadow_merges_on_host`); every byte, for a merge not +//! cut. Its kernel's sets are made as for any merge in place, for the places that record it +//! whole (between a pass's instances). //! - **The kernel** (`bind::shadow_merge_module`, one per device and form, `owned_kernel.rs`): four //! 4-byte words an invocation, each a workgroup's invocations apart from the next, so one //! store's words are consecutive across the invocations that run together (its module docs, @@ -161,10 +165,11 @@ use super::resource::ResourceKey; use super::shadow::{ShadowCopies, ShadowSource, ShadowTarget}; use super::shadow_copy_back::{self, CopyBack, WordView}; use super::shadow_copy_in::CopyIn; -use super::shadow_splice::MergeDrain; +use super::shadow_splice::{self, MergeDrain, Rows}; use super::texture::heap_tiled::SampleMoves; use super::texture::kept_image::{KeptImage, KeptImages, KeptLease, TakenImage}; use super::tracker::{Access, Barrier, ImagePlace, Use, UseRange}; +use super::upload::Upload; use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode}; use super::Device; use crate::device::functions::Vk; @@ -412,12 +417,19 @@ pub(super) struct ShadowMerge { } /// What a merge on the host compares and stores: the host addresses of its kept and changed -/// parts, of a `Shared` scratch, and each row it reaches: where the row lies in the buffer's -/// `VkBuffer`, its byte of each part, and its bytes. +/// parts, of a `Shared` scratch, and each piece: where it lies in the buffer's `VkBuffer`, its byte +/// of each part, and its bytes. struct HostMerge { kept: u64, changed: u64, - rows: Vec<(u64, u64, u64)>, + /// Each row the merge reaches, where the host step merges every byte; else the pieces of its + /// rows in lines beside its texels (`shadow_splice::beside_texels`), its kernel merging the + /// rest. + pieces: Vec<(u64, u64, u64)>, + /// Where its kernel merges the rest, the bytes the pieces' kept bytes take, back to back, in + /// the region of the arena the GPU copies them into before it + /// ([`ShadowMerge::record_on_host`]); `None` where the host step merges every byte. + saved: Option, } impl ShadowMerge { @@ -487,7 +499,15 @@ impl ShadowMerge { // A merge in place into host pages on a device whose stores write back the lines they // end in goes on the host, its parts in a `Shared` scratch (`shadow_splice.rs`, // **Merges**): kept in no image, and the texels the commands left copied, never fetched. - let host = in_place && copies.merges_on_host(device); + // Cut to its texels' rows, its host step takes the pieces of them in lines that also hold + // bytes beside the texels (`pieces`), and its kernel the rest; one with no such piece goes + // by its kernel alone, as anywhere, and one not cut goes on the host whole. + let on_host = in_place && copies.merges_on_host(device); + let cut = in_place.then(|| cut_of(copies, area)).flatten(); + let pieces = (on_host) + .then(|| (cut.as_ref()).and_then(|(_, geometry)| beside(device, copies, geometry))) + .flatten(); + let host = on_host && pieces.as_ref().is_none_or(|pieces| !pieces.is_empty()); let limits = &device.properties().description.limits; let range = u64::from(limits.max_storage_buffer_range); let [groups, groups_y] = @@ -497,20 +517,21 @@ impl ShadowMerge { // fetches the texels after the commands through the shadow's unsigned-integer view, or // its own 8-bit unsigned normalized view, where it has one (`fetch_view`), and the // rectangle lies within the kernel's origin and workgroups. - let cut = in_place - .then(|| cut_of(copies, area)) - .flatten() - .and_then(|(cut, geometry)| { - let view = (!host) - .then(|| fetch_view(copies)) - .flatten() - .filter(|&(_, read)| fetches(&cut, read, groups, groups_y)); - let rows = match view { - Some(_) => groups_y, - None => groups * GROUP_BYTES / geometry.row_bytes, - }; - Some((cut, geometry, geometry.band(range, rows)?, view)) - }); + let cut = cut.and_then(|(cut, geometry)| { + let view = (!host) + .then(|| fetch_view(copies)) + .flatten() + .filter(|&(_, read)| fetches(&cut, read, groups, groups_y)); + let rows = match view { + Some(_) => groups_y, + None => groups * GROUP_BYTES / geometry.row_bytes, + }; + Some((cut, geometry, geometry.band(range, rows)?, view)) + }); + // A cut that takes no band merges every byte of the texture's: on the host whole where the + // merge goes there. + let host = host || (on_host && cut.is_none()); + let pieces = pieces.filter(|_| host && cut.is_some()); let part = match &cut { Some((_, geometry, ..)) => geometry.rows * geometry.row_bytes, None => rounded, @@ -661,22 +682,27 @@ impl ShadowMerge { Some([held.first(), held.get(1)].map(|b| b.and_then(|b| mapped(b, 0)))) } }; - // Each row it reaches: the cut rectangle's, row after row in the parts, else every byte - // of the texture's, laid out as in the buffer. - let rows = match &cut { - Some((_, geometry, ..)) => (0..geometry.rows) + // What the host step merges: the pieces of a cut's rows beside its texels, their kept bytes + // copied back to back into a region (`saved` of them), else each row the merge reaches, + // the cut rectangle's, row after row in the parts, or every byte of the texture's, laid + // out as in the buffer. + let saved = (pieces.as_ref()).map(|pieces| pieces.iter().map(|&(.., bytes)| bytes).sum()); + let pieces = match (pieces, &cut) { + (Some(pieces), _) => pieces, + (None, Some((_, geometry, ..))) => (0..geometry.rows) .map(|r| { let at = geometry.first + r * geometry.pitch; (at, r * geometry.row_bytes, geometry.row_bytes) }) .collect(), - None => vec![(first, 0, span)], + (None, None) => vec![(first, 0, span)], }; let host = match host { Some([Some(kept), Some(changed)]) => Some(HostMerge { kept, changed, - rows, + pieces, + saved, }), Some(_) => { return Err(internal( @@ -874,8 +900,11 @@ impl ShadowMerge { } // Whole blocks where every word the dispatches examine is bytes the command wrote or // Metal's own store rewrites: a command's that replaces every texel, or a render pass's - // that stores the tiles of its area, cut to the texels' rows (the module docs). - let stores = match blocks && !two_ways && cut.is_some() { + // that stores the tiles of its area, cut to the texels' rows (the module docs); but where + // the host step stores the pieces beside the texels, whose lines a block's store holding + // one would write back from the GPU. + let split = (host.as_ref()).is_some_and(|host| host.saved.is_some()); + let stores = match blocks && !two_ways && cut.is_some() && !split { true => ShadowMergeStores::Blocks, false => ShadowMergeStores::Words, }; @@ -1071,37 +1100,130 @@ impl ShadowMerge { self.texels } - /// Whether it merges on the host (`shadow_splice.rs`, **Merges**). - pub(super) fn on_host(&self) -> bool { - self.host.is_some() + /// Where it merges on the host (`shadow_splice.rs`, **Merges**), the bytes of the arena's + /// region its host step reads the pieces' kept bytes from: 0 where the host step merges every + /// byte; `None` where it merges by its kernel. + pub(super) fn saves(&self) -> Option { + (self.host.as_ref()).map(|host| host.saved.unwrap_or(0)) } /// The CPU's part of this merge on the host, into the pages of `buffer`, whose `VkBuffer`'s - /// byte `v` lies at the host address `v + base`: each row the merge reaches (the cut - /// rectangle's, row after row in the parts, else every byte of the texture's, laid out as in - /// the buffer), compared and stored by the host step. `None` where it merges by its kernel. - pub(super) fn drain(self: &Arc, buffer: Buffer, base: u64) -> Option { + /// byte `v` lies at the host address `v + base`: each piece the host step compares and stores + /// (each row the merge reaches, the cut rectangle's, row after row in the parts, else every + /// byte of the texture's, laid out as in the buffer; or, where its kernel merges the rest, the + /// pieces beside its texels, whose kept bytes the GPU copies into `region`, + /// [`record_on_host`](Self::record_on_host)). `None` where it merges by its kernel, or where + /// its kernel merges the rest and `region` is none or unmapped. + pub(super) fn drain( + self: &Arc, + buffer: Buffer, + base: u64, + region: Option, + ) -> Option { let host = self.host.as_ref()?; - let rows = (host.rows.iter()) - .map(|&(at, part, bytes)| (at.wrapping_add(base), part, bytes)) + let kept = match (host.saved, ®ion) { + (None, _) => host.kept, + (Some(_), Some(region)) => { + let (chunk, at) = region.buffer(); + chunk.mapped_contents()?.as_ptr().addr() as u64 + at + } + (Some(_), None) => return None, + }; + let mut into = 0; + let pieces = (host.pieces.iter()) + .map(|&(at, part, bytes)| { + let kept = match host.saved { + Some(_) => { + into += bytes; + into - bytes + } + None => part, + }; + (at.wrapping_add(base), kept, part, bytes) + }) .collect(); Some(MergeDrain { _buffer: buffer, _merge: Arc::clone(self), - kept: host.kept, + _region: region, + kept, changed: host.changed, - rows, + pieces, }) } - /// Record the copy of the texels the commands left into the changed part, the GPU's part of - /// a merge on the host (the copy [`record_merge`](Self::record_merge) records first): the - /// host step reads it once its batch completed, which ends with the barrier to the host. + /// Record the GPU's part of a merge on the host (`shadow_splice.rs`, **Merges**): the copy of + /// the texels the commands left into the changed part; and, where its kernel merges all but + /// the pieces its host step takes, `saved` the arena's region the host step reads their kept + /// bytes from ([`saves`](Self::saves) of them, its `VkBuffer` and offset), the copy of those + /// kept bytes there, then, after a barrier, of their changed bytes over them in the kept part, + /// so that its dispatches, after another, find them unchanged and store none of them, and a + /// barrier to everything after. The host step reads the parts and the region once its batch + /// completed, which ends with the barrier to the host. + /// + /// # Safety + /// + /// As `record_merge`; the region lives until the command buffer completes (its arena's). + pub(super) unsafe fn record_on_host( + &self, + device: &Vk, + command_buffer: vk::CommandBuffer, + (copies, moves): (&ShadowCopies, Option<&SampleMoves>), + saved: Option<(vk::Buffer, u64)>, + ) { + // SAFETY: the caller's contract. + unsafe { self.record_changed(device, command_buffer, (copies, moves)) }; + let ( + Some(HostMerge { + pieces, + saved: Some(_), + .. + }), + Some((region, at)), + KeptIn::Part(kept), + Changed::Copied { part: changed, .. }, + ) = (&self.host, saved, self.kept_in, &self.changed) + else { + return; + }; + let mut into = at; + let saves: Vec = (pieces.iter()) + .map(|&(_, part, size)| { + into += size; + vk::BufferCopy { + src_offset: kept.at + part, + dst_offset: into - size, + size, + } + }) + .collect(); + let masks: Vec = (pieces.iter()) + .map(|&(_, part, size)| vk::BufferCopy { + src_offset: changed.at + part, + dst_offset: kept.at + part, + size, + }) + .collect(); + // SAFETY: the caller's contract; the pieces lie in the parts' rows, and back to back in + // the region, which holds `saves` bytes; the copies over the kept part read the changed + // part's bytes, apart from them. + unsafe { + device.cmd_copy_buffer(command_buffer, kept.raw, region, &saves); + Barrier::everything().record(device, command_buffer); + device.cmd_copy_buffer(command_buffer, changed.raw, kept.raw, &masks); + Barrier::everything().record(device, command_buffer); + self.record_dispatches(device, command_buffer); + Barrier::everything().record(device, command_buffer); + } + } + + /// Record the copy of the texels the commands left into the changed part (the copy + /// [`record_merge`](Self::record_merge) records first, and a merge on the host's). /// /// # Safety /// /// As `record_merge`. - pub(super) unsafe fn record_changed( + unsafe fn record_changed( &self, device: &Vk, command_buffer: vk::CommandBuffer, @@ -1239,13 +1361,35 @@ impl ShadowMerge { Changed::Copied { ref dispatch, .. } => dispatch.is_some(), Changed::Fetched => true, }; - let kept_read = match self.kept_in { - KeptIn::Part(_) => vk::AccessFlags2::SHADER_STORAGE_READ, - KeptIn::Image { .. } => vk::AccessFlags2::SHADER_SAMPLED_READ, + // A merge whose host step takes the pieces beside the texels also copies their kept bytes + // out of the kept part and their changed bytes over them (`record_on_host`). + let kept = match (self.kept_in, self.saves()) { + (KeptIn::Part(_), Some(saves)) if saves > 0 => Use { + key, + tracked, + range, + read: Access::new( + vk::PipelineStageFlags2::COPY | vk::PipelineStageFlags2::COMPUTE_SHADER, + vk::AccessFlags2::TRANSFER_READ | vk::AccessFlags2::SHADER_STORAGE_READ, + ), + write: transfer(vk::AccessFlags2::TRANSFER_WRITE), + }, + (KeptIn::Part(_), _) => Use::reads( + key, + tracked, + range, + storage(vk::AccessFlags2::SHADER_STORAGE_READ), + ), + (KeptIn::Image { .. }, _) => Use::reads( + key, + tracked, + range, + storage(vk::AccessFlags2::SHADER_SAMPLED_READ), + ), }; vec![ ShadowMerge::shadow_read(copies, dispatched), - Use::reads(key, tracked, range, storage(kept_read)), + kept, Use { key: self.merged.key, tracked: copies.tracked, @@ -1317,20 +1461,9 @@ impl ShadowMerge { ) { let Merged { ref bytes, .. } = self.merged; let span = bytes.end - bytes.start; - // SAFETY: the caller's contract; each part holds the texture's bytes, and the sets bind - // windows inside the parts and, in place, inside the texture's bytes (and the shadow's - // view, where the merge fetches its texels). + // SAFETY: the caller's contract; each part holds the texture's bytes. unsafe { - match &self.changed { - Changed::Copied { - dispatch: Some(out), - .. - } => out.record(device, command_buffer), - Changed::Copied { part, .. } => { - self.record_out(device, command_buffer, (copies, moves), *part); - } - Changed::Fetched => {} - } + self.record_changed(device, command_buffer, (copies, moves)); if let Some(current) = self.current { for (bytes, copy) in self.merged.current_copies(current, span) { device.cmd_copy_buffer(command_buffer, bytes, current.raw, &[copy]); @@ -1340,6 +1473,32 @@ impl ShadowMerge { if copied { Barrier::everything().record(device, command_buffer); } + self.record_dispatches(device, command_buffer); + // To everything after: the copy back, the next keep into the same scratch, and the + // bytes' next use. + Barrier::everything().record(device, command_buffer); + if let Some(current) = self.current { + for (bytes, copy) in self.merged.current_copies(current, span) { + let back = vk::BufferCopy { + src_offset: copy.dst_offset, + dst_offset: copy.src_offset, + size: copy.size, + }; + device.cmd_copy_buffer(command_buffer, current.raw, bytes, &[back]); + } + } + } + } + + /// Record the merge's dispatches, its kernel bound, one a window. + /// + /// # Safety + /// + /// As `record_merge`, after the barrier from the copies into its parts. + unsafe fn record_dispatches(&self, device: &Vk, command_buffer: vk::CommandBuffer) { + // SAFETY: the caller's contract; the sets bind windows inside the parts and, in place, + // inside the texture's bytes (and the shadow's view, where the merge fetches its texels). + unsafe { device.cmd_bind_pipeline( command_buffer, vk::PipelineBindPoint::COMPUTE, @@ -1357,19 +1516,6 @@ impl ShadowMerge { ); device.cmd_dispatch(command_buffer, groups[0], groups[1], 1); } - // To everything after: the copy back, the next keep into the same scratch, and the - // bytes' next use. - Barrier::everything().record(device, command_buffer); - if let Some(current) = self.current { - for (bytes, copy) in self.merged.current_copies(current, span) { - let back = vk::BufferCopy { - src_offset: copy.dst_offset, - dst_offset: copy.src_offset, - size: copy.size, - }; - device.cmd_copy_buffer(command_buffer, current.raw, bytes, &[back]); - } - } } } } @@ -1481,6 +1627,52 @@ fn kept_extent(copies: &ShadowCopies) -> Option<[u32; 2]> { } } +/// The pieces of the rows of `geometry`, a cut of the shadow of `copies`, its merge's host step +/// stores on `device` (`shadow_splice::beside_texels`): beside its texture's rows, over its truth's +/// pages as they lie now, in the device's lines (`nonCoherentAtomSize`); `None` where its texture +/// is not one region's rows, or its pages are not mapped. +fn beside( + device: &Device, + copies: &ShadowCopies, + geometry: &Geometry, +) -> Option> { + let ShadowSource::Bytes { + target: + ShadowTarget::Image { + regions, + texel: Some(texel), + .. + }, + .. + } = &copies.source + else { + return None; + }; + let [region] = regions.as_slice() else { + return None; + }; + let extent = region.image_extent; + let row = match region.buffer_row_length { + 0 => extent.width, + row => row, + }; + let texture = Rows { + first: region.buffer_offset, + bytes: u64::from(extent.width) * texel, + pitch: u64::from(row) * texel, + rows: u64::from(extent.height), + }; + let cut = Rows { + first: geometry.first, + bytes: geometry.row_bytes, + pitch: geometry.pitch, + rows: geometry.rows, + }; + let base = copies.pages_base()?; + let line = device.shared().in_place.line(); + Some(shadow_splice::beside_texels(texture, cut, base, line)) +} + /// Whether `bind::shadow_merge_image_module` takes the rectangle of `cut`: its first texel's /// coordinates and its last row's below 65536 (the shape's origin), and its row's workgroups /// within `groups` (`maxComputeWorkGroupCount[0]`); its rows go in bands of at most diff --git a/crates/metal2vulkan-runtime/src/shadow_splice.rs b/crates/metal2vulkan-runtime/src/shadow_splice.rs index 3677f4445..08bd81484 100644 --- a/crates/metal2vulkan-runtime/src/shadow_splice.rs +++ b/crates/metal2vulkan-runtime/src/shadow_splice.rs @@ -35,12 +35,23 @@ //! step, so the commands after it order after them; and the work after it goes in a later batch, //! which the step precedes. //! -//! **Merges** ([`MergeDrain`]). A merge stores the words its commands changed (`shadow_merge.rs`): -//! a GPU store into a line writes it back whole, the bytes the commands left in it, which the CPU -//! may write meanwhile, among them, wherever the rows end. So over such pages, on such a device, a -//! merge in place goes on the host: its keep and its copy of the texels the commands left go -//! into a `Shared` scratch, as two parts, and the host step compares them, eight bytes at a -//! time, storing each byte that differs into the pages (`WorkCounts::shadow_merges_on_host`). +//! **Merges** ([`MergeDrain`], [`beside_texels`]). A merge stores the words its commands changed +//! (`shadow_merge.rs`): a GPU store into a line writes it back whole, the bytes the commands left +//! in it, which the CPU may write meanwhile, among them. So over such pages, on such a device, a +//! merge in place goes on the host, split as a copy back is: its keep and its copy of the texels +//! the commands left go into a `Shared` scratch, as two parts; the host step merges each row's +//! bytes in the lines that also hold bytes of no row of the texture's (those between its rows, +//! before its first and past its last, the bytes the probe above measured Metal keeping), and its +//! kernel the rest, whose lines hold its texels alone. Before the kernel the GPU copies those +//! pieces' kept bytes into a region of the command buffer's arena, then their changed bytes over +//! them in the kept part, so the kernel finds them unchanged and stores none of them; the host step +//! compares the region's bytes with the changed part's and stores those that differ +//! ([`store_differing`]). A merge none of whose rows' lines holds a byte beside its texels goes by +//! its kernel alone, as anywhere; one not cut to its texels' rows (`shadow_merge.rs`, **Cut**) +//! goes on the host whole (`WorkCounts::shadow_merges_on_host`, `shadow_merge_bytes_on_host`). A +//! CPU write to a texel the commands left, in a line whose other bytes they changed, while the +//! command buffer runs, may still be put back by the kernel's store (docs/FAST-PATHS.md, known +//! gaps): no probe measured whether Metal keeps it. //! //! **Where the copy stays.** A copy back or merge between a render pass's instances or before its //! tile dispatch (`render/pass_steps.rs`), into a pass's held command buffer @@ -61,7 +72,7 @@ use super::shadow_merge::ShadowMerge; use super::upload::{Upload, Uploads}; use super::Device; use ash::vk; -use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicU8, Ordering}; use std::sync::Arc; use std::time::Instant; @@ -117,6 +128,124 @@ fn boundaries(phase: u64, bytes: u64, line: u64) -> (u64, u64) { (first, last) } +/// A texture's rows, or a rectangle of them, as a merge reaches them in its buffer's `VkBuffer`: +/// where the first row's first byte lies, the bytes of each row and their pitch (`bytes` at most +/// `pitch`), and the rows. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Rows { + pub(crate) first: u64, + pub(crate) bytes: u64, + pub(crate) pitch: u64, + pub(crate) rows: u64, +} + +impl Rows { + /// Whether every byte of `[from, to)` lies in one of the rows. + fn hold(&self, from: u64, to: u64) -> bool { + let mut at = from; + while at < to { + let Some(past) = at.checked_sub(self.first) else { + return false; + }; + let (row, x) = (past / self.pitch, past % self.pitch); + if row >= self.rows || x >= self.bytes { + return false; + } + at = self.first + row * self.pitch + self.bytes; + } + true + } +} + +/// The pieces of the rows of `cut`, a rectangle of `texture`'s rows, a merge's host step stores +/// (the module docs' **Merges**): each row's bytes in a line of `line` bytes (from a multiple of +/// it at the host address `v + base` of the `VkBuffer`'s byte `v`, wrapping) that holds a byte of +/// none of `texture`'s rows. Only a row's first and last lines can: every line between them holds +/// its bytes alone. Each piece: where it starts in the `VkBuffer`, its byte of the rectangle's rows +/// laid back to back (a merge's parts), and its bytes. +pub(crate) fn beside_texels( + texture: Rows, + cut: Rows, + base: u64, + line: u64, +) -> Vec<(u64, u64, u64)> { + let phase = |at: u64| at.wrapping_add(base) % line; + // Whether the line byte `at` lies in holds a byte of no row: one that starts before the + // `VkBuffer`'s first byte does. + let beside = |at: u64| match at.checked_sub(phase(at)) { + Some(from) => !texture.hold(from, from + line), + None => true, + }; + let mut pieces = Vec::new(); + for row in 0..cut.rows { + let start = cut.first + row * cut.pitch; + let end = start + cut.bytes; + let mut take = + |from: u64, to: u64| pieces.push((from, row * cut.bytes + from - start, to - from)); + // The row's bytes in its first line, then, where it runs past that line, in its last. + let first_end = (start + (line - phase(start))).min(end); + if beside(start) { + take(start, first_end); + } + if end > first_end && beside(end - 1) { + take(end - 1 - phase(end - 1), end); + } + } + pieces +} + +/// Store into the bytes at `host` each byte of `changed` that differs from the same byte of +/// `kept` (the module docs' **Merges**). Each word of 4 bytes at a multiple of 4 that lies among +/// them, where any of its bytes differs, takes one 4-byte store: of `changed`'s word where every +/// byte differs, else of the word as it holds it now with those bytes `changed`'s, as the merge's +/// kernel stores one (`bind::ShadowMergeStores::Words`), a race with another writer's store to its +/// other bytes meanwhile that the merge does not order. The bytes before the first such word and +/// past the last are stored one by one, those that differ alone. +/// +/// # Safety +/// +/// `host` is valid for writes of `changed.len()` bytes, which another thread may write meanwhile +/// with atomic stores of their own; `kept` is as long as `changed`. +pub(crate) unsafe fn store_differing(host: *mut u8, kept: &[u8], changed: &[u8]) { + let bytes = |at: *mut u8, kept: &[u8], changed: &[u8]| { + for (k, (kept, changed)) in kept.iter().zip(changed).enumerate() { + if kept != changed { + // SAFETY: the byte lies among the caller's; another thread may store to it + // meanwhile, so the store is an atomic byte's. + let byte = unsafe { AtomicU8::from_ptr(at.add(k)) }; + byte.store(*changed, Ordering::Relaxed); + } + } + }; + let lead = (host.addr().wrapping_neg() % 4).min(changed.len()); + bytes(host, &kept[..lead], &changed[..lead]); + let (kept_words, kept_past) = kept[lead..].as_chunks::<4>(); + let (changed_words, changed_past) = changed[lead..].as_chunks::<4>(); + // SAFETY: `lead` bytes from `host` lie among the caller's. + let words = unsafe { host.add(lead) }; + for (k, (kept, changed)) in kept_words.iter().zip(changed_words).enumerate() { + if kept == changed { + continue; + } + let differ = u32::from_ne_bytes(std::array::from_fn(|b| match kept[b] != changed[b] { + true => 0xff, + false => 0, + })); + let changed = u32::from_ne_bytes(*changed); + // SAFETY: the word's 4 bytes lie among the caller's, from a multiple of 4; another thread + // may store to them meanwhile, so it is an atomic word. + let word = unsafe { AtomicU32::from_ptr(words.add(4 * k).cast()) }; + let value = match differ { + u32::MAX => changed, + differ => (word.load(Ordering::Relaxed) & !differ) | (changed & differ), + }; + word.store(value, Ordering::Relaxed); + } + // SAFETY: as `words`, the whole words past it. + let past = unsafe { words.add(4 * kept_words.len()) }; + bytes(past, kept_past, changed_past); +} + /// A copy back cut for its splice: the GPU's copies `R` of whole lines into the buffer /// (`whole`) and of the rest into the region (`edges`, their offsets from its start), and the /// CPU's pieces: each one's host address, length and byte of the region. @@ -430,52 +559,53 @@ pub(super) struct SpliceDrain { } /// The CPU's part of a shadow's merge on the host (`shadow_merge.rs`, **On the host**): the -/// texels the commands left and those kept before them, in the merge's scratch, compared row by -/// row, and each byte that differs stored into the truth's pages. +/// texels the commands left, in the merge's scratch, and those kept before them, there or in the +/// region the GPU copied them into, compared piece by piece, and each byte that differs stored +/// into the truth's pages. pub(super) struct MergeDrain { /// Kept until the CPU's merge, whose command buffer keeps its pages until it completes. pub(super) _buffer: Buffer, /// The merge, which holds its scratch. pub(super) _merge: Arc, - /// The host addresses of the kept and the changed parts' first bytes. + /// The region of the command buffer's arena the GPU copied the pieces' kept bytes into, where + /// the merge's kernel merges the rest (the module docs' **Merges**): held until the step. + pub(super) _region: Option, + /// The host addresses of the kept bytes' first (the kept part's, or the region's) and the + /// changed part's. pub(super) kept: u64, pub(super) changed: u64, - /// Each row's host address in the pages, its byte of each part, and its bytes. - pub(super) rows: Vec<(u64, u64, u64)>, + /// Each piece's host address in the pages, its byte of the kept bytes and of the changed part, + /// and its bytes. + pub(super) pieces: Vec<(u64, u64, u64, u64)>, } impl MergeDrain { - /// Store each byte of each row whose changed part differs from its kept part, words of eight - /// compared first: the bytes it stores alone change, so the CPU's writes to every other byte - /// meanwhile stay. - fn run(&self) { - for &(host, at, length) in &self.rows { - let length = length as usize; - // SAFETY: both parts hold `length` bytes from `at` (the merge's scratch, a `Shared` - // buffer the merge holds, mapped while it lives), which the GPU's copies wrote before - // the batches this step follows completed, and which no command writes any more. + /// Store each byte of each piece whose changed byte differs from its kept one + /// ([`store_differing`]): the CPU's writes to every other byte of the pages meanwhile stay. + /// The bytes compared. + fn run(&self) -> u64 { + let mut compared = 0; + for &(host, kept, changed, length) in &self.pieces { + // SAFETY: both hold `length` bytes from there (the merge's scratch, a `Shared` buffer + // the merge holds, and the arena's region, mapped while they live), which the GPU's + // copies wrote before the batches this step follows completed, and which no command + // writes any more. let (kept, changed) = unsafe { ( - std::slice::from_raw_parts((self.kept + at) as *const u8, length), - std::slice::from_raw_parts((self.changed + at) as *const u8, length), + std::slice::from_raw_parts((self.kept + kept) as *const u8, length as usize), + std::slice::from_raw_parts( + (self.changed + changed) as *const u8, + length as usize, + ), ) }; - // The bytes of each word of eight that differs, then those past the last word. - let ((kept_words, _), (changed_words, _)) = - (kept.as_chunks::<8>(), changed.as_chunks::<8>()); - let candidates = (kept_words.iter().zip(changed_words).enumerate()) - .filter(|(_, (kept, changed))| kept != changed) - .flat_map(|(word, _)| word * 8..word * 8 + 8) - .chain(kept_words.len() * 8..length); - for k in candidates.filter(|&k| kept[k] != changed[k]) { - // SAFETY: the row's host bytes lie in the truth's pages, which stay mapped while - // the command buffer runs (its segment's uses name the buffer, whose pages it - // holds until it completes); another thread may write them meanwhile, so the - // store is an atomic byte's. - let byte = unsafe { AtomicU8::from_ptr((host + k as u64) as *mut u8) }; - byte.store(changed[k], Ordering::Relaxed); - } + // SAFETY: the piece's host bytes lie in the truth's pages, which stay mapped while the + // command buffer runs (its segment's uses name the buffer, whose pages it holds until + // it completes); another thread may write them meanwhile, with stores of its own. + unsafe { store_differing(host as *mut u8, kept, changed) }; + compared += length; } + compared } } @@ -499,7 +629,7 @@ impl ShadowSplices { /// nothing; the merges' time is counted on `device`. pub(super) fn drain(&self, device: &Device) -> RecordedSegment { let started = Instant::now(); - let mut merges = 0; + let (mut merges, mut compared) = (0, 0); for write in &self.0 { match write { HostWrite::Splice(drain) => { @@ -513,14 +643,14 @@ impl ShadowSplices { } } HostWrite::Merge(drain) => { - drain.run(); + compared += drain.run(); merges += 1; } } } if merges > 0 { let nanos = u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX); - device.shared().counts.shadow_merged_on_host(merges, nanos); + (device.shared().counts).shadow_merged_on_host(merges, nanos, compared); } RecordedSegment::submitted(Vec::new()) } diff --git a/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs b/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs index 7aeeb2d1c..aa615ef8e 100644 --- a/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs +++ b/crates/metal2vulkan-runtime/src/tests/shadow_runs.rs @@ -237,17 +237,25 @@ fn between_changed(bytes: &[u8]) -> usize { .count() } -/// Page-aligned host memory of `length` bytes, freed when dropped: declared before the device's -/// buffer over it, so dropped after it. -struct Host(NonNull, Layout); +/// Host memory of at least `length` bytes from `.2` bytes into a page, freed when dropped: +/// declared before the device's buffer over it, so dropped after it. +struct Host(NonNull, Layout, usize); impl Host { + /// Page-aligned. fn new(length: u64) -> Host { - let layout = - Layout::from_size_align(length.next_multiple_of(64 << 10) as usize, 64 << 10).unwrap(); + Host::into_page(length, 0) + } + + /// From `offset` bytes into a page. + fn into_page(length: u64, offset: usize) -> Host { + let size = (length as usize + offset).next_multiple_of(64 << 10); + let layout = Layout::from_size_align(size, 64 << 10).unwrap(); // SAFETY: the layout's size is not zero. let pointer = unsafe { std::alloc::alloc_zeroed(layout) }; - Host(NonNull::new(pointer).unwrap(), layout) + // SAFETY: `offset` bytes into the allocation, which is larger. + let at = unsafe { pointer.add(offset) }; + Host(NonNull::new(at).unwrap(), layout, offset) } /// Its pages, for a no-copy buffer or a rebind. @@ -261,14 +269,14 @@ impl Host { } fn length(&self) -> u64 { - self.1.size() as u64 + (self.1.size() - self.2) as u64 } } impl Drop for Host { fn drop(&mut self) { - // SAFETY: allocated with this layout in `new`. - unsafe { std::alloc::dealloc(self.0.as_ptr(), self.1) }; + // SAFETY: allocated with this layout in `into_page`, `.2` bytes before the pointer. + unsafe { std::alloc::dealloc(self.0.as_ptr().sub(self.2), self.1) }; } } @@ -783,20 +791,32 @@ fn rebound_passes_leave_their_runs() { } /// As [`rebound_passes_leave_their_runs`], on a device whose check of lines never answers -/// ([`shadow_device`]'s): each pass merges on the host (`shadow_splice.rs`), its CPU part a host -/// step after its encoder, resolved at its calls (`Deferred::resolved_at_its_calls`), so the -/// rebind is not refused but encodes the four passes again, each merging over the new pages; -/// the texels left are the private texture's as there. +/// ([`shadow_device`]'s), the texture's buffer over pages from [`INTO_PAGE`] bytes into one, so +/// each row's first and last lines hold bytes beside its texels: each pass merges on the host +/// (`shadow_splice.rs`), the CPU's part a host step after its encoder, resolved at its calls +/// (`Deferred::resolved_at_its_calls`), so the rebind is not refused but encodes the four passes +/// again, each merging over the new pages; the texels left are the private texture's as there. #[test] fn passes_merged_on_the_host_are_encoded_again_at_a_rebind() { rebound(false); } +/// Where the texture's pages start in their first page in +/// [`passes_merged_on_the_host_are_encoded_again_at_a_rebind`]: off a line of every device's +/// (`nonCoherentAtomSize`, at most 256 bytes), so every row starts and ends inside one. +const INTO_PAGE: usize = 16; + /// The sequence of [`rebound_passes_leave_their_runs`], on a device whose copies and shader /// writes keep the lines they end in where `kept` ([`device`]), its passes in runs; else on one -/// whose check never answers, each pass merged on the host. +/// whose check never answers, each pass merged on the host, over pages from [`INTO_PAGE`] bytes +/// into one. fn rebound(kept: bool) { - let (host, moved, moved_to) = (Host::new(ROW * H), Host::new(1 << 16), Host::new(1 << 16)); + let into = match kept { + true => 0, + false => INTO_PAGE, + }; + let host = Host::into_page(ROW * H, into); + let (moved, moved_to) = (Host::new(1 << 16), Host::new(1 << 16)); write_corners(&moved, BEFORE); write_corners(&moved_to, MOVED); let cache = Scratch::new("shadow-runs-rebound"); @@ -868,6 +888,19 @@ fn rebound(kept: bool) { on_host, REBOUND_PASSES as u64, "each pass merges on the host once" ); + // Each row's bytes in its first line and in its last, its kernel merging the rest: a + // line's in all, the row's start and end as far into their lines (its pitch and its bytes + // whole lines). + let line = device.shared().in_place.line(); + assert!( + line > INTO_PAGE as u64 && ROW.is_multiple_of(line), + "the device's line of {line} bytes" + ); + assert_eq!( + after.shadow_merge_bytes_on_host - before.shadow_merge_bytes_on_host, + REBOUND_PASSES as u64 * H * line, + "each pass's host step compares each row's bytes in its first and last lines alone" + ); assert!( encoded.encoders_reencoded - before.encoders_reencoded >= NAMING.len() as u64, "the rebind encodes the passes that bound the buffer again" diff --git a/crates/metal2vulkan-runtime/src/tests/shadow_splice.rs b/crates/metal2vulkan-runtime/src/tests/shadow_splice.rs index 81f4f5085..a672ac240 100644 --- a/crates/metal2vulkan-runtime/src/tests/shadow_splice.rs +++ b/crates/metal2vulkan-runtime/src/tests/shadow_splice.rs @@ -1,11 +1,13 @@ //! A copy back's cut for its splice (`shadow_splice.rs`): run as the GPU and the CPU would, over a //! map of host bytes, it leaves every texel's bytes in its place and no other byte written, and no //! copy the GPU makes into the buffer writes a byte whose line holds a byte outside its row's -//! texels. +//! texels. A merge's split: its host step's pieces are exactly the bytes of its rows in lines that +//! hold a byte of no row of the texture's, and the host step's loop stores the bytes that differ +//! alone. -use crate::shadow_splice::{image, staged, Cut}; +use crate::shadow_splice::{beside_texels, image, staged, store_differing, Cut, Rows}; use ash::vk; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; const LINE: u64 = 64; @@ -230,3 +232,117 @@ fn a_staged_cut_writes_each_byte_once_and_no_shared_line_from_the_gpu() { } } } + +/// The bytes of `cut`'s rows (a rectangle of `texture`'s) in lines of [`LINE`] bytes (from a +/// multiple of it at host address `v + base`) that hold a byte of no row of `texture`'s, found byte +/// by byte, each with its byte of the rectangle's rows laid back to back. +fn beside_by_bytes(texture: Rows, cut: Rows, base: u64) -> BTreeMap { + let texel = |v: i128| { + let past = v - i128::from(texture.first); + let pitch = i128::from(texture.pitch); + past >= 0 + && past / pitch < i128::from(texture.rows) + && past % pitch < i128::from(texture.bytes) + }; + let mut beside = BTreeMap::new(); + for row in 0..cut.rows { + let start = cut.first + row * cut.pitch; + for v in start..start + cut.bytes { + let line = i128::from(v) - i128::from(v.wrapping_add(base) % LINE); + if (line..line + i128::from(LINE)).any(|u| !texel(u)) { + beside.insert(v, row * cut.bytes + v - start); + } + } + } + beside +} + +#[test] +fn a_merge_s_host_pieces_are_its_rows_bytes_in_lines_beside_its_texels() { + let rows = |first, bytes, pitch, rows| Rows { + first, + bytes, + pitch, + rows, + }; + // The guest's 34x34 `RGBA16Float` render target, rows 512 bytes apart from a line: each row's + // last 16 bytes, which share a line with its padding. + let guest = rows(0, 272, 512, 34); + let pieces = beside_texels(guest, guest, 0x10_0000, LINE); + assert_eq!(pieces.len(), 34); + assert!((pieces.iter()) + .all(|&(at, part, bytes)| at % 512 == 256 && part % 272 == 256 && bytes == 16)); + // A 1920x1080 one whose rows lie on lines, and the rectangle a pass draws over its right half: + // no piece. + let wide = rows(0, 15360, 15360, 1080); + assert!(beside_texels(wide, wide, 0x10_0000, LINE).is_empty()); + assert!(beside_texels(wide, rows(7680, 7680, 15360, 1080), 0x10_0000, LINE).is_empty()); + // Each against the bytes found one by one, over phases of the pages and rectangles. + let shapes = [ + (guest, guest), + (guest, rows(136, 136, 512, 34)), + (guest, rows(512 * 3 + 40, 200, 512, 5)), + (rows(0, 4096, 15360, 6), rows(0, 4096, 15360, 6)), + (rows(0, 4096, 15360, 6), rows(15360 + 1000, 2000, 15360, 3)), + // Rows tight, shorter than a line: only the texture's first and last lines hold bytes + // beside its texels. + (rows(8, 16, 16, 10), rows(8, 16, 16, 10)), + (rows(8, 16, 16, 10), rows(40, 8, 16, 6)), + (rows(4, 60, 60, 9), rows(4, 60, 60, 9)), + (rows(0, 15360, 15360, 4), rows(0, 15360, 15360, 4)), + ]; + for (texture, cut) in shapes { + for base in [0, 4, 16, 40, 0x10_0000, 0u64.wrapping_sub(16)] { + let pieces = beside_texels(texture, cut, base, LINE); + let mut got = BTreeMap::new(); + for &(at, part, bytes) in &pieces { + for i in 0..bytes { + let twice = got.insert(at + i, part + i); + assert!( + twice.is_none(), + "{texture:?} {cut:?} at {base}: byte {} twice", + at + i + ); + } + } + assert_eq!( + got, + beside_by_bytes(texture, cut, base), + "{texture:?} {cut:?} at {base}" + ); + let firsts: BTreeSet = pieces.iter().map(|&(at, ..)| at).collect(); + assert_eq!(firsts.len(), pieces.len(), "{texture:?} {cut:?} at {base}"); + } + } +} + +#[test] +fn the_host_step_stores_the_bytes_that_differ_alone() { + let byte = |i: usize, seed: usize| ((i * 131 + seed * 17) % 251) as u8; + for length in [0, 1, 3, 4, 5, 8, 15, 64, 67, 300] { + for offset in 0..4 { + let kept: Vec = (0..length).map(|i| byte(i, 1)).collect(); + // Every third byte changed, and every 4-byte word of the first 16 bytes whole. + let changed: Vec = (kept.iter().enumerate()) + .map(|(i, &b)| match i % 3 == 0 || i < 16 { + true => b ^ 0xa5, + false => b, + }) + .collect(); + // What the CPU wrote meanwhile: every byte, and guards around them. + let mut host: Vec = (0..length + 8).map(|i| byte(i, 2)).collect(); + let before = host.clone(); + // SAFETY: `host` holds the bytes from `offset`, which no other thread uses. + unsafe { store_differing(host.as_mut_ptr().add(offset), &kept, &changed) }; + let want: Vec = (before.iter().enumerate()) + .map( + |(i, &b)| match i.checked_sub(offset).filter(|&k| k < length) { + Some(k) if kept[k] != changed[k] => changed[k], + _ => b, + }, + ) + .collect(); + assert_eq!(host, want, "{length} bytes from {offset}"); + } + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/shadow_write_lines.rs b/crates/metal2vulkan-runtime/src/tests/shadow_write_lines.rs index 93de14c5a..6521d03b7 100644 --- a/crates/metal2vulkan-runtime/src/tests/shadow_write_lines.rs +++ b/crates/metal2vulkan-runtime/src/tests/shadow_write_lines.rs @@ -27,7 +27,8 @@ //! copy back), which must lose none, its copies back spliced. //! - `draw`: a pass that loads it, draws a rectangle over its right half (its last column among //! it) in a color of the round's and stores it (a keep and a merge), which must lose none, its -//! merges on the host. +//! merges on the host: the host step stores each row's last 16 bytes of texels, in the line its +//! padding shares, and the merge's kernel the rest. //! - `idle`: the thread alone, which must find none. //! //! The device's policy runs no check of its own, so its verdicts stay unanswered: every copy back @@ -35,7 +36,8 @@ //! the verdicts the device's check measured under the default policy, and finds a copy back //! spliced, and a merge on the host, exactly where they splice: each as before where both the //! copies and the shader writes passed. A third prints what a write back costs each way, for the -//! shape and for a 1920x1080 one. +//! shape and for a 1920x1080 one, and what the host step's loop costs over a 1920x1080 texture's +//! bytes in plain heap memory and in memory of the host step's scratch's type. use super::blit_holds::{options, WAIT}; use super::encoder_holds::{bytes_of, library}; @@ -43,10 +45,13 @@ use super::host_residency::{host_page, udmabuf_openable, Ram, Scratch}; use super::merge_scratch::blit; use super::no_pointer_import::lists_dma_buf_route; use crate::in_place::{Access, PagesClass, RowEnds, Verdict}; +use crate::shadow_splice::store_differing; +use crate::submit_failure::flag_names; use crate::{ - BlitOption, Buffer, ClearColor, CommandQueue, Device, HostMemory, IoSurfacePlane, LoadAction, - Origin, PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size, - StoreAction, Texture, TextureDescriptor, WorkCounts, + BlitOption, Buffer, ClearColor, CommandQueue, CpuCacheMode, Device, HazardTrackingMode, + HostMemory, IoSurfacePlane, LoadAction, Origin, PipelineOptions, RenderPassDescriptor, + RenderPipelineState, ResourceOptions, Size, StorageMode, StoreAction, Texture, + TextureDescriptor, WorkCounts, }; use metal2vulkan::device::{HostPageTexturePolicy, VkExtension}; use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; @@ -257,13 +262,14 @@ fn beside(base: usize, work: impl FnOnce()) -> (Tally, Duration) { /// The counts a line names. fn counted(before: &WorkCounts, after: &WorkCounts) -> String { format!( - "shadow copies +{}, copies back spliced +{}, merges on the host +{} ({} us), copies back \ - dispatched +{}, merge dispatches planned +{}, merge copies dispatched +{}, merges \ - fetched +{}, merges kept in images +{}", + "shadow copies +{}, copies back spliced +{}, merges on the host +{} ({} us, {} bytes \ + compared), copies back dispatched +{}, merge dispatches planned +{}, merge copies \ + dispatched +{}, merges fetched +{}, merges kept in images +{}", after.shadow_copies - before.shadow_copies, spliced(before, after), on_host(before, after), (after.shadow_merge_host_nanos - before.shadow_merge_host_nanos) / 1000, + after.shadow_merge_bytes_on_host - before.shadow_merge_bytes_on_host, after.shadow_copies_back_dispatched - before.shadow_copies_back_dispatched, after.shadow_merge_dispatches_planned - before.shadow_merge_dispatches_planned, after.shadow_merge_copies_dispatched - before.shadow_merge_copies_dispatched, @@ -401,6 +407,17 @@ fn a_shadow_s_copy_back_keeps_the_cpu_s_writes_beside_its_texels() { "{TEST}: every {form} {what}: {}", counted(&before, &after) ); + // The draw's merges: each row's bytes in the line its padding shares, its last 16. + if let Kind::Draw = kind { + let compared = after.shadow_merge_bytes_on_host - before.shadow_merge_bytes_on_host; + assert_eq!( + compared, + made * HEIGHT * (ROW_BYTES % LINE), + "{TEST}: each {form} merge's host step compares each row's bytes beside its \ + padding alone: {}", + counted(&before, &after) + ); + } } } drop(buffer); @@ -480,11 +497,12 @@ fn a_copy_back_splices_by_the_device_s_check() { /// The cost of a write back, spliced and merged on the host or not: for the guest's shape and a /// 1920x1080 `RGBA16Float` IOSurface plane (rows 15360 bytes apart, each on a line, so its copy -/// back splices nothing), a pass that clears and stores it (a copy back) and one that loads it, -/// draws over its right half and stores it (a keep and a merge), each [`COST_ROUNDS`] command -/// buffers committed and waited for, the median of each's time from its commit to its -/// completion printed, with the verdicts unanswered (spliced, on the host) and then passed (as -/// before). Asserts each takes the form its verdicts say. +/// back splices nothing, and its merge goes by its kernel alone), a pass that clears and stores it +/// (a copy back) and one that loads it, draws over its right half and stores it (a keep and a +/// merge), each [`COST_ROUNDS`] command buffers committed and waited for, the median of each's +/// time from its commit to its completion printed, with the verdicts unanswered (spliced, on the +/// host) and then passed (as before). Asserts each takes the form its verdicts say. Then the host +/// step's loop ([`host_loop`]). #[test] fn costs_of_a_write_back_spliced_or_not() { if !udmabuf_openable(TEST) { @@ -534,13 +552,13 @@ fn costs_of_a_write_back_spliced_or_not() { took[took.len() / 2], counted(&before, &after) ); - let (made, edges) = match kind { - Kind::Clear => (spliced(&before, &after), row != 15360), - _ => (on_host(&before, &after), true), + let made = match kind { + Kind::Clear => spliced(&before, &after), + _ => on_host(&before, &after), }; assert_eq!( made > 0, - splices && edges, + splices && row != 15360, "{TEST}: {width}x{height} {kind:?} under {verdict:?}: {}", counted(&before, &after) ); @@ -550,4 +568,60 @@ fn costs_of_a_write_back_spliced_or_not() { drop(buffer); drop(ram); } + host_loop(&device); +} + +/// The host step's loop (`shadow_splice::store_differing`) over a 1920x1080 `RGBA16Float` +/// texture's bytes as the cost test's draw changes them (the right half's texels, their red and +/// blue), the median of five runs printed: from plain heap memory, and from a buffer made as a +/// merge on the host's scratch is (`Shared`, the default CPU cache mode), whose memory type's +/// flags it prints, each into heap memory. +fn host_loop(device: &Device) { + const LENGTH: usize = 1920 * 1080 * 8; + let kept: Vec = (0..LENGTH).map(|i| (i * 7 % 251) as u8).collect(); + let changed: Vec = (kept.iter().enumerate()) + .map(|(i, &byte)| match (i / 8 % 1920 >= 960, i % 8) { + (true, 0 | 1 | 4 | 5) => byte ^ 0x5a, + _ => byte, + }) + .collect(); + let median = |kept: &[u8], changed: &[u8]| { + let mut into = vec![0u8; LENGTH]; + let mut took: Vec = (0..5) + .map(|_| { + let start = Instant::now(); + // SAFETY: `into` holds the bytes, which no other thread uses. + unsafe { store_differing(into.as_mut_ptr(), kept, changed) }; + start.elapsed() + }) + .collect(); + took.sort(); + took[2] + }; + let heap = median(&kept, &changed); + let options = ResourceOptions::new( + StorageMode::Shared, + CpuCacheMode::DefaultCache, + HazardTrackingMode::Default, + ); + let (scratch, _) = (device.unzeroed_buffer_with(2 * LENGTH as u64, options)).unwrap(); + let at = scratch.mapped_contents().unwrap().as_ptr(); + // SAFETY: the buffer's `2 * LENGTH` bytes, mapped while it lives, which no command uses. + let (kept_part, changed_part) = unsafe { + std::ptr::copy_nonoverlapping(kept.as_ptr(), at, LENGTH); + std::ptr::copy_nonoverlapping(changed.as_ptr(), at.add(LENGTH), LENGTH); + ( + std::slice::from_raw_parts(at, LENGTH), + std::slice::from_raw_parts(at.add(LENGTH), LENGTH), + ) + }; + let mapped = median(kept_part, changed_part); + println!( + "{TEST} HOST-LOOP on {}: 1920x1080 RGBA16Float, half the texels' red and blue changed: \ + from heap memory {heap:?}, from the scratch's memory {mapped:?} (its type's flags {})", + device.name(), + scratch + .own_pages_flags() + .map_or("unknown".to_owned(), flag_names), + ); } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index eb85aa09a..b8ed4c236 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -709,6 +709,7 @@ pub(crate) struct Counters { shadow_copies_back_spliced: AtomicU64, shadow_merges_on_host: AtomicU64, shadow_merge_host_nanos: AtomicU64, + shadow_merge_bytes_on_host: AtomicU64, shadow_copies_in_dispatched: AtomicU64, shadow_keeps_from_staging: AtomicU64, shadow_merge_copies_dispatched: AtomicU64, @@ -5664,13 +5665,15 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } - /// A host step stored the bytes `merges` merges on the host changed, in `nanos` of its thread - /// (`shadow_splice.rs`). - pub(crate) fn shadow_merged_on_host(&self, merges: u64, nanos: u64) { + /// A host step stored the bytes `merges` merges on the host changed, comparing `bytes`, in + /// `nanos` of its thread (`shadow_splice.rs`). + pub(crate) fn shadow_merged_on_host(&self, merges: u64, nanos: u64, bytes: u64) { self.shadow_merges_on_host .fetch_add(merges, Ordering::Relaxed); self.shadow_merge_host_nanos .fetch_add(nanos, Ordering::Relaxed); + self.shadow_merge_bytes_on_host + .fetch_add(bytes, Ordering::Relaxed); } /// An encoder recorded a merged shadowed texture's copy in and keep as one dispatch @@ -11085,10 +11088,15 @@ pub struct WorkCounts { /// device whose check found its copies or shader writes of texels writing back a line of /// memory they end in whole, or has not answered (`shadow_splice.rs`): the GPU copies the /// texels the commands left into a `Shared` scratch beside those kept before them, and a host - /// step after it stores each byte that differs, so the CPU's writes to every other byte stay. + /// step after it stores each byte that differs of each row's bytes in the lines that also hold + /// bytes beside the texels (every byte, for a merge not cut to its texels' rows), so the CPU's + /// writes to those other bytes stay; the merge's kernel stores the rest. A merge none of whose + /// rows' lines holds a byte beside its texels goes by its kernel alone, and is not counted. pub shadow_merges_on_host: u64, /// The nanoseconds of the host steps that made those merges, on the thread that ran them. pub shadow_merge_host_nanos: u64, + /// The bytes those host steps compared. + pub shadow_merge_bytes_on_host: u64, /// Of the copies in among `shadow_copies`, those recorded with their texture's keep after /// them (one of `shadow_merge_copies_dispatched`) as one dispatch that stores the texels in /// the shadow and in the merge's scratch, where the device runs them faster so @@ -13447,6 +13455,7 @@ impl Device { shadow_copies_back_spliced: counters.shadow_copies_back_spliced.load(Ordering::Relaxed), shadow_merges_on_host: counters.shadow_merges_on_host.load(Ordering::Relaxed), shadow_merge_host_nanos: counters.shadow_merge_host_nanos.load(Ordering::Relaxed), + shadow_merge_bytes_on_host: counters.shadow_merge_bytes_on_host.load(Ordering::Relaxed), shadow_copies_in_dispatched: counters .shadow_copies_in_dispatched .load(Ordering::Relaxed), diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 07e3e105d..4170f0780 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 = 523; /// 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 = 2437; +pub const RUNTIME_VERSION: u32 = 2438; /// 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 b557fddd2..0e803c232 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3665,6 +3665,7 @@ field metal2vulkan-runtime::WorkCounts.shadow_copies_in_dispatched pub shadow_co field metal2vulkan-runtime::WorkCounts.shadow_copies_in_skipped_by_standing pub shadow_copies_in_skipped_by_standing: 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_bytes_on_host pub shadow_merge_bytes_on_host: u64 field metal2vulkan-runtime::WorkCounts.shadow_merge_copies_dispatched pub shadow_merge_copies_dispatched: u64 field metal2vulkan-runtime::WorkCounts.shadow_merge_dispatches_in_blocks pub shadow_merge_dispatches_in_blocks: u64 field metal2vulkan-runtime::WorkCounts.shadow_merge_dispatches_planned pub shadow_merge_dispatches_planned: u64 diff --git a/docs/API.md b/docs/API.md index b22514e9c..14abd7acb 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2511,10 +2511,14 @@ bound. device whose check of those pages finds its copies or shader writes writing such a line back whole, or has not answered, is spliced: the GPU copies the texels that fill whole lines, and a host step after the copies writes the rest, so a CPU write beside them stays - (`WorkCounts::shadow_copies_back_spliced`); and a merge in place there goes on the host: its - keep and the copy of the texels the commands left go into a `Shared` scratch, and a host step - after them stores each byte that differs (`WorkCounts::shadow_merges_on_host`; docs/FAST-PATHS.md, - **Known gaps**, the Iris Xe's line write-back). Where the device is measured to run it + (`WorkCounts::shadow_copies_back_spliced`); and a merge in place there splits the same way: its + keep and the copy of the texels the commands left go into a `Shared` scratch, its kernel stores + the changed words in the lines that hold the texture's texels alone, and a host step after them + stores each byte that differs of each row's bytes in the lines that also hold bytes beside them + (`WorkCounts::shadow_merges_on_host`, `shadow_merge_bytes_on_host`; a merge none of whose rows' + lines holds such a byte goes by its kernel alone; docs/FAST-PATHS.md, **Known gaps**, the Iris + Xe's line write-back, which may still put back a CPU write to a texel the commands left in a + line whose other bytes they changed). Where the device is measured to run it faster so (`DriverFact::ShadowCopyBackDispatchFaster`), a copy back of a one-slice texture of 4-, 8- or 16-byte texels is a compute dispatch that stores the same bytes (`WorkCounts::shadow_copies_back_dispatched`), and so is a merge's copy of such a texture's image diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 0f6c40e62..cdfcf83b1 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -913,11 +913,21 @@ driver's. Each is open work. lines back, or has not answered: the GPU copies only the texels that fill whole lines, and a host step after the copies writes each row's texels in the lines it shares, as the CPU's stores go (`shadow_splice.rs`, `WorkCounts::shadow_copies_back_spliced`); and a shadow's merge - in place there goes on the host: the GPU copies the texels the commands left into a `Shared` - scratch beside those kept before them, and a host step after it stores each byte that differs - (`WorkCounts::shadow_merges_on_host`, `shadow_merge_host_nanos`), where the merge's kernel - would store whole words into lines the commands left bytes in. Such a texture opens no run of - passes (`pass_runs.rs`). Still lost, by the same write-back: a CPU write beside a copy back or + in place there splits the same way: the GPU copies the texels the commands left into a + `Shared` scratch beside those kept before them, the merge's kernel stores the changed words in + the lines that hold the texture's texels alone, and a host step after it stores each byte that + differs of each row's bytes in the lines that also hold bytes beside them, the bytes between + the rows and around them (`WorkCounts::shadow_merges_on_host`, `shadow_merge_bytes_on_host`, + `shadow_merge_host_nanos`). A merge none of whose rows' lines holds such a byte goes by its + kernel alone, as on any device; one not cut to its texels' rows (`shadow_merge.rs`, **Cut**) + goes on the host whole. Such a texture opens no run of passes (`pass_runs.rs`). Metal's + contract for those bytes is measured: + `crates/metal2vulkan-conformance/probes/row_padding_writes.m` found an M3 Max, a Radeon Pro + 5300M and an Intel UHD 630 keeping every CPU write to the bytes between and around a texture's + rows under clears, stores and draws, and over IOSurfaces under kernels. No probe measured a CPU write to a texel the commands left, inside a line whose other + bytes they changed, while the command buffer runs: the merge's kernel stores into such a line, + so on the Iris Xe that write may be put back, and whether Metal keeps it is not known. Still + lost, by the same write-back: a CPU write beside a copy back or merge between a render pass's instances or before its tile dispatch, into a pass's held command buffer, at the end of a segment recorded at a commit or a host step, of a rotated texture's, a heap's two-plane, tiled, depth or stencil texture's, beside a merge through a copy