RUNTIME 2432: Shadows: merge on the host over host pages on devices that write lines back
What: a shadow's merge in place into a no-copy buffer's host pages, on a device whose check of those pages failed, or has not answered, the copies or the shader writes of texels whose rows end inside a line (the same rule as the copy back's splice), now goes on the host. Its keep and the copy of the texels the commands left go into two parts of a Shared scratch (ScratchKind::ShadowHost; the fetch view is not used, so the changed texels are always copied). The encoder records only that copy, and a host step of a batch of its own (Deferred::ShadowSplice, now carrying HostWrite::Splice or ::Merge) compares the parts eight bytes at a time and stores each byte that differs into the pages with atomic byte stores. Such a texture joins no run of passes (render.rs), so each pass merges as its encoder ends. Devices where both checks passed keep the kernel merge. Why: the Iris probe (m3-max-35510) showed the merge kernel's stores losing CPU writes to padding bytes in the line that holds each row's last texels, as the copy back did. A CPU store changes only the bytes it stores, so the bytes the commands left, and every byte the CPU writes meanwhile, stay. Metal keeps those bytes (conformance probe row_padding_writes.m). Where the merge stays on the GPU (FAST-PATHS known gaps): merges recorded between a pass's instances, before a tile dispatch, into a held command buffer, at a segment's end, merges through a copy, and the runtime's own Shared memory. New WorkCounts fields: shadow_merges_on_host, shadow_merge_host_nanos. Tests: shadow_write_lines now asserts the Draw rounds (keep + merge) put back no byte and go on the host under unanswered verdicts, and follow the measured verdicts in the second test. A new test, costs_of_a_write_back_spliced_or_not, prints the median command-buffer time of a copy back and a merge for 34x34 and 1920x1080 RGBA16Float, with verdicts unanswered and passed. Degradation kinds added: none. Verified (fplend): msi m3-max-35675 at bdb1e2cbae clippy (runtime, all targets/features, -D warnings) 0, touched unit tests 3/3, api_signatures + fast_paths 34/34; msi 35689 clippy --cfg m2v_gpu 0. PHOENIX suites (35711), lavapipe, rustdoc and the Iris cost run follow.
This commit is contained in:
1 parent
8ff90fd10c
commit
518d6d8443
14 files changed
+584
-149
No files matched your search
@@ -68,9 +68,10 @@ pub(super) enum Deferred {
|
||||
/// ([`StagedScatter::drain`]): the host step of a batch of its own records nothing, once the
|
||||
/// work before it completed.
|
||||
ScatterDrain(Arc<StagedScatter>),
|
||||
/// The CPU's part of an encoder's copies back spliced at one place (`shadow_splice.rs`,
|
||||
/// [`ShadowSplices::drain`]): its texels' bytes in lines the GPU's copies left, copied from
|
||||
/// the arena into the pages by the host step of a batch of its own, which records nothing,
|
||||
/// The CPU's part of an encoder's copies back spliced and merges on the host at one place
|
||||
/// (`shadow_splice.rs`, [`ShadowSplices::drain`]): its texels' bytes in lines the GPU's
|
||||
/// copies left, copied from the arena into the pages, and the bytes its merges' commands
|
||||
/// changed, stored there, by the host step of a batch of its own, which records nothing,
|
||||
/// once the work before it completed.
|
||||
ShadowSplice(Arc<ShadowSplices>),
|
||||
}
|
||||
@@ -668,7 +669,7 @@ impl Deferred {
|
||||
Deferred::GatherStage(gather) => gather.stage(command_buffer),
|
||||
Deferred::ScatterStage(scatter) => scatter.stage(command_buffer),
|
||||
Deferred::ScatterDrain(scatter) => scatter.drain(command_buffer.device()),
|
||||
Deferred::ShadowSplice(splices) => Ok(splices.drain()),
|
||||
Deferred::ShadowSplice(splices) => Ok(splices.drain(command_buffer.device())),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ use super::shadow::{
|
||||
};
|
||||
use super::shadow_copy_in::CopyIn;
|
||||
use super::shadow_merge::{MergeLease, ShadowMerge};
|
||||
use super::shadow_splice::{self, ShadowSplices, SpliceDrain, SplicePlan};
|
||||
use super::shadow_splice::{self, HostWrite, MergeDrain, ShadowSplices, SplicePlan};
|
||||
use super::shadow_standing::Unskipped;
|
||||
use super::sparse::encoder::SparseUpdate;
|
||||
use super::texture::decoded_twin::TwinWrite;
|
||||
@@ -2931,8 +2931,9 @@ impl EncoderCore {
|
||||
/// retains each until it completes. A copy back into host pages the CPU may write beside its
|
||||
/// texels, on a device whose stores write back the lines they end in, is spliced where a host
|
||||
/// step may follow, outside a pass the encoder holds: the GPU copies the texels that fill
|
||||
/// whole lines, and the host step after the copies the rest (`shadow_splice.rs`,
|
||||
/// [`drain_splices`](Self::drain_splices)).
|
||||
/// whole lines, and the host step after the copies the rest; and a merge there that goes on
|
||||
/// the host copies the texels the commands left into its scratch, whose changed bytes the
|
||||
/// host step stores (`shadow_splice.rs`, [`drain_splices`](Self::drain_splices)).
|
||||
pub(super) fn shadow_copies(&mut self, copies: &[ShadowCopy]) {
|
||||
let device = self.device().clone();
|
||||
let mut run = ShadowRun::default();
|
||||
@@ -2940,7 +2941,8 @@ impl EncoderCore {
|
||||
// the staging buffer their copy in filled.
|
||||
let mut taken = Vec::new();
|
||||
let mut staged = Vec::new();
|
||||
// The CPU's parts of the copies back spliced, with their writes of their truths' bytes.
|
||||
// The CPU's parts of the copies back spliced and of the merges on the host, with their
|
||||
// writes of their truths' bytes.
|
||||
let mut spliced = Vec::new();
|
||||
let splices = self.splices_apart && self.pass.is_none();
|
||||
for (i, copy) in copies.iter().enumerate() {
|
||||
@@ -2983,6 +2985,10 @@ 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));
|
||||
continue;
|
||||
}
|
||||
// A shadow takes the view a dispatch reads on a device that dispatches alone.
|
||||
let dispatched = copy.dispatched(&device);
|
||||
let rows = match dispatched {
|
||||
@@ -3110,7 +3116,7 @@ impl EncoderCore {
|
||||
run: &mut ShadowRun,
|
||||
copy: &ShadowCopy,
|
||||
plan: SplicePlan,
|
||||
) -> Option<(SpliceDrain, Use<ResourceKey>)> {
|
||||
) -> Option<(HostWrite, Use<ResourceKey>)> {
|
||||
let device = self.device().clone();
|
||||
let line = device.shared().in_place.line();
|
||||
let region = {
|
||||
@@ -3139,21 +3145,48 @@ impl EncoderCore {
|
||||
}
|
||||
device.shared().counts.shadow_copy_back_spliced();
|
||||
let written = uses.into_iter().find(|used| !used.write.is_empty())?;
|
||||
Some((splice.drain, written))
|
||||
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.
|
||||
fn merge_on_host(
|
||||
&mut self,
|
||||
run: &mut ShadowRun,
|
||||
copy: &ShadowCopy,
|
||||
drain: MergeDrain,
|
||||
) -> Option<(HostWrite, Use<ResourceKey>)> {
|
||||
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) };
|
||||
recorded.set(true);
|
||||
};
|
||||
self.shadow_command(run, (copy.stages(), &uses, true), record);
|
||||
if !recorded.get() {
|
||||
return None;
|
||||
}
|
||||
let written = uses.into_iter().find(|used| !used.write.is_empty())?;
|
||||
Some((HostWrite::Merge(drain), written))
|
||||
}
|
||||
|
||||
/// Leave the CPU's parts of the copies back [`shadow_copies`](Self::shadow_copies) just
|
||||
/// spliced, `spliced` with each one's write of its truth's bytes, to the host step of a batch
|
||||
/// of their own, once the work before them completed (`Deferred::ShadowSplice`), and note
|
||||
/// those writes there: the encoder goes on in a new `VkCommandBuffer` after it, so its later
|
||||
/// commands, and every later batch, run after the CPU's copies. Where the step cannot be
|
||||
/// left, the command buffer fails, as a recording that fails does.
|
||||
fn drain_splices(&mut self, spliced: Vec<(SpliceDrain, Use<ResourceKey>)>) {
|
||||
/// spliced and of its merges on the host, `spliced` with each one's write of its truth's
|
||||
/// bytes, to the host step of a batch of their own, once the work before them completed
|
||||
/// (`Deferred::ShadowSplice`), and note those writes there: the encoder goes on in a new
|
||||
/// `VkCommandBuffer` after it, so its later commands, and every later batch, run after the
|
||||
/// CPU's copies. Where the step cannot be left, the command buffer fails, as a recording that
|
||||
/// fails does.
|
||||
fn drain_splices(&mut self, spliced: Vec<(HostWrite, Use<ResourceKey>)>) {
|
||||
if spliced.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (drains, writes): (Vec<SpliceDrain>, Vec<Use<ResourceKey>>) =
|
||||
spliced.into_iter().unzip();
|
||||
let (drains, writes): (Vec<HostWrite>, Vec<Use<ResourceKey>>) = spliced.into_iter().unzip();
|
||||
let work = Deferred::ShadowSplice(Arc::new(ShadowSplices(drains)));
|
||||
if let Err(error) = self.defer(work) {
|
||||
let device = self.device().clone();
|
||||
|
||||
@@ -68,11 +68,13 @@ use super::shadow_merge::ScratchSpares;
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
/// The kinds of scratch, apart: a linear attachment's merge takes an untracked buffer
|
||||
/// (`Device::scratch_buffer`), a shadow's a tracked one, whose uses the tracker orders.
|
||||
/// (`Device::scratch_buffer`), a shadow's a tracked one, whose uses the tracker orders, `Private`,
|
||||
/// or `Shared` for a merge on the host, whose parts the CPU reads (`shadow_splice.rs`).
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub(super) enum ScratchKind {
|
||||
Linear,
|
||||
Shadow,
|
||||
ShadowHost,
|
||||
}
|
||||
|
||||
impl ScratchKind {
|
||||
@@ -80,6 +82,7 @@ impl ScratchKind {
|
||||
match self {
|
||||
ScratchKind::Linear => 0,
|
||||
ScratchKind::Shadow => 1,
|
||||
ScratchKind::ShadowHost => 2,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -136,7 +139,7 @@ struct Pool {
|
||||
/// scratch whose merges all went is gone, and its entry with it at the next take.
|
||||
free: Vec<(Weak<Scratch>, ScratchKind, u64)>,
|
||||
/// The largest scratch of each kind made for the command buffer's merges.
|
||||
largest: [u64; 2],
|
||||
largest: [u64; 3],
|
||||
}
|
||||
|
||||
impl MergeScratch {
|
||||
|
||||
@@ -39,6 +39,9 @@
|
||||
//! it opens the run, its image carried with no copy in, keeping it again, as nothing may write
|
||||
//! the bytes between a run's keep and its merge but that merge (a byte its passes changed and
|
||||
//! changed back keeps the bytes' value, below).
|
||||
//! A shadowed texture whose merges go on the host (`shadow_splice.rs`, **Merges**) opens no
|
||||
//! run: each of its passes merges as its encoder ends, the merge's CPU part following that
|
||||
//! encoder's commands.
|
||||
//! - **Why the bytes are Metal's.** Within the run, nothing reads the attachment's bytes or
|
||||
//! writes them another way (below): between two of its passes the bytes are what the first
|
||||
//! copy in read (or what the work before the run left), and the image holds them, as Metal's
|
||||
|
||||
@@ -5531,6 +5531,7 @@ impl RenderLowering {
|
||||
&& instances.len() == 1
|
||||
&& image
|
||||
&& copies.merges_back()
|
||||
&& !copies.merges_on_host(&device)
|
||||
&& c.load == LoadAction::Load
|
||||
&& stored(c)
|
||||
&& c.stand_in.is_none()
|
||||
|
||||
@@ -270,6 +270,7 @@ use super::buffer::{Buffer, CallerMemory, WeakBuffer};
|
||||
use super::dirty_pages::{CopyInGate, ShadowLog};
|
||||
use super::error::{Error, RuntimeGap};
|
||||
use super::image_plan::{ImageFacts, ImagePlan};
|
||||
use super::in_place::PagesClass;
|
||||
use super::mipmap::record_blit;
|
||||
use super::mipmap_filter::{filter_chain, FilterRun};
|
||||
use super::mipmap_pick::{picks_fit, PickRun};
|
||||
@@ -280,7 +281,7 @@ use super::rotated::{RotatedCopies, Turn};
|
||||
use super::row_copies::RowCopies;
|
||||
use super::shadow_copy_back::{CopyBack, WordView};
|
||||
use super::shadow_merge::{ScratchSpares, ShadowMerge, UnormView};
|
||||
use super::shadow_splice::{self, PlannedCut, Splice, SpliceCopies, SplicePlan};
|
||||
use super::shadow_splice::{self, MergeDrain, PlannedCut, Splice, SpliceCopies, SplicePlan};
|
||||
use super::shadow_standing::{Missed, StandingAcross};
|
||||
use super::texture::copy_images::UseMaker;
|
||||
use super::texture::decoded_twin::DecodePass;
|
||||
@@ -1361,6 +1362,30 @@ impl ShadowCopies {
|
||||
keys
|
||||
}
|
||||
|
||||
/// The no-copy buffer over host pages its truth lies in, and their class, where the CPU writes
|
||||
/// them while a command buffer runs (`shadow_splice::class`): not a copy of them. `None` for
|
||||
/// any other truth, and a buffer that went.
|
||||
pub(super) fn host_truth(&self) -> Option<(Buffer, PagesClass)> {
|
||||
let ShadowSource::Bytes {
|
||||
buffer: ShadowBuffer::Rebound(buffer),
|
||||
..
|
||||
} = &self.source
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let buffer = buffer.upgrade()?;
|
||||
let class = shadow_splice::class(&buffer)?;
|
||||
Some((buffer, class))
|
||||
}
|
||||
|
||||
/// 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`).
|
||||
pub(super) fn merges_on_host(&self, device: &Device) -> bool {
|
||||
let checks = &device.shared().in_place;
|
||||
(self.host_truth()).is_some_and(|(_, class)| shadow_splice::splices(checks, class))
|
||||
}
|
||||
|
||||
/// Whether what the commands write through the shadow goes back into its truth as a merge
|
||||
/// (`shadow_merge.rs`): a buffer's bytes that another writer may write beside the commands'
|
||||
/// writes while a command buffer runs, whose writes to texels the commands left Metal keeps;
|
||||
@@ -2029,28 +2054,17 @@ impl ShadowCopy {
|
||||
/// device whose check splices those pages' copies back ([`shadow_splice::splices`]). `None`
|
||||
/// for any other copy, one that moves no texel, and a buffer whose pages went.
|
||||
pub(super) fn splice_plan(&self, device: &Device) -> Option<SplicePlan> {
|
||||
let (
|
||||
Step::Back,
|
||||
None,
|
||||
ShadowSource::Bytes {
|
||||
buffer: ShadowBuffer::Rebound(buffer),
|
||||
target,
|
||||
..
|
||||
},
|
||||
) = (&self.step, &self.clear, &self.copies.source)
|
||||
let (Step::Back, None, ShadowSource::Bytes { target, .. }) =
|
||||
(&self.step, &self.clear, &self.copies.source)
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let buffer = buffer.upgrade()?;
|
||||
let class = shadow_splice::class(&buffer)?;
|
||||
let (buffer, class) = self.copies.host_truth()?;
|
||||
let checks = &device.shared().in_place;
|
||||
if !shadow_splice::splices(checks, class) {
|
||||
return None;
|
||||
}
|
||||
let contents = buffer.mapped_contents()?.as_ptr().addr() as u64;
|
||||
let (truth, at) = buffer.attached_at(0)?;
|
||||
// The `VkBuffer`'s byte `v` lies at the host address `v + base`.
|
||||
let base = contents.wrapping_sub(at);
|
||||
let (truth, base) = host_base(&buffer)?;
|
||||
let line = checks.line();
|
||||
let cut = match target {
|
||||
ShadowTarget::Image {
|
||||
@@ -2171,6 +2185,35 @@ 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<MergeDrain> {
|
||||
let Step::Merge(merge) = &self.step else {
|
||||
return None;
|
||||
};
|
||||
if !merge.on_host() {
|
||||
return None;
|
||||
}
|
||||
let (buffer, _) = self.copies.host_truth()?;
|
||||
let (_, base) = host_base(&buffer)?;
|
||||
merge.drain(buffer, base)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// As [`record`](Self::record).
|
||||
pub(super) unsafe fn record_changed(&self, device: &Vk, command_buffer: vk::CommandBuffer) {
|
||||
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)) };
|
||||
}
|
||||
}
|
||||
|
||||
/// The texels a copy in of a one-region, one-slice 2D texture's image over a buffer's bytes
|
||||
/// copied in place moves, as `record` cuts its region (where they lie in the buffer, and in
|
||||
/// the image): what a merge's keep may take with it (`ShadowMerge::keep_in`). `None` for any
|
||||
@@ -2843,6 +2886,14 @@ impl ShadowCopy {
|
||||
}
|
||||
}
|
||||
|
||||
/// `buffer`'s `VkBuffer` now, and the base its byte `v` lies at the host address `v + base` of
|
||||
/// (wrapping): `None` where the CPU maps it not, or it lies in no pages.
|
||||
fn host_base(buffer: &Buffer) -> Option<(vk::Buffer, u64)> {
|
||||
let contents = buffer.mapped_contents()?.as_ptr().addr() as u64;
|
||||
let (raw, at) = buffer.attached_at(0)?;
|
||||
Some((raw, contents.wrapping_sub(at)))
|
||||
}
|
||||
|
||||
/// The `VkBuffer` bytes `regions` copy, `texel` bytes a texel, from the first region's first byte
|
||||
/// to the last row's end; `None` for none, or a region of depth.
|
||||
fn copied_bytes(regions: &[vk::BufferImageCopy], texel: u64) -> Option<Range<u64>> {
|
||||
|
||||
@@ -119,6 +119,14 @@
|
||||
//! stored with the value the merge reads, Metal's answer. Every other merge stores the changed
|
||||
//! words alone (`ShadowMergeStores::Words`): its rows may hold bytes no command wrote, which
|
||||
//! 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).
|
||||
//! - **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,
|
||||
@@ -153,10 +161,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::texture::heap_tiled::SampleMoves;
|
||||
use super::texture::kept_image::{KeptImage, KeptImages, KeptLease, TakenImage};
|
||||
use super::tracker::{Access, Barrier, ImagePlace, Use, UseRange};
|
||||
use super::values::{HazardTrackingMode, ResourceOptions};
|
||||
use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode};
|
||||
use super::Device;
|
||||
use crate::device::functions::Vk;
|
||||
use ash::vk;
|
||||
@@ -185,11 +194,13 @@ const KEPT_SCRATCHES: usize = 2;
|
||||
pub(super) struct ScratchSpares(Arc<Mutex<Vec<Buffer>>>);
|
||||
|
||||
impl ScratchSpares {
|
||||
/// The smallest kept buffer of at least `length` bytes, taken.
|
||||
fn take(&self, length: u64) -> Option<Buffer> {
|
||||
/// The smallest kept buffer of at least `length` bytes, the CPU mapping it where `host` (a
|
||||
/// merge on the host's) and not elsewhere, taken.
|
||||
fn take(&self, length: u64, host: bool) -> Option<Buffer> {
|
||||
let spares = &mut *lock(&self.0);
|
||||
let at = (spares.iter().enumerate())
|
||||
.filter(|(_, buffer)| buffer.length() >= length)
|
||||
.filter(|(_, buffer)| buffer.mapped_contents().is_some() == host)
|
||||
.min_by_key(|(_, buffer)| buffer.length())
|
||||
.map(|(at, _)| at)?;
|
||||
Some(spares.swap_remove(at))
|
||||
@@ -395,6 +406,18 @@ pub(super) struct ShadowMerge {
|
||||
binds: OwnedBinds,
|
||||
/// Each window's workgroups (along x and y) and push bytes.
|
||||
dispatches: Vec<([u32; 2], [u8; 16])>,
|
||||
/// Where it merges on the host (`shadow_splice.rs`, **Merges**), what the host step reads and
|
||||
/// writes; `None` where its kernel merges.
|
||||
host: Option<HostMerge>,
|
||||
}
|
||||
|
||||
/// 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.
|
||||
struct HostMerge {
|
||||
kept: u64,
|
||||
changed: u64,
|
||||
rows: Vec<(u64, u64, u64)>,
|
||||
}
|
||||
|
||||
impl ShadowMerge {
|
||||
@@ -461,6 +484,10 @@ impl ShadowMerge {
|
||||
&& first.is_multiple_of(4)
|
||||
&& first + rounded <= buffer.end()
|
||||
&& merged.buffer != vk::Buffer::null();
|
||||
// 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);
|
||||
let limits = &device.properties().description.limits;
|
||||
let range = u64::from(limits.max_storage_buffer_range);
|
||||
let [groups, groups_y] =
|
||||
@@ -474,8 +501,10 @@ impl ShadowMerge {
|
||||
.then(|| cut_of(copies, area))
|
||||
.flatten()
|
||||
.and_then(|(cut, geometry)| {
|
||||
let view =
|
||||
(fetch_view(copies)).filter(|&(_, read)| fetches(&cut, read, groups, groups_y));
|
||||
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,
|
||||
@@ -513,7 +542,18 @@ impl ShadowMerge {
|
||||
(true, None, _) => 2,
|
||||
(false, ..) => 3,
|
||||
};
|
||||
let options = ResourceOptions::private();
|
||||
let options = match host {
|
||||
true => ResourceOptions::new(
|
||||
StorageMode::Shared,
|
||||
CpuCacheMode::DefaultCache,
|
||||
HazardTrackingMode::Default,
|
||||
),
|
||||
false => ResourceOptions::private(),
|
||||
};
|
||||
let kind = match host {
|
||||
true => ScratchKind::ShadowHost,
|
||||
false => ScratchKind::Shadow,
|
||||
};
|
||||
let place = |buffer: &Buffer, at: u64| {
|
||||
let (raw, at) = buffer.at(at);
|
||||
Part { raw, at }
|
||||
@@ -560,16 +600,10 @@ impl ShadowMerge {
|
||||
let written = cut.is_some() || (in_place && copies.copies_out_whole(rounded));
|
||||
let spares = copies.merge_scratch.clone();
|
||||
let whole = roles * rounded.next_multiple_of(PART_ALIGNMENT);
|
||||
let pooled = lent
|
||||
.then(|| pool.take(ScratchKind::Shadow, length))
|
||||
.flatten();
|
||||
let pooled = lent.then(|| pool.take(kind, length)).flatten();
|
||||
let lent = pooled.or_else(|| {
|
||||
let spare = spares.take(length)?;
|
||||
Some(Scratch::new(
|
||||
spare,
|
||||
ScratchKind::Shadow,
|
||||
Some(spares.clone()),
|
||||
))
|
||||
let spare = spares.take(length, host)?;
|
||||
Some(Scratch::new(spare, kind, Some(spares.clone())))
|
||||
});
|
||||
let one = match lent {
|
||||
Some(lent) => {
|
||||
@@ -577,9 +611,12 @@ impl ShadowMerge {
|
||||
lent
|
||||
}
|
||||
None => {
|
||||
let length = pool.grown(ScratchKind::Shadow, length, whole);
|
||||
let made = device.unzeroed_buffer(length, HazardTrackingMode::Default)?;
|
||||
Scratch::new(made, ScratchKind::Shadow, Some(spares))
|
||||
let length = pool.grown(kind, length, whole);
|
||||
let made = match host {
|
||||
true => device.unzeroed_buffer_with(length, options)?.0,
|
||||
false => device.unzeroed_buffer(length, HazardTrackingMode::Default)?,
|
||||
};
|
||||
Scratch::new(made, kind, Some(spares))
|
||||
}
|
||||
};
|
||||
if !written {
|
||||
@@ -609,6 +646,45 @@ impl ShadowMerge {
|
||||
let placed = held.iter().map(|buffer| place(buffer, 0)).collect();
|
||||
(Held::Apart(held), placed)
|
||||
};
|
||||
// A merge on the host's parts as the CPU maps them: the kept part and the changed one,
|
||||
// each `part` bytes.
|
||||
let mapped = |buffer: &Buffer, at: u64| {
|
||||
(buffer.mapped_contents()).map(|contents| contents.as_ptr().addr() as u64 + at)
|
||||
};
|
||||
let host = match (host, &held) {
|
||||
(false, _) | (true, Held::Image(_)) => None,
|
||||
(true, Held::Spare(one)) => {
|
||||
let buffer = one.buffer();
|
||||
Some([mapped(buffer, 0), mapped(buffer, part)])
|
||||
}
|
||||
(true, Held::Apart(held)) => {
|
||||
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)
|
||||
.map(|r| {
|
||||
let at = geometry.first + r * geometry.pitch;
|
||||
(at, r * geometry.row_bytes, geometry.row_bytes)
|
||||
})
|
||||
.collect(),
|
||||
None => vec![(first, 0, span)],
|
||||
};
|
||||
let host = match host {
|
||||
Some([Some(kept), Some(changed)]) => Some(HostMerge {
|
||||
kept,
|
||||
changed,
|
||||
rows,
|
||||
}),
|
||||
Some(_) => {
|
||||
return Err(internal(
|
||||
"a merge on the host whose scratch the CPU maps not",
|
||||
))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let (kept_in, changed, current) = match (&held, &placed[..]) {
|
||||
(Held::Image(image), []) => {
|
||||
let (
|
||||
@@ -865,6 +941,7 @@ impl ShadowMerge {
|
||||
blocks,
|
||||
binds,
|
||||
dispatches,
|
||||
host,
|
||||
};
|
||||
Ok((merge, lease))
|
||||
}
|
||||
@@ -994,6 +1071,58 @@ 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()
|
||||
}
|
||||
|
||||
/// 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<Self>, buffer: Buffer, base: u64) -> Option<MergeDrain> {
|
||||
let host = self.host.as_ref()?;
|
||||
let rows = (host.rows.iter())
|
||||
.map(|&(at, part, bytes)| (at.wrapping_add(base), part, bytes))
|
||||
.collect();
|
||||
Some(MergeDrain {
|
||||
_buffer: buffer,
|
||||
_merge: Arc::clone(self),
|
||||
kept: host.kept,
|
||||
changed: host.changed,
|
||||
rows,
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// As `record_merge`.
|
||||
pub(super) unsafe fn record_changed(
|
||||
&self,
|
||||
device: &Vk,
|
||||
command_buffer: vk::CommandBuffer,
|
||||
(copies, moves): (&ShadowCopies, Option<&SampleMoves>),
|
||||
) {
|
||||
// SAFETY: the caller's contract; the changed part holds the texture's bytes, or the cut
|
||||
// rectangle's rows.
|
||||
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 => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the copy of the shadow of `copies` into `part`: the cut rectangle's texels, row after
|
||||
/// row, or every texel laid out as in the buffer from the texture's first byte.
|
||||
///
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! A shadowed texture's copy back into bytes the CPU may write beside its texels, spliced: the
|
||||
//! GPU writes only the lines of memory its texels fill, and the CPU writes the rest.
|
||||
//! GPU writes only the lines of memory its texels fill, and the CPU writes the rest; and its merge
|
||||
//! there, on the host: the CPU stores the bytes the commands changed.
|
||||
//!
|
||||
//! A device may write back a line of memory a store of its ends in whole (`in_place::RowEnds`: a
|
||||
//! line is `nonCoherentAtomSize` bytes at a multiple of it, "the size and alignment in bytes that
|
||||
@@ -27,28 +28,42 @@
|
||||
//! fall at the same columns), else one a row; the columns before the first boundary and after
|
||||
//! the last are copied by the GPU into a region of the command buffer's arena (`upload.rs`), its
|
||||
//! own lines whole ([`region`]), and from there by the CPU into the pages, by a host step of a
|
||||
//! batch of its own once that copy completed ([`ShadowSplices::drain`], `Deferred::ShadowSplice`),
|
||||
//! a byte at a time as the CPU's stores go: the CPU's own writes beside them stay. A row whose
|
||||
//! texels hold no whole line goes to the CPU whole. A texel the boundary cuts goes to the CPU
|
||||
//! with its row's edge. The encoder notes the CPU's writes of the truth's bytes after the step,
|
||||
//! so the commands after it order after them; and the work after it goes in a later batch, which
|
||||
//! the step precedes.
|
||||
//! batch of its own once that copy completed ([`ShadowSplices::drain`], `Deferred::ShadowSplice`):
|
||||
//! a store of the CPU changes the bytes it stores alone, so its own writes beside them stay. A
|
||||
//! row whose texels hold no whole line goes to the CPU whole. A texel the boundary cuts goes to
|
||||
//! the CPU with its row's edge. The encoder notes the CPU's writes of the truth's bytes after the
|
||||
//! step, so the commands after it order after them; and the work after it goes in a later batch,
|
||||
//! which the step precedes.
|
||||
//!
|
||||
//! **Where the copy stays.** A copy back between a render pass's instances or before its tile
|
||||
//! dispatch (`render/pass_steps.rs`), into a pass's held command buffer
|
||||
//! **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`).
|
||||
//!
|
||||
//! **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
|
||||
//! (`render/inline_splits.rs`), or at a segment's end (`EncoderCore::end_segment`), where no host
|
||||
//! step may follow before the commands after it that read the bytes; a rotated texture's, a
|
||||
//! heap's two-plane or tiled texture's, a heap's depth or stencil texture's; and a copy back into
|
||||
//! the runtime's own memory (a `Shared` buffer's): each copies back as before
|
||||
//! (`docs/FAST-PATHS.md`, known gaps).
|
||||
//! heap's two-plane or tiled texture's, a heap's depth or stencil texture's; a merge through a
|
||||
//! copy (`shadow_merge.rs`: a texture's first byte inside a word, through a staging buffer, or
|
||||
//! with bytes in its tail); and a copy back or merge into the runtime's own memory (a `Shared`
|
||||
//! buffer's): each goes as before (`docs/FAST-PATHS.md`, known gaps). A shadowed texture whose
|
||||
//! merges go on the host opens no run of passes (`pass_runs.rs`): each pass merges as its encoder
|
||||
//! ends.
|
||||
|
||||
use super::buffer::Buffer;
|
||||
use super::encoder::RecordedSegment;
|
||||
use super::error::{internal, Error};
|
||||
use super::in_place::{Access, InPlaceChecks, PagesClass, RowEnds, Verdict};
|
||||
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::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
/// The alignment of each edge's bytes in the region: a multiple of every texel's size a copy
|
||||
/// into it takes (1, 2, 4, 8 or 16 bytes), as `bufferOffset` must be.
|
||||
@@ -414,26 +429,99 @@ pub(super) struct SpliceDrain {
|
||||
pieces: Vec<(u64, u64, u64)>,
|
||||
}
|
||||
|
||||
/// The CPU's parts of an encoder's copies back spliced at one place (`Deferred::ShadowSplice`):
|
||||
/// held by its segment until its command buffer completes.
|
||||
pub(super) struct ShadowSplices(pub(super) Vec<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.
|
||||
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<ShadowMerge>,
|
||||
/// The host addresses of the kept and the changed parts' first bytes.
|
||||
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)>,
|
||||
}
|
||||
|
||||
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.
|
||||
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),
|
||||
)
|
||||
};
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a host step writes into the truth's pages for one copy of a shadow.
|
||||
pub(super) enum HostWrite {
|
||||
/// A copy back's spliced edges.
|
||||
Splice(SpliceDrain),
|
||||
/// A merge's changed bytes.
|
||||
Merge(MergeDrain),
|
||||
}
|
||||
|
||||
/// The CPU's parts of an encoder's copies back spliced and merges on the host at one place
|
||||
/// (`Deferred::ShadowSplice`): held by its segment until its command buffer completes.
|
||||
pub(super) struct ShadowSplices(pub(super) Vec<HostWrite>);
|
||||
|
||||
impl ShadowSplices {
|
||||
/// The host step, once every batch submitted before its own completed, the GPU's copies into
|
||||
/// the regions among them (each batch ends with the barrier to the host): each piece's bytes
|
||||
/// copied from its region into the pages, a byte at a time as the CPU's stores go. It records
|
||||
/// nothing.
|
||||
pub(super) fn drain(&self) -> RecordedSegment {
|
||||
for drain in &self.0 {
|
||||
for &(host, length, at) in &drain.pieces {
|
||||
// SAFETY: the piece's host bytes lie in the truth's pages (its texels' bytes,
|
||||
// `image` and `staged`), which stay mapped while the command buffer runs (its
|
||||
// segment's uses name the buffer, whose pages it holds until it completes); the
|
||||
// region is memory of the runtime's own, apart from them, and no command writes
|
||||
// it any more.
|
||||
unsafe { drain.region.copy_out(at, host as *mut u8, length) };
|
||||
/// the regions and scratches among them (each batch ends with the barrier to the host): each
|
||||
/// splice's pieces copied from its region into the pages, and each merge's changed bytes
|
||||
/// stored there; each of the CPU's stores changes the bytes it stores alone. It records
|
||||
/// nothing; the merges' time is counted on `device`.
|
||||
pub(super) fn drain(&self, device: &Device) -> RecordedSegment {
|
||||
let started = Instant::now();
|
||||
let mut merges = 0;
|
||||
for write in &self.0 {
|
||||
match write {
|
||||
HostWrite::Splice(drain) => {
|
||||
for &(host, length, at) in &drain.pieces {
|
||||
// SAFETY: the piece's host bytes lie in the truth's pages (its texels'
|
||||
// bytes, `image` and `staged`), which stay mapped while the command
|
||||
// buffer runs (its segment's uses name the buffer, whose pages it holds
|
||||
// until it completes); the region is memory of the runtime's own, apart
|
||||
// from them, and no command writes it any more.
|
||||
unsafe { drain.region.copy_out(at, host as *mut u8, length) };
|
||||
}
|
||||
}
|
||||
HostWrite::Merge(drain) => {
|
||||
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);
|
||||
}
|
||||
RecordedSegment::submitted(Vec::new())
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
//! A shadow's copy back into host pages imported as dma-bufs keeps the bytes the CPU writes
|
||||
//! beside its texels in their lines of memory while it runs (`shadow_splice.rs`). On the Iris Xe
|
||||
//! (ANV) a copy of texels into a buffer's rows writes back the 64-byte line that holds each row's
|
||||
//! last texels whole, putting back older values over the CPU's writes to the row's padding there
|
||||
//! (docs/FAST-PATHS.md, **Known gaps**): the control below, a blit into the rows, loses some on
|
||||
//! every run there; a shadow's copy back, spliced, loses none.
|
||||
//! A shadow's copy back and merge into host pages imported as dma-bufs keep the bytes the CPU
|
||||
//! writes beside its texels in their lines of memory while they run (`shadow_splice.rs`). On the
|
||||
//! Iris Xe (ANV) a copy of texels into a buffer's rows writes back the 64-byte line that holds
|
||||
//! each row's last texels whole, putting back older values over the CPU's writes to the row's
|
||||
//! padding there (docs/FAST-PATHS.md, **Known gaps**): the control below, a blit into the rows,
|
||||
//! loses some on every run there; a shadow's copy back, spliced, and its merge, on the host, lose
|
||||
//! none.
|
||||
//!
|
||||
//! The shape is a guest's render target: a 34x34 `RGBA16Float` texture that reads, writes and
|
||||
//! renders, rows 512 bytes apart from the first byte of a no-copy buffer of 32768 bytes over a
|
||||
@@ -25,20 +26,23 @@
|
||||
//! - `clear`: a pass that clears the shadowed target and stores it (it replaces every texel: a
|
||||
//! 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), its losses printed.
|
||||
//! 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.
|
||||
//! - `idle`: the thread alone, which must find none.
|
||||
//!
|
||||
//! The device's policy runs no check of its own, so its verdicts stay unanswered and every copy
|
||||
//! back over the pages is spliced. A second test gives such a device the verdicts the device's
|
||||
//! check measured under the default policy, and finds a copy back spliced exactly where they
|
||||
//! splice: copied back as before where both the copies and the shader writes passed.
|
||||
//! The device's policy runs no check of its own, so its verdicts stay unanswered: every copy back
|
||||
//! over the pages is spliced, and every merge goes on the host. A second test gives such a device
|
||||
//! 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.
|
||||
|
||||
use super::blit_holds::{options, WAIT};
|
||||
use super::encoder_holds::{bytes_of, library};
|
||||
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};
|
||||
use crate::in_place::{Access, PagesClass, RowEnds, Verdict};
|
||||
use crate::{
|
||||
BlitOption, Buffer, ClearColor, CommandQueue, Device, HostMemory, IoSurfacePlane, LoadAction,
|
||||
Origin, PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, Size,
|
||||
@@ -62,6 +66,8 @@ const LENGTH: u64 = 32768;
|
||||
const LINE: u64 = 64;
|
||||
/// The command buffers of each kind of round.
|
||||
const ROUNDS: usize = 300;
|
||||
/// The command buffers each arm of the cost test times.
|
||||
const COST_ROUNDS: usize = 30;
|
||||
/// How long the second test waits for the device's check.
|
||||
const CHECK_WAIT: Duration = Duration::from_secs(120);
|
||||
|
||||
@@ -251,11 +257,13 @@ 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 +{}, 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), 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_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,
|
||||
@@ -269,13 +277,18 @@ fn spliced(before: &WorkCounts, after: &WorkCounts) -> u64 {
|
||||
after.shadow_copies_back_spliced - before.shadow_copies_back_spliced
|
||||
}
|
||||
|
||||
/// A no-copy buffer of [`LENGTH`] bytes over `ram`'s pages, imported as dma-bufs.
|
||||
fn over_dma_bufs(device: &Device, ram: &Ram, calls: &Arc<AtomicUsize>) -> Buffer {
|
||||
/// The merges on the host between two counts.
|
||||
fn on_host(before: &WorkCounts, after: &WorkCounts) -> u64 {
|
||||
after.shadow_merges_on_host - before.shadow_merges_on_host
|
||||
}
|
||||
|
||||
/// A no-copy buffer of `length` bytes over `ram`'s pages, imported as dma-bufs.
|
||||
fn over_dma_bufs(device: &Device, ram: &Ram, calls: &Arc<AtomicUsize>, length: u64) -> Buffer {
|
||||
// SAFETY: the view outlives the buffer, and the source makes dma-bufs of its pages.
|
||||
let buffer = unsafe {
|
||||
device.new_buffer_with_bytes_no_copy(
|
||||
HostMemory::with_dma_buf(ram.pointer(0), ram.source(calls)),
|
||||
LENGTH,
|
||||
length,
|
||||
ResourceOptions::default(),
|
||||
None,
|
||||
)
|
||||
@@ -288,10 +301,10 @@ fn over_dma_bufs(device: &Device, ram: &Ram, calls: &Arc<AtomicUsize>) -> Buffer
|
||||
buffer
|
||||
}
|
||||
|
||||
/// The shape's descriptor (the module docs).
|
||||
fn shape() -> TextureDescriptor {
|
||||
/// The shape's descriptor (the module docs), of `width` x `height` texels.
|
||||
fn shape((width, height): (u64, u64)) -> TextureDescriptor {
|
||||
let mut descriptor =
|
||||
TextureDescriptor::texture_2d(PixelFormat::RGBA16Float, WIDTH, HEIGHT, false);
|
||||
TextureDescriptor::texture_2d(PixelFormat::RGBA16Float, width, height, false);
|
||||
descriptor.usage =
|
||||
TextureUsage::SHADER_READ | TextureUsage::SHADER_WRITE | TextureUsage::RENDER_TARGET;
|
||||
descriptor
|
||||
@@ -305,13 +318,14 @@ fn source(device: &Device) -> Texture {
|
||||
device.new_texture(&d).unwrap()
|
||||
}
|
||||
|
||||
/// The texture of the shape over `buffer`, in `form` (`buffer` or `plane`), a shadow.
|
||||
fn target(buffer: &Buffer, form: &str) -> Texture {
|
||||
let descriptor = shape();
|
||||
/// The texture of the shape over `buffer`, in `form` (`buffer` or `plane`), a shadow: of
|
||||
/// `width` x `height` texels, rows `row` bytes apart.
|
||||
fn target(buffer: &Buffer, form: &str, (width, height, row): (u64, u64, u64)) -> Texture {
|
||||
let descriptor = shape((width, height));
|
||||
let texture = match form {
|
||||
"buffer" => buffer.new_texture(&descriptor, 0, ROW).unwrap(),
|
||||
"buffer" => buffer.new_texture(&descriptor, 0, row).unwrap(),
|
||||
_ => (buffer
|
||||
.new_texture_with_iosurface_plane(&descriptor, IoSurfacePlane::new(0, ROW, false)))
|
||||
.new_texture_with_iosurface_plane(&descriptor, IoSurfacePlane::new(0, row, false)))
|
||||
.unwrap(),
|
||||
};
|
||||
// SAFETY: the handle is only compared, while the texture lives.
|
||||
@@ -341,7 +355,7 @@ fn a_shadow_s_copy_back_keeps_the_cpu_s_writes_beside_its_texels() {
|
||||
let file = (LENGTH as usize).next_multiple_of(host_page());
|
||||
let ram = Ram::new(file, 0, file);
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let buffer = over_dma_bufs(&device, &ram, &calls);
|
||||
let buffer = over_dma_bufs(&device, &ram, &calls, LENGTH);
|
||||
let base = ram.pointer(0).as_ptr().addr();
|
||||
let source = source(&device);
|
||||
|
||||
@@ -358,7 +372,7 @@ fn a_shadow_s_copy_back_keeps_the_cpu_s_writes_beside_its_texels() {
|
||||
});
|
||||
println!("{TEST} on {name}: copy (the control): {ROUNDS} rounds in {took:?}: {copied:?}");
|
||||
for form in ["buffer", "plane"] {
|
||||
let target = target(&buffer, form);
|
||||
let target = target(&buffer, form, (WIDTH, HEIGHT, ROW));
|
||||
for kind in [Kind::Clear, Kind::Draw] {
|
||||
let before = device.work_counts();
|
||||
let (tally, took) = beside(base, || {
|
||||
@@ -371,20 +385,22 @@ fn a_shadow_s_copy_back_keeps_the_cpu_s_writes_beside_its_texels() {
|
||||
"{TEST} on {name}: {form} {kind:?}: {ROUNDS} rounds in {took:?}: {tally:?}; {}",
|
||||
counted(&before, &after)
|
||||
);
|
||||
if let Kind::Clear = kind {
|
||||
assert_eq!(
|
||||
(tally.hot, tally.cold, tally.past),
|
||||
(0, 0, 0),
|
||||
"{TEST}: a {form} texture's copies back put back no byte the CPU wrote \
|
||||
beside its texels (the control put back {}): {tally:?}",
|
||||
copied.hot + copied.cold + copied.past
|
||||
);
|
||||
assert!(
|
||||
spliced(&before, &after) >= ROUNDS as u64,
|
||||
"{TEST}: every {form} copy back was spliced: {}",
|
||||
counted(&before, &after)
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
(tally.hot, tally.cold, tally.past),
|
||||
(0, 0, 0),
|
||||
"{TEST}: a {form} texture's {kind:?} rounds put back no byte the CPU wrote beside \
|
||||
its texels (the control put back {}): {tally:?}",
|
||||
copied.hot + copied.cold + copied.past
|
||||
);
|
||||
let (made, what) = match kind {
|
||||
Kind::Clear => (spliced(&before, &after), "copy back was spliced"),
|
||||
_ => (on_host(&before, &after), "merge went on the host"),
|
||||
};
|
||||
assert!(
|
||||
made >= ROUNDS as u64,
|
||||
"{TEST}: every {form} {what}: {}",
|
||||
counted(&before, &after)
|
||||
);
|
||||
}
|
||||
}
|
||||
drop(buffer);
|
||||
@@ -431,27 +447,107 @@ fn a_copy_back_splices_by_the_device_s_check() {
|
||||
let file = (LENGTH as usize).next_multiple_of(host_page());
|
||||
let ram = Ram::new(file, 0, file);
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let buffer = over_dma_bufs(&device, &ram, &calls);
|
||||
let buffer = over_dma_bufs(&device, &ram, &calls, LENGTH);
|
||||
let source = source(&device);
|
||||
for form in ["buffer", "plane"] {
|
||||
let target = target(&buffer, form);
|
||||
let before = device.work_counts();
|
||||
round(&queue, Kind::Clear, (&target, &source, &buffer), &state, 0);
|
||||
let after = device.work_counts();
|
||||
println!(
|
||||
"{TEST} on {name}: the check's verdicts for rows that end inside a line {measured:?}, \
|
||||
so spliced {splices}: {form} Clear: {}",
|
||||
counted(&before, &after)
|
||||
);
|
||||
assert_eq!(
|
||||
spliced(&before, &after) > 0,
|
||||
splices,
|
||||
"{TEST}: a {form} copy back spliced as the verdicts {measured:?} say: {}",
|
||||
counted(&before, &after)
|
||||
);
|
||||
let target = target(&buffer, form, (WIDTH, HEIGHT, ROW));
|
||||
for kind in [Kind::Clear, Kind::Draw] {
|
||||
let before = device.work_counts();
|
||||
round(&queue, kind, (&target, &source, &buffer), &state, 0);
|
||||
let after = device.work_counts();
|
||||
println!(
|
||||
"{TEST} on {name}: the check's verdicts for rows that end inside a line \
|
||||
{measured:?}, so spliced {splices}: {form} {kind:?}: {}",
|
||||
counted(&before, &after)
|
||||
);
|
||||
let made = match kind {
|
||||
Kind::Clear => spliced(&before, &after),
|
||||
_ => on_host(&before, &after),
|
||||
};
|
||||
assert_eq!(
|
||||
made > 0,
|
||||
splices,
|
||||
"{TEST}: a {form} {kind:?}'s write back as the verdicts {measured:?} say: {}",
|
||||
counted(&before, &after)
|
||||
);
|
||||
}
|
||||
}
|
||||
drop(buffer);
|
||||
drop(queue);
|
||||
drop(device);
|
||||
drop(ram);
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[test]
|
||||
fn costs_of_a_write_back_spliced_or_not() {
|
||||
if !udmabuf_openable(TEST) {
|
||||
return;
|
||||
}
|
||||
let scratch = Scratch::new();
|
||||
let device = device(&scratch.0);
|
||||
let name = device.name();
|
||||
if !lists_dma_buf_route(&device) {
|
||||
println!("{TEST}: {name} lists no dma-buf route: not run");
|
||||
return;
|
||||
}
|
||||
let queue = device.new_command_queue().unwrap();
|
||||
let state = drawing(&device);
|
||||
let checks = &device.shared().in_place;
|
||||
for (width, height, row) in [(WIDTH, HEIGHT, ROW), (1920, 1080, 15360)] {
|
||||
let length = row * height;
|
||||
let file = (length as usize).next_multiple_of(host_page());
|
||||
let ram = Ram::new(file, 0, file);
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let buffer = over_dma_bufs(&device, &ram, &calls, length);
|
||||
let target = target(&buffer, "plane", (width, height, row));
|
||||
for verdict in [Verdict::Pending, Verdict::Passed] {
|
||||
for access in [Access::Copies, Access::Writes] {
|
||||
checks.set(PagesClass::DmaBuf, access, RowEnds::InLines, verdict);
|
||||
}
|
||||
let splices = crate::shadow_splice::splices(checks, PagesClass::DmaBuf);
|
||||
for kind in [Kind::Clear, Kind::Draw] {
|
||||
// Warmed: the pipelines, the scratch and the arena's chunks made.
|
||||
for i in 0..3 {
|
||||
round(&queue, kind, (&target, &target, &buffer), &state, i);
|
||||
}
|
||||
let before = device.work_counts();
|
||||
let mut took: Vec<Duration> = (0..COST_ROUNDS)
|
||||
.map(|i| {
|
||||
let start = Instant::now();
|
||||
round(&queue, kind, (&target, &target, &buffer), &state, i);
|
||||
start.elapsed()
|
||||
})
|
||||
.collect();
|
||||
let after = device.work_counts();
|
||||
took.sort();
|
||||
println!(
|
||||
"{TEST} COST on {name}: {width}x{height} rows {row} apart, {kind:?}, verdicts \
|
||||
{verdict:?} (spliced {splices}): median {:?} a command buffer over \
|
||||
{COST_ROUNDS}; {}",
|
||||
took[took.len() / 2],
|
||||
counted(&before, &after)
|
||||
);
|
||||
let (made, edges) = match kind {
|
||||
Kind::Clear => (spliced(&before, &after), row != 15360),
|
||||
_ => (on_host(&before, &after), true),
|
||||
};
|
||||
assert_eq!(
|
||||
made > 0,
|
||||
splices && edges,
|
||||
"{TEST}: {width}x{height} {kind:?} under {verdict:?}: {}",
|
||||
counted(&before, &after)
|
||||
);
|
||||
}
|
||||
}
|
||||
drop(target);
|
||||
drop(buffer);
|
||||
drop(ram);
|
||||
}
|
||||
}
|
||||
@@ -707,6 +707,8 @@ pub(crate) struct Counters {
|
||||
shadow_texels_copied_back: AtomicU64,
|
||||
shadow_copies_back_dispatched: AtomicU64,
|
||||
shadow_copies_back_spliced: AtomicU64,
|
||||
shadow_merges_on_host: AtomicU64,
|
||||
shadow_merge_host_nanos: AtomicU64,
|
||||
shadow_copies_in_dispatched: AtomicU64,
|
||||
shadow_keeps_from_staging: AtomicU64,
|
||||
shadow_merge_copies_dispatched: AtomicU64,
|
||||
@@ -5662,6 +5664,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) {
|
||||
self.shadow_merges_on_host
|
||||
.fetch_add(merges, Ordering::Relaxed);
|
||||
self.shadow_merge_host_nanos
|
||||
.fetch_add(nanos, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// An encoder recorded a merged shadowed texture's copy in and keep as one dispatch
|
||||
/// (`shadow_copy_in.rs`).
|
||||
pub(crate) fn shadow_copy_in_dispatched(&self) {
|
||||
@@ -11070,6 +11081,14 @@ pub struct WorkCounts {
|
||||
/// lines it shares with bytes beside them, a byte at a time, as the CPU's stores go, so the
|
||||
/// CPU's writes to those bytes stay.
|
||||
pub shadow_copies_back_spliced: u64,
|
||||
/// The merges of shadowed textures over a no-copy buffer's host pages made on the host, on a
|
||||
/// 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.
|
||||
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,
|
||||
/// 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
|
||||
@@ -13426,6 +13445,8 @@ impl Device {
|
||||
.shadow_copies_back_dispatched
|
||||
.load(Ordering::Relaxed),
|
||||
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_copies_in_dispatched: counters
|
||||
.shadow_copies_in_dispatched
|
||||
.load(Ordering::Relaxed),
|
||||
|
||||
Vendored
+1
-1
@@ -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 = 2431;
|
||||
pub const RUNTIME_VERSION: u32 = 2432;
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -3668,6 +3668,7 @@ field metal2vulkan-runtime::WorkCounts.shadow_keeps_from_staging pub shadow_keep
|
||||
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
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_merge_host_nanos pub shadow_merge_host_nanos: u64
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_merge_kept_images_followed pub shadow_merge_kept_images_followed: u64
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_merge_kept_images_live pub shadow_merge_kept_images_live: u64
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_merge_kept_images_made pub shadow_merge_kept_images_made: u64
|
||||
@@ -3676,6 +3677,7 @@ field metal2vulkan-runtime::WorkCounts.shadow_merge_scratches_zeroed pub shadow_
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_merge_words_examined pub shadow_merge_words_examined: u64
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_merges_fetched pub shadow_merges_fetched: u64
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_merges_kept_in_images pub shadow_merges_kept_in_images: u64
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_merges_on_host pub shadow_merges_on_host: u64
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_texels_bounded_copied_in pub shadow_texels_bounded_copied_in: u64
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_texels_copied_back pub shadow_texels_copied_back: u64
|
||||
field metal2vulkan-runtime::WorkCounts.shadow_texels_copied_in pub shadow_texels_copied_in: u64
|
||||
|
||||
|
Can't render this file because it is too large.
|
+4
-2
@@ -2512,8 +2512,10 @@ 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`; 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 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
|
||||
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
|
||||
|
||||
+12
-7
@@ -910,13 +910,18 @@ driver's. Each is open work.
|
||||
does not, where the device's check of those pages finds copies or shader writes writing such
|
||||
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`). Still lost, by the
|
||||
same write-back: a CPU write beside the texels a shadow's merge stores (`shadow_merge.rs`), and
|
||||
beside a copy back 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, or into the
|
||||
runtime's own memory (a `Shared` buffer's), each of which still writes whole rows from the
|
||||
GPU. A texture that
|
||||
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
|
||||
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
|
||||
(a texture's first byte inside a word, through a staging buffer, or with bytes in its tail), or
|
||||
into the runtime's own memory (a `Shared` buffer's), each of which still stores from the GPU.
|
||||
A texture that
|
||||
renders over host pages whose rows end inside a line, with the rows' padding free, takes the
|
||||
image in place where the device's check finds its copies losing those bytes too, over its kind
|
||||
of pages or over another kind whose pages lay in memory of a type of the same property flags
|
||||
|
||||
Reference in new issue
Block a user